0

I'm a little confused with the below code, it is printing step 3 to the console

let switch; 
switch('abc'){
  case('abc'): 
    switch = 'step 1';
  case('def'): 
    switch = 'step 2';
  default: 
    switch = 'step 3';
}
console.log(switch);
mkingmking
  • 41
  • 1
  • 8

2 Answers2

2

The problem is that you're missing the break statement that prevents it from executing subsequent code

let switch; 
switch('abc'){
  case('abc'): 
    switch = 'step 1';
    break;
  case('def'): 
    switch = 'step 2';
    break;
  default: 
    switch = 'step 3';
}
console.log(switch);

putting the console log into the swi9tch, hopefully that illustrates the point

switch ("abc") {
  case "abc":
    console.log("step 1 - no break");
  case "def":
    console.log("step 2 - no break");
  default:
    console.log("step 3 - no break");
}

switch ("abc") {
  case "abc":
    console.log("step 1");
    break;
  case "def":
    console.log("step 2");
    break;
  default:
    console.log("step 3");
}
Daniel
  • 34,125
  • 17
  • 102
  • 150
0

After adding break; statement, this code will still be ineffectual. You need to also add something like user input to make switch determine which case it will run.

mkingmking
  • 41
  • 1
  • 8