JavaScript for WordPress Forums Vanilla JavaScript 1.2.14 – Switch Statements

This topic contains 1 reply, has 2 voices, and was last updated by  Zac Gordon 3 years, 5 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #6830

    Thorsten Frommen

    Although one wouldn’t see code like this very often, it is possible to implement the exact same functionality of and using switch.
    The trick is to pass true to the switch:

    switch ( true ) {
      case 'admin' === user.role && 'zgordon' === user.username:
        console.log( 'Show Dashboard' );
      case 'admin' === user.role && 'dev' === user.username:
        console.log( 'Show Source' );
      case 'editor' === user.role && '' !== user.twitter:
        console.log( 'Please share this post!' );

    See this JS Bin.

    Again, you won’t see this very often, however, I wanted to make aware of this as the statement You could not do this with a switch statement is just not correct.



    Zac Gordon

    Thanks Thorsten! Good point this is technically possible, although according to the WordPress coding standards it would not be a valid use for a Switch statement.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.