Search⌘ K

Switch statements

Explore how switch statements simplify complex if-else chains in JavaScript. Understand variable matching, the importance of break statements, and how to use default cases effectively. This lesson helps you write clearer conditional code by using switch statements.

We'll cover the following...

There is an abbreviated version for a long chain of if-else statement: the switch operator. Switch is like a telephone operator. It puts you through some code in case the correct value is stored in your variable. There is also a default line, saying “the number you have dialed is invalid”.

Node.js
function logLampColor( state ) {
switch( state ) {
case 1:
console.log( 'Red' );
break;
case 2:
console.log( 'Yellow' );
break;
case 3:
console.log( 'Green' );
break;
default:
console.log( 'Wrong lamp state' );
}
}
logLampColor( 1 );

Try this code ...