SA-21/06, C-11, Asapur, Varanasi, UP support@kamaldnp.com +91 8318013442
JavaScript
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10
Try this code live
Lesson 20 of 35

JavaScript switch Statement — case, break, default

5 min read · Free · No login needed

An if...else if chain works fine for three or four options, but what about seven — one for each day of the week? Or twelve, one for each month? The chain gets long and hard to read. That is when you use a switch: you give it one value, and it jumps straight to the matching case.

Diagram — see how it fits together
Diagram: JavaScript Switch

Think of a railway station enquiry counter. You say "Platform 3", and the clerk does not check platform 1, then platform 2, then platform 3 — he jumps straight to the right board. A switch works the same way: it looks at one value and goes directly to the matching case. No repeated questions, no long chain.

Remember it like this: switch picks, case matches, break stops, default catches the rest.

switch and case — jumping to the right answer

A switch statement starts with the word switch, then the value in round brackets, then a block with one case for each possible value. Each case has a colon, then the code to run.

let day = 3;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Another day");
}
// "Wednesday"

The computer compares day with each case, top to bottom, and runs the first one that matches. It compares with === — strict equality, value and type — so case 3 does not match the string "3".

break — why it matters

Here is the strange part: without a break, the computer does not stop after the matching case. It keeps running into the next case, and the next, until it hits a break or the end of the switch. This is called "fall-through", and it is the most common switch bug in the world.

let day = 2;
switch (day) {
  case 2:
    console.log("Tuesday");
  case 3:
    console.log("Wednesday");
  case 4:
    console.log("Thursday");
}
// Tuesday, Wednesday, Thursday — all three print!

Because there was no break after "Tuesday", the computer fell through and printed Wednesday and Thursday too. In almost every switch you write, every case ends with a break. The only time you skip it on purpose is when two cases should do the same thing.

Note: Fall-through is not always a mistake. If Monday to Friday all mean "working day", you can stack the cases with no code between them and one shared break at the end. But if you leave out a break by accident, you get three answers instead of one — so check every case for its break before you run the code.

default — the safety net

default is the case that runs when nothing matches. It is like the else of an if-chain: it catches everything the cases missed. It is optional, but writing one is good practice — it means your program always has an answer, even for a value you did not expect.

let grade = "Z";
switch (grade) {
  case "A":
    console.log("Excellent");
    break;
  case "B":
    console.log("Good");
    break;
  default:
    console.log("Unknown grade");
}
// "Unknown grade"

default does not need a break because it is the last block in the switch — there is nothing after it to fall through into. But some programmers add one anyway, in case a new case is added below it later.

Tip: Use a switch when you are comparing one value against many exact options — days, months, grades, menu choices. Use if...else if when each test is different — ranges like "more than 90", "more than 60". A switch cannot test ranges; it only matches exact values.

Common mistakes

  • Forgetting break after a case — the code falls through and runs the next cases too, printing three answers instead of one.
  • Using a switch for ranges — case marks >= 90 does not work. Switch matches exact values only; ranges need if...else if.
  • Mixing types — switch ("3") will not match case 3, because the comparison is strict. The string "3" and the number 3 are different values.
  • Forgetting default — when no case matches, the switch silently does nothing. A default makes the program's answer clear.
  • Putting code between the cases without a case label — the switch ignores it. Every line must belong to a case or to default.

Remember

  • Switch picks, case matches, break stops, default catches the rest.
  • Without break, the code falls through into the next case — almost always a bug.
  • switch matches exact values only, with strict === comparison. Ranges need if...else if.
  • Use switch for one value with many exact options — days, months, grades, menu choices.

Example explained

  • let day = 3; — the day number, where 1 is Monday and 7 is Sunday.
  • switch (day) — the computer looks at the value of day and jumps to the matching case.
  • case 3: ... break; — day is 3, so this case runs, prints "Wednesday", and the break stops the switch right there.
  • default: — if day were 8 or 0 or anything else, this block would run and print "Invalid day number".
  • document.getElementById("result").innerHTML = ... — writes the weekday name into the page when the button is clicked.

Example

Example
<!DOCTYPE html>
<html>
<head>
<title>Weekday Finder — JavaScript Switch</title>
<style>
body { font-family: Verdana, sans-serif; padding: 20px; }
h1 { color: #1e3a5f; }
button { background-color: #e13611; color: white; border: none; padding: 10px 18px; font-size: 16px; cursor: pointer; }
p { font-size: 18px; }
.result { background-color: #f1f5f9; padding: 12px; }
</style>
</head>
<body>

<h1>Weekday Finder</h1>
<p>Day number: 3 (1 = Monday, 7 = Sunday)</p>
<button onclick="findDay()">Find the Day</button>
<p class="result" id="result">Click the button to see which weekday day 3 is.</p>

<script>
function findDay() {
  let day = 3;
  let name;
  switch (day) {
    case 1:
      name = "Monday";
      break;
    case 2:
      name = "Tuesday";
      break;
    case 3:
      name = "Wednesday";
      break;
    case 4:
      name = "Thursday";
      break;
    case 5:
      name = "Friday";
      break;
    case 6:
      name = "Saturday";
      break;
    case 7:
      name = "Sunday";
      break;
    default:
      name = "Invalid day number";
  }
  document.getElementById("result").innerHTML =
    "Day " + day + " is " + name;
}
</script>

</body>
</html>

Output

Output — how it looks in the browser
Output of JavaScript switch Statement — case, break, default

Try it yourself — live editor

Change the code below and press Run to see the result instantly. No file to save, no login needed.

Result

Frequently asked questions

The questions learners ask most about this lesson — read the question, then open it to see the answer.

1. When should I use switch instead of if else if?

When one value has many options, like seven days or twelve months — a long chain gets hard to read.

2. Why is break needed in a switch case?

Without break, the computer keeps running into the next case after the matching one instead of stopping.

3. Does switch compare with == or ===?

With ===, strict equality of value and type, so case 3 does not match the string "3".

Why learn this yourself — and not just ask AI?

AI can write code for you, but it cannot think for you. When you learn HTML yourself, your brain builds the real skill: you understand why a page looks the way it does, you can fix it when it breaks, and you can answer it in an exam or an interview without help. That is the skill that gets you a job — not a copied answer.

Get certified — just ₹10

Finish all 35 lessons, pass the test (80%), pay ₹10 and get your certificate.

Take the test

Prefer watching? Video courses teach the same topics step by step.

Go further with a full course

Free tutorials teach you the basics. Our paid courses add live projects, mentorship and a certificate.

Core Python Programming – 3 Month Complete Course
₹700
View
Advanced Cyber Security Industrial Training
₹5,000
View
AI & ML with Azure AI, AWS AI & Generative AI
₹10,000
View
Browse all courses
JavaScript — Lessons
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10

🤖 KAMALDNP AI Assistant

Ask about courses, website & more

Hi! I'm KAMALDNP AI Assistant. Ask me about our courses, website features, or anything else! 😊
Please wait 5s...
🤖 KAMALDNP Assistant ✕

Request human callback:

🔐 Login Required
✕

Please log in to download. You will stay on this page after logging in!

New here? Register now →