Unlock The Power Of The "Switch" Statement: A Comprehensive Guide

Unlock The Power Of The "Switch" Statement: A Comprehensive Guide

Hey, Awesome ones!

Welcome to my other blog about this JavaScript Blog Course. You can find it here↗️

In this blog, we are going to learn JavaScript Switch Statements.

What to wait?

lets-begin-samus-paulicelli.gif (498×494)

Yeah.. let's begin🚀

The "switch" statement

A switch statement is used to write small code and can replace multiple if & else if conditions.

Syntax:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
  • The value of expression is checked for strict equality to the value from the first case (that is, x) then to the second (y) and so on.

  • If equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break (or until the end of switch).

  • If no case is matched then the default code is executed (if it exists).

Example:

let a = 2 + 3;

switch (a) {
  case 3:
    alert( 'Not the correct value' );
  case 4:
    alert( 'Move ahead!' );
  case 5:
    alert( 'Correct' );
  default:
    alert( "We can't find the number" );
}

Nesting of “case”

case which share the same code can be grouped.

Code:

let a = 3;

switch (a) {
  case 4:
    alert('Right!');
    break;

  case 3: // (*) grouped two cases
  case 5:
    alert('Wrong!');
    alert("Why don't you take a math class?");
    break;

  default:
    alert('The result is strange. Really.');
}

Type Counts

let arg = prompt("Enter a value?");
switch (arg) {
  case '0':
  case '1':
    alert( 'One or zero' );
    break;

  case '2':
    alert( 'Two' );
    break;

  case 3:
    alert( 'Never executes!' );
    break;
  default:
    alert( 'An unknown value' );
}
  1. For 0, 1, the first alert runs.

  2. For 2 the second alert runs.

  3. But for 3, the result of the prompt is a string "3", which is not strictly equal === to the number 3. So we’ve got a dead code in case 3! The default variant will execute.

I hope you Understand and Love this Blog💖

Don't forget to support me by following this blog

Social Accounts:
Twitter & LinkedIn