-2

Hello I'm using node js v12.10 and the following code don´t work properly

let number = 0x10
switch(number){    
    case 0x10:
        console.log('0x10')        
    case 0x16:
        console.log('0x16')
        break
    default:
        console.log(number)
        break
}

the output is: 0x10 0x16

I know that I forget the break instruction on case 0x10, but still the case 0x16 should not be executed. Is that a bug?

5
  • 3
    that's the default behavior. Commented Jul 16, 2020 at 3:40
  • 1
    Reading the documentation is always useful. Commented Jul 16, 2020 at 3:46
  • 1
    if you won't provide break statement it will execute the next case until it find the break statement Commented Jul 16, 2020 at 3:47
  • 1
    Welcome to StackOverflow. Please try searching before posting a new query. Refer the answers to this question for understanding on the working of Switch-Case - stackoverflow.com/questions/54377350/… Commented Jul 16, 2020 at 3:51
  • "The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement. " - quoted from MDN docs Commented Jul 16, 2020 at 3:56

2 Answers 2

2

Yes, it's a feature not a bug. It is very useful when you want to group several cases like so:

const errorcode = 'EADDRINUSE'
switch(errorcode){    
    case 'EADDRINUSE':
    case 'ERR_CONNECTION_REFUSED':
        console.log('connection error')
        break
    case '502':
    case '404':
        console.log('server error')
    default:
        console.log('general error')
        break
}
Sign up to request clarification or add additional context in comments.

Comments

0

That's a language feature. It's sometimes called 'switch statement fallthrough'.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.