Should JavaScript switch Statement Always Contain a default Clause?

In JavaScript switch statement, the default clause is optional. Therefore, switch statements do not need to always contain a default clause. For example:

const expression = 'bar';

switch (expression) {
  case 'foo':
    console.log('foo');
    break;

  case 'bar':
    console.log('bar');
    break;
}

// output: 'bar'

If you do not provide a default clause, and no case matches the provided expression, then nothing within the switch statement is executed. For example:

const expression = 'non-existent';

switch (expression) {
  case 'foo':
    console.log('foo');
    break;

  case 'bar':
    console.log('bar');
    break;
}

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.