
The JavaScript Switch assertion is a conditional management circulation assertion. It is extremely helpful for creating conditional blocks with numerous clauses.
This article is a tutorial on the swap assertion and the way to use it. We may even evaluate it to different conditional constructs, if statements, and ternary operators so you might know when to use every.
Table of Contents
What Is the Switch Statement in JavaScript?
The JavaScript Switch Statement is used to resolve which department of code to execute primarily based on the worth of an expression. It is one among the two conditional statements in JavaScript.
The first being the if-statement and the second being the ternary operator. It capabilities very like the two however has completely different nuances, making it ultimate for some instances. In this text, we’re going to discover all that.
How to Use JavaScript Switch Statement
In this portion of the article, I’ll clarify the JavaScript Switch Statement and the way to use it. I’ll use code examples, so you will want a JavaScript compiler to comply with alongside. The best one to use is this online JavaScript Compiler. Alternatively, you may examine our article on the finest on-line JavaScript IDEs.
General Syntax
The basic syntax for a swap assertion is as follows:
swap(<expression>) {
case <worth 1>:
<statements>
break;
case <worth 2>:
<statements>
break;
default:
<statements>
}
The swap key phrase marks the starting of a JavaScript swap block. Inside the parentheses, you place in any JavaScript expression. An expression is something that evaluates to a price. For instance, literals resembling strings or numbers, variables, or perform calls.
Next, we add the physique of the swap assertion between curly braces. The physique is made up of a number of instances. Each case has a price and a gaggle of statements. If the expression between the parentheses equals a case’s worth, then that case’s statements are executed.
For every case, we will add the break key phrase. Adding this phrase is solely non-obligatory. If you add it, JavaScript breaks out of the swap block when it encounters it. If it’s not current, JavaScript will proceed to run all the instances after it. This is called fall via. Unless you need to make the most of fall via, it’s endorsed that you simply add the break key phrase.
The final key phrase to be aware of is the default key phrase. This case matches any worth of the expression between the parentheses.
Examples
This part will exhibit completely different examples of utilizing the swap assertion.
#1. With Fallthrough
Here is an instance of utilizing the swap assertion with out the break key phrase. The function of that is to exhibit fallthrough.
In this instance, we’re writing code to deal with completely different HTTP standing codes:
const statusCode = <insert standing code right here>
swap (statusCode) {
case 200:
console.log('OK');
case 301:
console.log('Redirect');
case 403:
console.log('Forbidden');
case 404:
console.log('Not Found');
case 500:
console.log('Internal Server Error')
}
In the code snippet above, we examine if a price equals a specific standing code, then print out a message describing the standing code.
Observe what occurs whenever you set the standing code to 403.

After matching the 403 instances, all the instances following it had been additionally matched. This is known as fallthrough. This just isn’t ultimate, as we frequently like to match one case. This bizarre quirk of JavaScript is the cause why it’s crucial to add the break key phrase.
#2. Without Fallthrough
To keep away from fallthrough, we add the break key phrase at the finish of every case. The following instance demonstrates what occurs whenever you do.
const statusCode = <insert a standing code right here>
swap (statusCode) {
case 200:
console.log('OK');
break;
case 301:
console.log('Redirect');
break;
case 403:
console.log('Forbidden');
break;
case 404:
console.log('Not Found');
break;
case 500:
console.log('Internal Server Error')
break;
}
And whenever you run the code above with the standing code 403, you get this.

As you may see, the code now matches only one case and avoids fallthrough.
#3. Useful Fallthrough
That stated, it can be crucial to notice that fallthrough could be helpful in some instances. Consider the following instance the place we wish to examine if an individual is shifting horizontally or vertically primarily based on directional enter.
const path = '<enter path right here>'
swap(path) {
case 'left':
case 'proper':
console.log('horizontal motion');
break;
case 'up':
case 'down':
console.log('horizontal motion');
break;
}
If you set the path to left and run the code above, that is the consequence:

And whenever you set the path to proper, you continue to get the identical consequence:

This is as a result of when the left case matches, it falls via to the proper case and prints ‘horizontal movement’. But since there’s a break key phrase, it doesn’t fall via to the up case. When the proper case matches, it runs the statements in the proper case and breaks.
Therefore, ‘horizontal movement’ is displayed when the path is both left or proper. Therefore, fallthrough permits you to create OR logic in your code.
#4. Matching Ranges
The JavaScript swap assertion checks if the worth of a case equals the worth of the expression. If so, it executes the statements in that case. However, you might typically need to examine if a price is in a given vary. Matching ranges could be difficult, however the code snippet under demonstrates a workaround.
In the instance under, we’re implementing a program that, given a mark, prints out the grade. For instance, if the mark is above 90, the program will print A+. If it’s above 80 however lower than 90, it should print A, and so forth.
To do that, I’ve put the expression true inside the parentheses. Then, the worth of every case has been outlined as a logical operation that can solely be true if the mark is in the vary for that case. For instance, the final case mark >= 90
will solely be true if the mark is bigger than or equal to 90. Therefore, it should match the worth of the expression since true
equals true
.
const mark = <substitute with any mark>;
swap (true) {
case mark >= 50 && mark < 60:
console.log('D');
break;
case mark >= 60 && mark < 70:
console.log('C');
break;
case mark >= 70 && mark < 80:
console.log('B');
break;
case mark >= 80 && mark < 90:
console.log('A')
break;
case mark >= 90:
console.log('A+')
break;
default:
console.log('<50')
}
The output of the code above when the mark is about to 80 is:

And when the mark is about to 95:

And when the mark is 45:

Lexical Scoping
The statements inside a case in a swap will not be lexically scoped. This means variables outlined in a single case shall be accessible in a distinct case. This is vital to know as you write swap blocks the place a couple of case shall be matched. Here’s an instance to clarify this higher:
swap (true) {
case true:
let num = 10
case true:
console.log(num);
}
In the code snippet above, each instances match. In the first case, we outline the num variable; in the second, we entry its worth. We received’t get any errors, as you may see from the screenshot under:

Difference Between a Switch Statement and Other Conditionals
A Switch assertion is best suited to situations the place you’re testing for a number of situations. An if-statement is suited to situations the place you’re testing 2 or 3 situations. A ternary operator is barely good for situations whenever you need to categorical a conditional as a one-liner.
For brevity, you must decide to write ternary operators first. If it’s not possible to categorical the logic in a ternary operator, then you might use an if-statement. But if that’s not attainable, you go for the swap assertion.
Conclusion
This article lined the swap assertion, how to use it, and its bizarre quirks. We additionally lined when to use it.
Next, you might have considered trying to polish up on JavaScript utilizing these JavaScript cheat sheets.