Chris
Chris

Reputation: 3129

Difference is Javascript switch statements

Someone took a look at my code the other day and said my switch statement was incorrectly written, yet I have never ran into a problem with how I have written it.

I took a look around in regards to switch statements, and indeed my switch statement are not written the same way, but similar except the placement of the break.

My switch statement is this

switch(val){
    case 'Add':{

    }break;
    case 'Edit':{

    }break;
    case 'Save':{

    }break;
    case 'Cancel':{

    }break;
    default:{

    }break;
}

and I took a look at Javascript Switch and it showed a statement like this

const action = 'say_hello';
switch (action) {
  case 'say_hello': {
    let message = 'hello';
    console.log(message);
    break;
  }
  case 'say_hi': {
    let message = 'hi';
    console.log(message);
    break;
  }
  default: {
    console.log('Empty action received.');
    break;
  }
}

So my question is, given how I wrote my switch statement, what kind of repercussions could happen with how I wrote it compared to the other provided snippet? Does it technically matter where the placement of my breaks are?

Upvotes: 1

Views: 62

Answers (1)

deceze
deceze

Reputation: 522382

The {} are block statements and they are entirely superfluous, they don't really do anything. They are not required by the switch syntax. All they're doing in your case is restrict the scope of the let statements. Apart from that, there's no difference between:

{
  foo;
}
bar;

and:

{
  foo;
  bar;
}

Both will execute both statements one after the other.

Upvotes: 4

Related Questions