How to use switch in Javascript
By FoxLearn Published on Dec 18, 2024 119
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 use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- 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
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
Nov 17, 2024
RuangAdmin Template
Nov 13, 2024
Admin BSB Free Bootstrap Admin Dashboard
Nov 14, 2024