Is it Necessary to Add break to "default" in JavaScript switch Statement?

If the default clause appears at the end of the switch statement, then there's no need to add break to the default clause, as there are no clauses after the default clause and the code cannot fall-through. For example:

const expression = 'non-existent';

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

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

  default:
    console.log('default');
}

// output: 'default'

It could be, however, that the default clause appears in a different place than at the end of a switch statement. In such a case, if you don't add a break after the default clause, then it will fall-through to other cases that appear after it. For example:

const expression = 'non-existent';

switch (expression) {
  case 'foo':
    console.log('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.