In a JavaScript switch statement, cases can be grouped to share the same code. ![]() Then, the switch statement executes cases based on the user input. ![]() In above program, the user is asked to enter either +, -, * or /, and two operands. Example 3: Simple Calculator // program for a simple calculatorĬonst operator = prompt('Enter operator ( either +, -, * or / ): ') Ĭonst number1 = parseFloat(prompt('Enter first number: ')) Ĭonst number2 = parseFloat(prompt('Enter second number: ')) Ĭonsole.log(`$`) Let's write a program to make a simple calculator with the switch statement. Notice in the above example, 1 does not match with "1". Note: In JavaScript, the switch statement checks the cases strictly (should be of the same data type) with the expression's result. Here, the expressions's result matches with case 1. Then the switch statement goes to the second case.So the expression's result does not match with case "1". In JavaScript, the switch statement checks the value strictly.In the above program, an expression a = 1 is evaluated with a switch statement. The break statement terminates the block and control flow of the program jumps to outside of the switch block.Įxample 2: Type Checking in switch Statement // program using switch statement.Here, the expression's result matches with case 2. The expression's result is evaluated with case 1 which results in false. ![]() In the above program, an expression a = 2 is evaluated with a switch statement.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |