Loading

Quipoin Menu

Learn • Practice • Grow

java-script / Switch Statement
interview

Q1. What is a Switch Statement?
A switch statement is used to execute one block of code from multiple possible options based on a specific condition or value.
It is often used as an alternative to multiple if...else statements when checking a single variable against many values.

Example
let day = 2;

switch(day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    default:
        console.log("Invalid day");
}

Output
Tuesday

Explanation:
  • The expression day is evaluated.
  • If it matches case 2, that block runs.
  • break stops further execution.


Q2. Why Do We Use Break in a Switch Statement?
The break statement stops the execution of the switch block once a matching case is found.
Without break, JavaScript continues executing the next cases even if they do not match. This is called fall-through behavior.

Example Without Break
let value = 1;

switch(value) {
    case 1:
        console.log("One");
    case 2:
        console.log("Two");
}

Output
One
Two

Since there is no break, execution continues to the next case.


Q3. What is the Default Case in a Switch Statement?
The default case runs when none of the cases match the given expression.
It acts like the else block in an if...else statement.

Example
let color = "Blue";

switch(color) {
    case "Red":
        console.log("Stop");
        break;
    case "Green":
        console.log("Go");
        break;
    default:
        console.log("Unknown Color");
}

Output
Unknown Color


Q4. Can Multiple Cases Share the Same Code Block?
Yes, multiple cases can execute the same block of code by placing them together without break.

Example
let fruit = "Apple";

switch(fruit) {
    case "Apple":
    case "Mango":
    case "Banana":
        console.log("This is a fruit");
        break;
    default:
        console.log("Not a fruit");
}

Output
This is a fruit

If the value matches any of these cases, the same code runs.


Q5. What Type of Comparison Does Switch Use?
Switch statements use strict comparison (===).

This means:
  • Value must match
  • Data type must also match
Example
let num = "5";

switch(num) {
    case 5:
        console.log("Number is 5");
        break;
    default:
        console.log("Not matched");
}

Output
Not matched

Explanation:
  • "5" is a string
  • 5 is a number
  • Strict comparison fails