[Go to site: main page, start]

0% found this document useful (0 votes)
68 views7 pages

JavaScript Switch Case Explained

This document discusses the JavaScript switch case statement. It begins with an introduction explaining that a switch statement evaluates an expression and executes the code for the matching case. It then provides two examples of using switch statements: 1) to get the day of the week from a number, and 2) to get the number of days in a month based on the month and year. The document concludes by summarizing that switch statements make code more readable compared to complex if/else statements and use strict equality checks.

Uploaded by

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

JavaScript Switch Case Explained

This document discusses the JavaScript switch case statement. It begins with an introduction explaining that a switch statement evaluates an expression and executes the code for the matching case. It then provides two examples of using switch statements: 1) to get the day of the week from a number, and 2) to get the number of days in a month based on the month and year. The document concludes by summarizing that switch statements make code more readable compared to complex if/else statements and use strict equality checks.

Uploaded by

Muhammad Amir
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

JavaScript switch case

If this JavaScript tutorial saves you


hours of work, please whitelist it in
your ad blocker 😭 and

Donate Now
([Link]

to support us ❤️in paying for web


hosting and CDN to keep the site
running.
Summary: in this tutorial, you will learn how to use the JavaScript switch statement to execute a
block based on multiple conditions.

Introduction to the JavaScript switch case statement


The switch statement evaluates an expression , compares its result with case values, and
executes the statement associated with the matching case value.

The following illustrates the syntax of the switch statement:

switch (expression) {

case value1:

statement1;

break;

case value2:

statement2;

break;

case value3:

[Link] 1/7
29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

statement3;

break;

default:

statement;

How it works.

First, evaluate the expression inside the parentheses after the switch keyword.

Second, compare the result of the expression with the value1 , value2 , … in the case
branches from top to bottom. The switch statement uses the strict comparison ( === ).

Third, execute the statement in the case branch where the result of the expression equals
the value that follows the case keyword. The break ([Link]
statement exits the switch statement. If you skip the break statement, the code execution
falls through the original case branch into the next one. If the result of the expression does
not strictly equal to any value, the switch statement will execute the statement in the
default branch.

That the switch statement will stop comparing the expression ‘s result with the remaining case
values as long as it finds a match.

The switch statement is like the if…else…if ([Link] statement.


But it has more readable syntax.

The following flowchart illustrates the switch statement:

[Link] 2/7
29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

Start

Evaluate expressi...

true
value1 statement1

false

true
value2 statement2

false

true
value3 statement3

default statement

End
([Link]

content/uploads/2022/01/[Link])

In practice, you often use a  switch statement to replace a complex if...else...if statement to
make the code more readable.

Technically, the  switch statement is equivalent to the following   if...else...if statement:

if (expression === value1) {

statement1;

} else if (expression === value2) {

statement2;

} else if (expression === value3) {

[Link] 3/7
29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

statement3;

} else {

statement;

JavaScript switch case examples


Let’s take some examples of using the JavaScript switch statement.

1) Using JavaScript switch statement to get the day of the week

The following example uses the switch statement to get the day of the week based on a day
number:

let day = 3;

let dayName;

switch (day) {

case 1:

dayName = 'Sunday';

break;

case 2:

dayName = 'Monday';

break;

case 3:

dayName = 'Tuesday';

break;

case 4:

dayName = 'Wednesday';

break;

case 5:

dayName = 'Thursday';

break;

case 6:

[Link] 4/7
29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

dayName = 'Friday';

break;

case 7:

dayName = 'Saturday';

break;

default:

dayName = 'Invalid day';

[Link](dayName); // Tuesday

Output:

Tuesday

How it works.

First, declare the day variable that holds the day number and the day name variable (dayName).

Second, get the day of the week based on the day number using the switch statement. If the day is
1 , the day of the week is Sunday . If the day is 2 , the day of the week is Monday , and so on.

Third, output the day of the week to the console.

2) Using the JavaScript switch statement to get the day count based of a
month

The following example uses the switch statement to get the day count of a month:

let year = 2016;

let month = 2;

let dayCount;

switch (month) {

case 1:

[Link] 5/7
29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:

dayCount = 31;

break;

case 4:

case 6:

case 9:

case 11:

dayCount = 30;

break;

case 2:

// leap year

if ((year % 4 == 0 && !(year % 100 == 0)) || year % 400 == 0) {

dayCount = 29;

} else {

dayCount = 28;

break;

default:

dayCount = -1; // invalid month

[Link](dayCount); // 29

In this example, we have four cases:

If the month is 1, 3,5, 7, 8, 10, or 12, the number of days in a month is 31.

If the month is 4, 6, 9, or 11, the number of days in that month is 30.

[Link] 6/7
29/07/2022, 08:01 JavaScript switch case Statement with Practical Examples

If the month is 2, and the year is not the leap year, the number of days is 28. If the year is the leap
year, the number of days is 29.

If the month is not in the valid range (1-12), the default branch executes and sets the
dayCount variable to -1, which indicates the invalid month.

Summary

The switch statement evaluates an expression, compare its result with case values, and
execute the statement associated with the matching case.

Use the switch statement to rather than a complex if...else...if statement to make the
code more redable.

The switch statement uses the strict comparison ( === ) to compare the expression with the
case values.

[Link] 7/7

Common questions

Powered by AI

The switch statement is significant for determining the day count of each month as it provides an organized approach to map months to their respective day counts. It streamlines the decision-making process for each month number. The implementation specifically handles varying days in February by incorporating a leap year check within the 'case 2' block, allowing the program to dynamically decide between 28 and 29 days based on leap year computations. This logic integration within the switch case simplifies handling of complex conditions such as leap years .

The use of a default case in a switch statement acts as a catch-all for scenarios where none of the specified cases match the expression's value. This is particularly useful for handling unknown or unforeseen inputs, ensuring that the code can handle unexpected data gracefully rather than failing silently or behaving unpredictably. It provides a safety net that can either manage errors, log incidents, or assign a valid default operational outcome .

The switch statement first evaluates the expression within the parentheses next to the switch keyword. It then uses strict comparison (===) to match the expression's result against the case values from top to bottom. When a matching case is found, the corresponding statement is executed. If no matches are found, and there's a default case, the default case's statement is executed .

Leap year calculations are integrated into the switch statement by using logical conditions within the 'case 2' block. For February (month 2), the statement checks if the year is a leap year by determining if it is divisible by 4, but not 100, or divisible by 400. If true, February has 29 days; otherwise, it has 28 days. This demonstrates advanced conditional logic embedded within a switch statement to handle complex cases like leap years .

Strict comparison is used in JavaScript switch statements to ensure the evaluation takes into account both the value and the type of the expression being compared. This means that only values with identical type and content will trigger a case clause, which prevents unexpected type coercion outcomes. Consequently, case clauses must consider and match the specific data types along with the values to ensure the correct case is executed .

The execution process of a JavaScript switch statement can be likened to following a flowchart, where each condition is evaluated sequentially from top to bottom. Each 'case' in a switch statement corresponds to a decision branch in a flowchart, directing the flow based on the evaluated expression's outcome. Using this analogy, understanding the switch statement's functionality becomes more intuitive, as it visually represents the decision-making process, making it easier to foresee how each case is assessed and potentially executed .

The JavaScript switch statement improves code readability by providing a clearer structure, especially when dealing with multiple conditions. The syntax is more concise and easier to follow compared to a series of nested if-else-if statements. Its use is particularly advantageous when you need to evaluate the same expression against multiple potential cases, as this avoids repeated expression evaluation and leads to cleaner, more maintainable code .

Omitting a break statement in a JavaScript switch case structure causes the execution to "fall through," meaning that after executing the matched case, the program continues to execute statements in subsequent cases until it encounters a break statement or the end of the switch block. This can lead to unintended behavior if not properly handled .

The JavaScript switch case example for determining the day of the week demonstrates concise code structure by associating day numbers with day names directly within the switch statement. This removes the need for multiple if statements and reduces code clutter. Each day number from 1 to 7 is matched against a case, with a simple assignment of the corresponding day name, illustrating the clear mapping of input to output .

When no matching case value is found in a JavaScript switch statement, the statement executes the code in the 'default' branch if it exists. This is akin to an else block in an if-else if statement. In situations where no specific default handling is required, both structures end without executing any case-specific code .

You might also like