Jessica  Jacobs

Jessica Jacobs


JavaScript Lecture - 21 Switch Statement

Hello Friends,
In this lecture we are going to learn switch case statement in javascript in hindi step by step, If you like the lecture please don’t forget to share and subscribe for more lectures.

#switchcase #javascriptswitchstatement #webdevelopment #webdesign #softwaredevelopment


What is GEEK

Buddha Community

JavaScript Lecture - 21 Switch Statement

How to Mastering The JavaScript Switch Statement

The JavaScript switch statement is a way to make decisions in your code based on different conditions. It is a more organized and concise alternative to using multiple if-else statements. The switch statement evaluates a given expression, which can be a variable or a value, and compares it to several possible cases. If the value of the expression matches one of the cases, the associated code block (a set of instructions) is executed. If no match is found, an optional default case can be executed as a fallback, meaning it runs when none of the other cases apply.

For example, here’s a simple switch statement that checks the value of a variable called day:

switch (day) {
  case "Monday":
    console.log("Start of the work week! 😴");
  case "Friday":
    console.log("End of the work week! 🥳");
    console.log("A regular day");

By mastering switch statements, you can write cleaner, more efficient, and better-organized JavaScript code, ultimately improving your overall programming skills.

switch Statement Basics: Anatomy and structure

switch statements begins with the keyword switch, followed by an expression in parentheses. This expression is compared to a series of case labels enclosed in a switch block. Each case label represents a distinct value, and the code block that follows the case is executed when the expression matches the case label’s value. A break statement is typically used to exit the switch block after a matching case is executed, ensuring that only the intended code block runs, and preventing fall-through to the next cases. Optionally, a default case can be included to provide a fallback action when none of the case labels match the expression, ensuring a response for unknown values.

switch(expression) {
    case {value1}:
    // <-- Your Code to execute -->  
    break    // optional
    case {value2}:
    // <-- Your Code to execute -->   
    break    // optional
    default: // optional
    // <-- Code that executes when no values match-->

const superhero = 'Spider-Man';
switch (superhero) { 
  case 'Batman':
    console.log('🦇 The Dark Knight!');
  case 'Wonder Woman':
    console.log('👸 The Amazon Princess!');
    console.log('💥 There are so many amazing superheroes!');

switch vs. if-else

The switch statement is an alternative to using if-else statements when you have multiple conditions to handle. While if-else statements are suitable for checking a series of conditions that can be expressed as true or false, switch statements are more efficient when dealing with a single expression that can take on multiple distinct values. In essence, switch statements can make your code cleaner, more organized, and easier to read when you have several related conditions to manage.

For example, consider the following if-else structure:

if (color === "red") {
  console.log("The color is red 🟥");
} else if (color === "blue") {
  console.log("The color is blue 🟦");
} else if (color === "green") {
  console.log("The color is green 🟩");
} else {
  console.log("Unknown color 🌈");

The equivalent switch statement would look like this:

switch (color) {
  case "red":
    console.log("The color is red 🟥");
  case "blue":
    console.log("The color is blue 🟦");
  case "green":
    console.log("The color is green 🟩");
    console.log("Unknown color 🌈");

The switch statement offers a more organized and readable way to handle multiple conditions, particularly when dealing with a large number of cases. In a switch statement, the expression being evaluated is the variable or value inside the parentheses (in this example, the variable color).

When to use switch over if-else

  1. Large number of single-variable conditions: When you have a large number of conditions to handle, switch statements are generally more organized and easier to read than if-else chains.
  2. Single variable evaluation: If the conditions you are evaluating are based on a single variable or expression with multiple distinct values, switch statements can provide a more efficient and cleaner solution than if-else patterns.
  3. Faster code execution: In certain situations, JavaScript engines can optimize switch statements, leading to faster code execution when compared to a series of if-else statements.
  4. Easier maintenance: Switch statements make it easier to add, remove, or modify cases, as each case is self-contained within the switch block. In contrast, if-else chains may require more extensive modifications when changes are needed.
  5. Default fallback: Switch statements provide an optional default case that can be executed when none of the other cases match the given expression. This feature allows for a clean way to handle unexpected or unknown values.

When to use if-else over switch

  1. Complex conditions: If the conditions you are evaluating involve complex logic, multiple variables, or relational and logical operators, if-else patterns provide more flexibility and are better suited for these situations than switch statements.
  2. Range-based conditions: When you need to check for a range of values or conditions that are not discrete, if-else patterns offer a better solution, as switch statements are designed for comparing discrete values.
  3. Small number of conditions: If you have only a few simple conditions to check, using an if-else pattern can be more straightforward and easier to write than a switch statement.
  4. Non-constant cases: Switch statements require constant values for case labels, meaning they cannot be expressions that change at runtime. If you need to evaluate conditions with non-constant values, if-else patterns are the appropriate choice.
  5. Evaluating truthy or falsy values: If-else patterns are suitable when you need to check if a value is truthy or falsy. Switch statements are not designed for this type of evaluation and would require more verbose code to accomplish the same result.
  6. Early exit conditions: If you have an early exit condition where further evaluation is unnecessary once a certain condition is met, if-else patterns can be more efficient. With a switch statement, all cases are evaluated, even if an early match is found (unless you use a “break” statement).

Deciding on switch or if-else

Both switch and if-else solve similar problems and have advantages and disadvantages based on your use cases. To help you make your decision, I’ve created a simple switch statement:

switch (yourUseCase) {
  case 'large_number_of_conditions':
  case 'single_variable_evaluation':
  case 'multiple_discrete_values':
    console.log('Consider using a switch statement.');
  case 'complex_conditions':
  case 'range_based_conditions':
  case 'non_constant_cases':
    console.log('Consider using an if-else pattern.');
    console.log('Choose the most appropriate control structure based on your specific use case.');

switch Statement Functionality and Techniques:

The switch statement provides additional functionality and concepts that can be used to improve the performance, readability, and conciseness of your code.

The default case

The default case in a switch statement is executed when none of the other cases match the provided expression. It serves as a fallback to handle unexpected or unknown values, ensuring a response is provided even if there’s no matching case.

const beverage = 'lemonade';

switch (beverage) {
  case 'coffee':
    console.log('☕️ Enjoy your coffee!');
  case 'tea':
    console.log('🍵 Have a relaxing cup of tea!');
    console.log('🥤 Your choice of drink is not listed, but cheers anyway!');

The break keyword

The break keyword is used in a switch statement to exit the switch block once a matching case is found and executed. It prevents the code from continuing to execute the remaining cases, ensuring only the correct output is generated.

const transport = 'bike';

switch (transport) {
  case 'car':
    console.log('🚗 Drive safely!');
  case 'bike':
    console.log('🚲 Enjoy your bike ride!');
  case 'bus':
    console.log('🚌 Have a pleasant bus journey!');

The Fall-Through technique

A case cannot have more than one condition in a switch statement. To incorporate multiple conditions in one case, consider using the fall-through technique. Not only does it save you time, it ensure you don’t repeat yourself.

Fall-through in a switch statement occurs when you intentionally omit the break keyword in a case, allowing the code execution to continue to the next case(s) until a break is encountered or the end of the switch block is reached. This can be useful when multiple cases share the same output or action.

const clothing = 'jacket';

switch (clothing) {
  case 't-shirt':
  case 'shorts':
    console.log('😎 Looks like it\'s warm outside!');
  case 'jacket':
  case 'sweater':
    console.log('❄️ Bundle up, it\'s cold!');
    // No break, fall-through to the next case
  case 'scarf':
    console.log('🧣 Don\'t forget your scarf!');

Common issues and pitfalls

Multiple cases executing (Forgetting to use the break statement)

A frequent mistake when using switch statements is not including the break statement after each case. This error results in unintentional fall-through, executing multiple cases instead of just the desired one.

How to fix it: Add a break statement after each case to prevent fall-through.

const mood = 'happy';

switch (mood) {
  case 'happy':
    console.log('😀 Keep smiling!');
    // <--- Missing break statement
  case 'sad':
    console.log('☹️ Cheer up!');
  case 'angry':
    console.log('😠 Take a deep breath!');

// --Output-- 
//😀 Keep smiling! 
//☹️ Cheer up!

Incorrect Comparison Values and Types

Switch statements use strict comparison, which can lead to unexpected results when comparing different data types. In the example below, the string "2" is not equal to the number 2. This pitfall might cause your cases not to execute as intended.

How to fix: Consider the type of your variables and remember it will be evaluated strictly. TypeScript may help if you’re working on larger projects.

const numOfPets = '2';

switch (numOfPets) {
  case 2: // Because '2' !== 2
    console.log('🐾 Double the fun!');
    console.log('🐾 Share the love!');

// -- Output --
// 🐾 Share the love!

Scoping issues

A common pitfall in switch statements is declaring variables without block scope or incorrect scopes, causing them to be accessible in other cases, or creating syntax errors. You may experience an Uncaught SyntaxError: ... if you try to redeclare the same variable in multiple clauses.

The fixes:

  • For common variables you intend to use in all cases, declare it with let before your switch statement, or;
  • Scope your clauses as block scope (i.e. wrap your clauses with parentheses { ... })

Block scope your clauses:

// The problem: 
switch (weather) {
  case 'rain':
    const notification = '🌦️ ️Rainy days can be cozy!';
  case 'thunder':
    // 'notification' is still accessible here
    console.log(notification + ' ⚡ Be careful!');
// Fix 1: Use Block Scope when declaring
switch (weather) {
  case 'rain': { // <-- look here.
    const notification = '🌦️ ️Rainy days can be cozy!';
  case 'thunder': {
    const notification = '⚡ Be careful!';

// Fix 2: Declare it with let before your statement
let notification = '' // <-- look here.
switch (weather) 
  case 'rain':
    notification = '🌦️ ️Rainy days can be cozy!';
  case 'thunder':
    notification = '⚡ Be careful!';


Now that you know what a switch statement is, how it works, and when to use it, it’s time to start implementing it! I hope you’ve enjoyed this article. Join us over on the SitePoint Community if you have any questions about this piece or JavaScript in general.

Original article source at:

#javascript #switch #statement 

Rahul Jangid


What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */


Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here

Book Free Interview:

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Erna  Herzog

Erna Herzog


Level Up Your React Designs with Styled Components + JavaScript Switch Statements

Learn how to create flexible components in React for your design system using Styled Components–a CSS in JS library.

Styled Components help make components more readable and keep the headache of styling and element architecture separated.

The pros and cons are often debated, but we’re big fans at Skillthrive. If you want to learn more about the pros and cons so you can make the decision for yourself, check out this article:




Setup a Gatsby Site with Styled Components: 1:37

Create the Styled Components: 4:51

Install Google Fonts on Gatsby: 7:28

How to Use a JavaScript Switch Statement with Styled Components: 7:57

How to Use Your New Styled Component: 14:22

#WebDev #WebDesign #WebDevelopment

#javascript #webdev #react #javascript switch statements #styled components

Javascript Switch Example | Switch Statement In Javascript

Javascript switch statement is used to perform different actions based on various conditions. You can use multiple if…else…if statements, but it is a little bit cumbersome instead you can use the switch statement to execute the code based on conditions. In one function, you can handle multiple conditions using a switch statement.

The switch statement which handles this situation precisely, and it does so more efficiently than repeated if…else if statements.

Javascript Switch Statement

See the following syntax.

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

This is how a switch statement works:

  • The switch expression is evaluated once at the beginning.
  • The value of the expression is compared with the other values of each case in a switch statement.
  • If there is a match found, the associated block of code is executed.

#javascript #switch #js