Computer Science
Javascript Switch Statement
A JavaScript switch statement is a control flow mechanism used to execute different code blocks based on the value of a variable or expression. It provides a concise way to handle multiple possible conditions within a program. The switch statement evaluates an expression and compares it with multiple case values to determine the appropriate code block to execute.
Written by Perlego with AI-assistance
Related key terms
1 of 5
9 Key excerpts on "Javascript Switch Statement"
- eBook - ePub
- Andy Harris(Author)
- 2014(Publication Date)
- For Dummies(Publisher)
As you can see in this structure, there are three different possibilities for temperatures higher than 60 degrees. Simply add more if statements to get the behavior you wish.- Test your code. When you build this kind of structure, you need to run your program several times to ensure it does what you expect.
Making decisions with switch
JavaScript, like a number of languages, supports another decision-making structure called switch . This is a useful alternative when you have a number of discrete values you want to compare against a single variable. Take a look at this variation of the name program from earlier in this chapter:function checkName(){ //from switch.html var name = prompt("What is your name?"); switch(name){ case "Bill Gates": alert("Thanks for MS Bob!"); break; case "Steve Jobs": alert("The Newton is awesome!"); break; default: alert("do I know you?"); } // end } // end checkNameThe switch code is similar to an if-elseif structure in its behavior, but it uses a different syntax:- Indicate a variable in the switch statement.
In the switch statement's parentheses, place a variable or other expression. The switch statement is followed by a code block encased in squiggly braces ({} ).
- Use the case statement to indicate a case. The case statement is followed by a potential value of the variable, followed by a colon. It's up to the programmer to ensure the value type matches the variable type.
- End each case with the break statement.
End each case with the break statement. This indicates that you're done thinking about cases, and it's time to pop out of this data structure. If you don't explicitly include the break
- eBook - ePub
HTML and CSS
The Comprehensive Guide
- Jürgen Wolf(Author)
- 2023(Publication Date)
- SAP PRESS(Publisher)
|| operators. However, you should keep in mind the readability of the source code.17.7.6 Multiple Branching via “switch”
If you want to check multiple cases, you can theoretically use multiple if queries in a row, or you can use the case distinction, switch . In JavaScript, switch supports values with any type. It’s even possible to have values determined dynamically first via function calls. In many other programming languages, these values must be constants. For this purpose, here’s a theoretical construct of a switch case distinction:switch( expression ) { case label_1 : statements; [ break ]; case label_2 : statements; [ break ]; ... default : statements; }In this case distinction, a matching value in case is searched for the expression in switch . If a case marker matches the switch evaluation, the program execution takes place after this case marker. If no case marker matches the switch evaluation, you can use an optional default marker, which will be executed as an alternative. Of particular importance in a switch case distinction are the break statements at the end of a case marker. You can use break to instruct the program to jump out of the switch block and continue with the program execution after. If you don’t use a break statement, all further statements (including the case markers after them) in the switch block will be executed until the next break statement or the end of the block has been reached.Here’s a simple example to demonstrate switch in use:switch ( new Date().getDay()) { case 0: console .log( "Today is Sunday" ); break ; case 6: console .log( "Today is Saturday" ); break ; default : console .log( "Today is an ordinary weekday" ); }Here, a Date object is created in switch, which is why the getDay() method is called. The getDay() method returns a day of the week as a number. 0 is returned for Sunday, 1 for Monday, and so on to 6 for Saturday. In the example, the return value is compared with case markers 0 (for Sunday) and 6 (for Saturday). If one of the markers matches, a corresponding output will occur in the JavaScript console. If none of the case markers apply, the return value is 1, 2, 3, 4, or 5, and it’s a normal weekday, so that no case marker will be used here anymore but default - eBook - ePub
- Jeremy McPeak(Author)
- 2015(Publication Date)
- Wrox(Publisher)
case statement then acts like if (myName == "Paul") . If the variable myName did contain the value "Paul" , execution would commence from the code starting below the case "Paul" statement and would continue to the end of the switch statement. This example has only two case statements, but you can have as many as you like.In most cases, you want only the block of code directly underneath the relevant case statement to execute, not all the code below the relevant case statement, including any other case statements. To achieve this, you put a break statement at the end of the code that you want executed. This tells JavaScript to stop executing at that point and leave the switch statement.Finally, you have the default case, which (as the name suggests) is the code that will execute when none of the other case statements match. The default statement is optional; if you have no default code that you want to execute, you can leave it out, but remember that in this case no code will execute if no case statements match. It is a good idea to include a default case, unless you are absolutely sure that you have all your options covered.TRY IT OUT Using the switch Statement
Let’s take a look at the switch statement in action. The following example illustrates a simple guessing game. Type the code and save it as ch3_example3.html - eBook - PDF
- Rob Larsen(Author)
- 2013(Publication Date)
- Wrox(Publisher)
This means: “If the conditions specified are met, run the first block of code; otherwise run the second block.” The syntax follows: if ( condition ){ //code to be executed if condition is true } else{ //code to be executed if condition is false } Returning to the previous example, you can write Good Morning if the time is before noon, and Good Afternoon if it is after noon ( ch10_eg05.js). var date = new Date(); var time = date.getHours(); if ( time < 12 ) { document.body.innerHTML += 'Good Morning
'; } else { document.body.innerHTML += 'Good Afternoon
'; } As you can imagine there are a lot of possibilities for using conditional statements. switch Statements A switch statement enables you to deal with several possible results of a condition. You have a single expression, which is usually a variable. This is evaluated immediately. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code executes. Here is the syntax for a switch statement: switch ( expression ){ case option1: //code to be executed if expression is what is written in option1 break; case option2: //code to be executed if expression is what is written in option2 Conditional Statements ❘ 359 break; case option3: //code to be executed if expression is what is written in option3 break; default: //code to be executed if expression is different from option1, option2, and option3 } You use the break to prevent code from running into the next case automatically. For example, you might check what type of animal a user has entered into a textbox, and you want to write out dif- ferent things to the screen depending upon what kind of animal is in the text input. - eBook - ePub
Decoding JavaScript
A Simple Guide for the Not-so-Simple JavaScript Concepts, Libraries, Tools, and Frameworks (English Edition)
- Rushabh Mulraj Shah(Author)
- 2021(Publication Date)
- BPB Publications(Publisher)
Note: Having a break statement is extremely important in switch statements. If you remove the break statements and execute this code, you will observe that all the cases get executed.Think of a switch statement as a waterfall. It will go through everything unless you apply an obstruction (break) in between.Looping in JavaScript
Let's assume you have a task to display numbers from 1 to 100. What will you do? You would possibly go about creating 100 <p> elements having numbers from 1 to 100, correct? What if I increase the difficulty and make that 100 to 100,000?In such cases, we make use of a JavaScript concept called loops. Looping functions basically begin with an initial value and keep incrementing or decrementing the value, until you resolve a condition.Figure 1.6: Flowchart of loopingThere are two types of looping functions in JavaScript – for loop and while loop (with an alternate version called do…while loop). As shown in figure 1.5 , all the logics follow the same following pattern:- Initialize a variable with a value.
- Test that value.
- Execute if true, quit if false.
In the following table 1.4 , we will understand and compare the different looping methods in JavaScript:for(var i=0; i<100; i++) { console.log(i); } var i=0; while(i<100) { console.log(i); i++; } var i=0; do { console.log(i); i++ } while(i<100); In a for loop, the keyword for is followed by three expressions inside parentheses, separated by semicolon (;).The first expression initializes the value, the second expression sets the condition, and the third expression updates the value. After the statements inside the curly braces are updated, the value is updated by the third expression.As long as the result of the condition expression is true, the statements inside the curly braces will be executed. If the result of the condition becomes false, the code will break out of the for loop.In a while loop, the variable is initialized outside the actual looping statement. The keyword while - No longer available |Learn more
Multimedia Web Design and Development
Using Languages to Build Dynamic Web Pages
- Theodor Richardson, Charles Thies(Authors)
- 2012(Publication Date)
- Mercury Learning and Information(Publisher)
OR condition, which evaluates to true if either side of the statement is true; an example of this is (x|| y)• && represents an AND condition, which evaluates to true only if both sides of the statement are true; an example of this is (x && y)Care must be taken to group chains of these statements correctly so that no more than two arguments are present for each of the concatenated elements. A statement can also be inverted using the NOT operator, which is represented by an exclamation point before the value; an example of this is !(x) which would switch the boolean value of x. These elements can be combined into complex conditional evaluations, such as:An if statement can be extended to include an else case, which will execute if the condition evaluates to false. The structure for this is:An additional if statement can be added after the else to further branch the statement, as in the following:These if statements can also be nested, but care must be taken to make sure they are grouped correctly using the curly braces.The switch statement evaluates a variable and compares it to defined cases. The switch statement typically operates on integers and characters. Each case will have its own set of statements. The break statement must be used at the end of a case to stop operation, or it will continue executing into the next case. A final default statement should be included to catch any exceptions, in which none of the cases matches the variable. The structure of a switch statement is:6.1.6 LoopingLooping is a repeated execution of the same set of statements. This is incredibly helpful if an action needs to be repeated or if a similar action needs to be performed repeatedly (such as counting from 1 to 5). There are three different basic types of loops that can be used in JavaScript: for, while, and do/while. Each of these will continue to operate while a condition is still valid.It is possible to create loops that do not ever stop. This happens if the condition for execution never becomes false; these are called infinite loops - No longer available |Learn more
The JavaScript Workshop
A New, Interactive Approach to Learning JavaScript
- Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, Philip Kirkbride(Authors)
- 2019(Publication Date)
- Packt Publishing(Publisher)
default statement is processed. Otherwise, no code is processed. The syntax is as follows:switch(expression){ case expression_value: //Optional statement(s) break; //optional case expression_value: //Optional statement(s) break; //optional default: //Statement(s) }The following is a flowchart illustrating the switch statement:Figure 3.8: Switch statement flowchartExercise 3.08: Writing a switch Statement and Testing It
We are going to use the switch statement by simulating a game where the player can move their playing pieces using their keyboard. They can move left with the A key, right with the S key, up with the W key, and down with the D key. To simulate a random selection of the keys, in either uppercase or lowercase, from the keyNames string, a variable will be used. Let's get started:- Open the switch-statement.html document in your web browser.
- Open the web developer console window using your web browser.
- Open the switch-statement.js document in your code editor, replace all of its content with the following code, and then save it:var keyNames = "WASDwasd"; var keyName = keyNames.charAt(Math.floor(Math.random() * keyNames.length)); console.log("keyName:", keyName); The Math.floor(Math.random() * keys.length) expression is selecting a number from 0 to 7 that is then used by charAt to select the character from the keyNames string variable.
- Run a few tests by reloading the switch-statement.html web page in your web browser with the console window open. Your results will show selections from the ADWSadws characters. Here are some examples of the console output:keyName: a keyName: S
- eBook - ePub
JavaScript for Gurus
Use JavaScript programming features, techniques and modules to solve everyday problems
- Ockert J. du Preez(Author)
- 2020(Publication Date)
- BPB Publications(Publisher)
switch statement provides a more descriptive way to check a value against multiple variants.The following sample shows how to create a switch statement:- Open a text editor of your choice and enter the following HTML and JavaScript code: <!doctype html> <body> <h1>Switch Statement example</h1> <p>Switch Statement example</p> <script> var objDay = new Date(); switch (objDay.getDay()) { case 0: console.log(“Sunday”); break; case 1: console.log(“Monday”); break; case 2: console.log(“Tuesday”); break; case 3: console.log(“Wednesday”); break; case 4: console.log(“Thursday”); break; case 5: console.log(“Friday”); break; case 6: console.log(“Saturday”); break; default: console.log(“Choose a proper day value”); break; } </script> </body> </html>
- Save the file with an HTML extension, for example Chapter 13.4.html .
- Double-click the file to open it in the default browser.
It looks much more complicated than what it actually is! You create a new Date object named objDay . Then the switch statement starts by testing what day is it currently. It achieves this via the use of the getDay date method.Depending on which day it currently is, that day will get logged to the console window. In my case, it is a Monday . As you can see, day 0 is on a Sunday and day 6 is on a Saturday .If you have even keener eyes, you will notice the little word break; in between each case statement. This is to indicate that the current branch’s code has finished, and the code should not continue through the other cases. - eBook - PDF
- Chris Minnick(Author)
- 2022(Publication Date)
- For Dummies(Publisher)
Because a switch statement will run any statements within any case clause after a clause that evaluates to true, unpredictable results can occur when you forget a break statement. Problems caused by missing break state- ments are not easy to identify because they generally won’t produce errors, but will frequently produce incorrect results. If no match is found in any of the case clauses, the switch statement will look for a default clause and execute the statement it contains. The exception to the rule that you should always use a break statement between case clauses is the default clause. As long as the default clause is the last state- ment in your switch (which it should be), you can safely omit the break after it because the program will break out of the switch after the last statement anyway. Listing 6-1 shows an example of how you might use a switch statement. LISTING 6-1: Using a switch Statement to Personalize a Greeting let languagePreference = "Spanish"; switch (languagePreference){ case "English": console.log("Hello!"); break; case "Spanish": console.log("Hola!"); break; case "German": console.log("Guten Tag!"); break; case "French": console.log("Bon Jour!"); break; default: console.log("I'm Sorry, I don't speak" + languagePreferance + "!"); } 246 BOOK 3 Advanced Web Coding Here We Go: Loop De Loop Loops execute the same statement multiple times. JavaScript has several different types of loops: » for » for ... in » do ... while » while for loops The for statement creates a loop using three expressions: » Initialization: The initial value of a variable, typically a counter. » Condition: A Boolean expression to be evaluated with each iteration of the loop. » Final expression: An expression to be evaluated after each loop iteration. Although it’s not required to use all three expressions in a for loop, all three of them are nearly always included. The for loop is usually used to run code a pre- determined number of times.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.








