How to use switch in Javascript
By FoxLearn 12/18/2024 7:05:22 AM 87
In JavaScript, the `switch` statement is used to perform different actions based on various conditions, similar to a series of `if...else` statements.
Here's the basic syntax of a switch
statement:
switch (expression) { case value1: // code to be executed if expression matches value1 break; case value2: // code to be executed if expression matches value2 break; // add more cases if necessary default: // code to be executed if none of the above cases match break; }
The expression in a switch
statement is evaluated once and compared with the values in the case
statements. If a match is found, the corresponding code block is executed. The break
statement is used to stop the execution of the switch
statement; without it, the execution continues to the next case.
Here's an example to demonstrate the usage of switch
:
let fruit = "Apple"; switch (fruit) { case "Apple": console.log("It's an apple"); break; case "Banana": console.log("It's a banana"); break; case "Orange": console.log("It's an orange"); break; default: console.log("It's some other fruit"); break; }
The output of this code will be "It's an apple" because the value of fruit
matches the first case
.
- How to format number with commas and decimal in Javascript
- How to Pass string parameter in an onclick function
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
- How to copy text to clipboard in Javascript
Categories
Popular Posts
Gentella Admin Template
11/14/2024
Modular Admin Template
11/14/2024
RuangAdmin Template
11/17/2024
DASHMIN Admin Dashboard Template
11/17/2024