JavaScript for WordPress Forums Vanilla JavaScript 1.2.14 – Switch Statements

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #6830
    Thorsten Frommen
    Participant

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

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

    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.

    Cheers,
    Thorsten

    #6982
    Zac Gordon
    Keymaster

    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.