Typically, the default
clause appears at the end of a switch
statement, and is executed when none of the cases match the value of the provided expression:
switch (expression) { case 'foo': // ... break; case 'bar': // ... break; default: // ... break; }
default
clause can, however, be placed anywhere within the switch
statement, and will still be executed only in case none of the other cases match:
const expression = 'non-existent'; switch (expression) { case 'foo': console.log('foo'); break; default: console.log('default'); break; case 'bar': console.log('bar'); break; } // output: 'default'
If you don't add a break
after the default
, then it will fall-through if other cases appear after it (as shown in the following code):
const expression = 'non-existent'; switch (expression) { case 'foo': // ... break; default: console.log('default'); case 'bar': console.log('bar'); break; } // output: // 'default' // 'bar'
Hope you found this post useful. It was published . Please show your love and support by sharing this post.