EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Case Statement in JavaScript

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » JavaScript Tutorial » Case Statement in JavaScript

Case Statement in JavaScript

Introduction to Case Statement in JavaScript

JavaScript is the most popular client-side scripting language which is supported by almost all browsers. It is an open-source dynamic programming language that front end developers use. Almost all popular front-end frameworks like Angular, React, etc., are based on JavaScript; the final code that gets generated is in pure JavaScript only. Like any other programming language, JavaScript has the ability to make decisions using conditional statements, which are very useful and required for decision making at runtime. Decision-making statements are the backbone of any programming language because, depending upon the different scenarios and situations, we can execute particular statements.

What is Case Statement in JavaScript?

While writing programs, there might be a situation where we need to execute a particular part of it depending upon the situation. This refers to dynamically choosing and executing the preferred part of the code. In such kind of situations, we can use conditional statements that allow us to make a decision at runtime and execute the correct part.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

JavaScript supports conditional statements like if statement, if… else… statement, switch case statement, etc. These are the statements that are used to decide the flow of execution depending on different conditions. If statement works and its details, then we will try to understand why we need to switch-case statements and their details in depth.

If Statement works in this way, if a condition is true, it will execute code from if block otherwise, if a condition is false, it will execute code from else block. The condition over here is what we are actually passing to make the decision for the program. In the case of the if statement, the condition statement is mostly a Boolean variable or an expression returning Boolean variable; it is either True or either False. Depending upon this value, If statement executes a particular block of code. There are three forms of if statement,

  1. If Statement
  2. If else Statement
  3. If else if Statement

How If Statement Works?

If (condition 1) {
//execute this block when condition 1 is true
}
else if (condition 2) {
//execute this block when condition 2 is true
}
.
.
.
else {
//execute this block when none of condition is true
}

For example, if statement will check condition one by one and execute a particular block of code. This kind of execution is OK for a smaller number of conditions, but imagine, if we have a large number of conditions, then it becomes difficult to track the code, code becomes messy and less efficient. In such kind of scenarios, the switch case statement is useful. The switch case statement is used as an alternative to multiple if… else… statements. They are more efficient when testing multiple conditions.

Popular Course in this category
JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes)39 Online Courses | 23 Hands-on Projects | 225+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (6,106 ratings)
Course Price

View Course

Related Courses
Angular JS Training Program (9 Courses, 7 Projects)Vue JS Training (1 Courses, 3 Project)

How does the Case Statement Work in Java Script?

The case statement executes one of many code blocks based on a variable or a value of the expression.

Syntax:

switch(expression)
{
case a:
//Statement or expression;
break;
case b:
//Statement or expression;
break;
.
.
.
default:
//default statement or expression;
}

  • The case statement evaluates expression first and finds out the value of it.
  • Then it matches the same value with each case statement. In our case, once the value of the expression is determined, it will be compared with case values a, b, etc.
  • After matching the value with the case statements, if a match is found, it executes the code or expression within that block and exits from the switch block.
  • It goes on by comparing the result of expression one by one with all case values.
  • If no match is found from all case statements, then it executes the code block from the default case statement. default block is always executed when no match is found.
  • Break keyword is used after every case block execution. Basically, it tells the program to exit from the switch statement.
  • If the break statement is not used, then the program execution will continue by executing code from the next case block, and it will continue until it finds out the break keyword or executes the final default block.

 Flow Diagram:

Case Statement in JavaScript-1.1

In the case of case statements, the condition can be an expression or a value of any datatype. The expression is nothing but a conditional statement returning the appropriate value to be compared. Switch case statements are good for evaluating fixed data types.

Examples of Case Statement in JavaScript

Examples of Case Statement in JavaScript are as follows:

Example 1

var x = 1;
switch (x)
{
case 0:
console.log(“Zero”);
break;
case 1:
console.log(“One”);
break;
case 2:
console.log(“Two”);
break;
default:
console.log (“Not Zero, One or Two);
}

In the above example, the variable x is of integer type, and we have assigned value 1 to it. x is passed as the expression to the switch statement. Now the value of x is compared with all cases; in our case, it will be matched with case 1. That will execute block for case 1, and the program will print out “One” on to the console. If the value of x has been any other, then the default block would have been executed.

Example 2

var colour = “Blue”;
switch(colour)
{
case “Red”:
alert (“Colour is Red”);
break;
case “Green”:
alert (“Colour is Green”);
break;
case “Blue”:
alert (“Colour is Blue”);
break;
default:
alert (“No Colour Match”);
}

The example above will match the color as Blue and show Alert in the browser as “Colour is Blue”.  Note that the data type of expression here is String. In the previous example, it was of Integer type.

Conclusion

JavaScript has the very broad support of conditional statements. Case statements are alternative to multiple if-else statements. Case statements make code efficient and look less messy. Case statements are very useful in JavaScript, where testing of multiple large numbers of conditions is required.

Recommended Articles

This is a guide to the Case Statement in JavaScript. Here we discuss how the case statement works along with the examples of the case statement in javascript. You may also look at the following articles to learn more –

  1. Arrays in JavaScript
  2. How JavaScript Works
  3. Cheat Sheet JavaScript
  4. Careers in JavaScript

JavaScript Training Program (39 Courses, 23 Projects)

39 Online Courses

23 Hands-on Projects

225+ Hours

Verifiable Certificate of Completion

Lifetime Access

4 Quizzes with Solutions

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
JavaScript Tutorial
  • Control statements
    • Control Statement in JavaScript
    • Conditional Statements in JavaScript
    • Break Statement in JavaScript
    • Continue in JavaScript
    • Switch Statement in JavaScript
    • Case Statement in JavaScript
    • JavaScript if Statement
    • Nested if in JavaScript
    • JavaScript elseIf
  • Basic
    • Introduction To JavaScript
    • What is JavaScript
    • What Javascript Can Do
    • Uses of JavaScript
    • How JavaScript Works
    • Is Javascript Case Sensitive
    • Is Javascript Object Oriented
    • Features of JavaScript
    • Careers in JavaScript
    • How to Install JavaScript
    • Best Javascript Frameworks
    • JavaScript MVC Frameworks
    • JavaScript Tools
    • What is JSON
    • What is Redux
    • What is ES6
    • Uses of React JS
    • How Analytics.JS Works
    • JavaScript Compilers
    • Java and JavaScript
    • JavaScript Literals
    • Variables in JavaScript
    • JavaScript Global Variable
    • JavaScript Keywords
    • String in JavaScript
    • Pointers in JavaScript
    • Primitive Data Types in JavaScript
    • JavaScript console log
    • Object in JavaScript
    • JavaScript Enum
    • Arithmetic in JavaScript
    • Assignment Operator in JavaScript
    • JavaScript Modules
    • Cheat Sheet JavaScript
    • NPM Alternatives
  • Objects
    • JavaScript Objects
    • JavaScript History Object
    • JavaScript Object Notation
    • JavaScript Map Object
    • JavaScript Date Object
    • JavaScript Window Object
    • JavaScript Object Constructors
    • JavaScript Clone Object
    • JavaScript Object.assign()
    • JavaScript object.is()
    • JavaScript Object to JSON
  • Operators
    • Arithmetic Operators in JavaScript
    • JavaScript Assignment Operators
    • Logical Operators in JavaScript
    • Comparison Operators in JavaScript
    • Bitwise Operators in JavaScript
    • Ternary Operator JavaScript
    • Boolean Operators in JavaScript
    • JavaScript?Modulo
    • JavaScript Boolean()
    • Unary Operators in JavaScript
    • JavaScript Number
    • JavaScript Floating
    • JS Operator Precedence
  • Loops
    • For Loop in JavaScript
    • While Loop in JavaScript
    • Do While Loop in JavaScript
    • Nested Loop in JavaScript
  • Array
    • Arrays in JavaScript
    • 2D Arrays in JavaScript
    • Multi-Dimensional Array in JavaScript
    • Associative Array in JavaScript
    • JavaScript Declare Array
    • Arrays Methods in JavaScript
    • JavaScript Loop Array
    • String Array in JavaScript
    • JavaScript Get Array Length
    • JavaScript Merge Arrays
    • JavaScript Array Sort
    • JavaScript Array Push
    • JavaScript Iterate Array
    • JavaScript Empty Array
    • JavaScript Array Concat
    • Dynamic Array in JavaScript
    • JavaScript subarray()
    • JavaScript Array Filter
    • JavaScript Nested Array
    • JavaScript Flatten Array
    • JavaScript Array map()
    • JavaScript Array includes()
    • JavaScript Array Contain
    • JavaScript Array Slice
    • JavaScript Copy Array
    • Javascript Sum Array
    • JavaScript reverse Array
    • JSON Parse Array
  • Sorting
    • Sorting Algorithms in JavaScript
    • Insertion Sort in JavaScript
    • Merge Sort in JavaScript
    • Quick Sort in JavaScript
    • Bubble Sort in JavaScript
    • pop() in JavaScript
    • push() in JavaScript
    • Sort string in JavaScript
  • Functions
    • JavaScript String Functions
    • JavaScript String Length
    • JavaScript split String
    • JavaScript Math Functions
    • Recursive Function in JavaScript
    • Regular Expressions in JavaScript
    • JavaScript Arrow Function
    • JavaScript Date Function
    • Match Function in Javascript
    • Replace Function in JavaScript
    • JavaScript Call Function
    • JavaScript Pass By Value
    • split() Function in JavaScript
    • reduce() Function JavaScript
    • JavaScript String replace
    • JavaScript Compare Strings
    • JavaScript Sleep
    • JavaScript toLowercase()
    • JavaScript String to Float
    • JavaScript String to Number
    • JavaScript String to int
    • JavaScript Object to String
    • JavaScript Convert to JSON
    • JavaScript Append
    • Javascript Array to String
    • Javascript Nested Functions
    • Set in JavaScript
    • Vectors in JavaScript
    • Javascript Anonymous Function
    • sign() in JavaScript
    • isNaN() JavaScript
    • Slice() Method in JavaScript
    • Javascript void
    • endsWith() in JavaScript
    • trim() Function in JavaScript
    • JavaScript typeof
    • JavaScript indexOf()
    • JavaScript encodeURI()
    • JavaScript Random
    • Ceil() in JavaScript
    • JavaScript tofixed
    • JavaScript hash()
    • JavaScript MD5
    • JavaScript search
    • JavaScript z-index
    • JavaScript Absolute Value
    • JavaScript Closure
    • Javascript Prototype
    • JavaScript Date parse
    • JavaScript DatePicker
    • JavaScript Parse String
    • JavaScript undefined
    • JavaScript FileReader
    • JavaScript Style visibility
    • JavaScript sleep Function
    • JavaScript forEach()
    • JavaScript keys()
    • JavaScript keycodes
    • JavaScript find() 
    • JavaScript values()
    • JavaScript Counter
    • JavaScript Countdown
    • JavaScript instanceof
    • JavaScript Delay
    • JavaScript Default Value
    • JavaScript concat String
    • JavaScript Document Object Model
    • Unshift JavaScript
    • JavaScript Callback Function
    • JavaScript hasOwnProperty()
    • JavaScript UUID
    • JSON Parser
    • JSON Array of Strings
    • Sublime Pretty JSON
    • JavaScript JSON to string
    • JavaScript Uppercase
    • JavaScript Namespace
    • JavaScript Range
    • JavaScript JSON
    • JavaScript exec()
    • JavaScript test()
    • JavaScript Self Invoking Functions
    • JSON Stringify Pretty
    • JavaScript findIndex()
    • JavaScript entries()
    • JavaScript join()
    • JavaScript lastIndexOf()
    • JavaScript every()
    • JavaScript getElementById()
    • JavaScript getElementsByName()
    • JavaScript getElementsByTagName()
    • JavaScript getElementsByClassName()
    • JavaScript Animation
    • JavaScript Minify
  • Events
    • JavaScript Events
    • JavaScript Event Handler
    • JavaScript Keyboard Events
    • JavaScript Mouse Events
    • JavaScript mousemove
    • JavaScript mousedown
    • JavaScript onchange
    • JavaScript onmouseout
    • JavaScript Onkeydown
    • JavaScript onsubmit
    • JavaScript Form Events
    • JavaScript Window Events
    • JavaScript Custom Events
    • JavaScript Alert
    • JavaScript Confirm
    • JavaScript onclick Alert
    • JavaScript Apply
    • JavaScript onblur
    • JavaScript onkeyup
    • JavaScript onfocus
  • Advanced
    • Constructor in JavaScript
    • Inheritance in JavaScript
    • Polymorphism in JavaScript
    • JavaScript Static Method
    • Navigator in JavaScript
    • Abstract Classes in JavaScript
    • keyword in JavaScript
    • Overriding in JavaScript
    • JavaScript Clear Console
    • JavaScript References
    • JavaScript list
    • JavaScript Grid
    • JavaScript innerText
    • Cookies in JavaScript
    • Delete Cookie in JS
    • Encapsulation in JavaScript
    • JavaScript Parent Node
    • JavaScript Parent
    • Javascript Remove Element
    • Errors in JavaScript
    • Forms in JavaScript
    • JavaScript Validator
    • JavaScript Form Validation
    • Email Validation in JavaScript
    • Hamburger Menu JavaScript
    • JavaScript Date Formats
    • JavaScript Number Format
    • JavaScript Debugger
    • JavaScript Stack
    • Queue in JavaScript
    • parseFloat in JavaScript
    • Javascript innerHTML
    • JavaScript setInterval
    • JavaScript Popup Box
    • JavaScript Message Box
    • Lightbox in JavaScript
    • Javascript Design Patterns
    • addEventListener JavaScript
    • Timer in JavaScript
    • JavaScript setTimeout
    • JavaScript clearTimeout()
    • JavaScript String Format
    • JavaScript Scroll to Top
    • JavaScript Function Declaration
    • JavaScript Function Arguments
    • Javascript Strict Mode
    • File Handling in JavaScript
    • JavaScript parseInt
    • JavaScript prompt
    • JavaScript Set Class
    • JavaScript Try Catch
    • Javascript Throw Exception
    • Finally in JavaScript
    • JavaScript Get Element by Class
    • JavaScript Obfuscator
    • Disable JavaScript
    • SetAttribute JavaScript
    • JavaScript Cursor
    • LinkedList in JavaScript
    • JavaScript WeakMap
    • JavaScript DOM
    • JavaScript defer
    • JavaScript Promise
    • Pagination in JavaScript
    • JavaScript Refresh Page
    • JSON.stringify JavaScript
    • JavaScript IIFE
    • JavaScript Fetch API
    • JavaScript Auto Complete
    • JavaScript Copy to Clipboard
    • JavaScript querySelector
    • JavaScript Graph
  • Programs
    • Patterns in JavaScript
    • Reverse in JavaScript
    • Palindrome in JavaScript
    • Factorial Program in JavaScript
    • Fibonacci Series In JavaScript
    • Square Root in JavaScript
    • Prime Number in JavaScript
    • Armstrong Number in JavaScript
    • Random Number Generator in JavaScript
    • Reverse String in JavaScript
    • JavaScript Random String
    • Functional Programming in JavaScript
  • Interview Questions
    • Javascript Interview Questions
    • JSON Interview Questions
    • JS Interview Questions

Related Courses

JavaScript Certification Training

Angular JS Certification Training

Vue JS Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - JavaScript Training Program (39 Courses, 23 Projects) Learn More