0% found this document useful (0 votes)
32 views

The Javascript Switch Statement: Syntax

The JavaScript Switch Statement allows code to select one of many code blocks to execute based on the value of an expression. It evaluates the switch expression once and compares it to the values in each case, executing the block for a matching case. For example, a switch statement can use the number returned from getDay() to set the variable day to the weekday name.

Uploaded by

Alex Mociran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

The Javascript Switch Statement: Syntax

The JavaScript Switch Statement allows code to select one of many code blocks to execute based on the value of an expression. It evaluates the switch expression once and compares it to the values in each case, executing the block for a matching case. For example, a switch statement can use the number returned from getDay() to set the variable day to the weekday name.

Uploaded by

Alex Mociran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

The JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.

Example

The getDay() method returns the weekday as a number between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

This example uses the weekday number to calculate the weekday name:

switch (new Date().getDay()) {


case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

The result of day will be:

Thursday

You might also like