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'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.