JavaScript switch case Statement

You are Here:

JavaScript switch case Statement

The switch case statement executes a block of code depending on different cases.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var num = 1; var txt = ""; switch(num){ case 0: txt = "zero"; break; case 1: txt = "One"; break; case 2: txt = "Two"; break; } x.innerHTML = txt; </script> </body> </html>

Syntax

switch(expression){ case x: // code block case y: // code block default: // code block }

switch case with default Keyword

Note: The statements under default will be executed when no match is found in cases.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var num = 5; var txt = ""; switch(num){ case 0: txt = "zero"; break; case 1: txt = "One"; break; case 2: txt = "Two"; break; default: txt = "None of these"; } x.innerHTML = txt; </script> </body> </html>

switch case without break Statement

Note: If there is no break statement then the cases following the matched case including default will get executed.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var num = 1; var txt = ""; switch(num){ case 0: txt += "zero"; case 1: txt += "One"; case 2: txt += "Two"; default: txt += "None of these"; } x.innerHTML = txt; </script> </body> </html>

Switch with Multiple Cases

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var num = 1; var txt = ""; switch(num){ case 0: case 1: case 2: txt = "num is less than or equal to 2"; break; case 3: case 4: case 5: txt = "num is greater than 2 but lesser than 6"; break; default: txt += "Case not found"; } x.innerHTML = txt; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author