Computing the operation
Use switch to select the operator and compute the result.
Computing the operation: the switch statement
We use the switch statement to choose among the four operations. switch (operator) picks the matching branch based on the value of operator.
Each operation is written as a case branch. At the end of a matching case we exit the switch with break; otherwise execution falls through to the next branch. If no case matches, the default branch runs.
The result is assigned to the result variable and finally printed with console.log.
case, break and default
Each case branch compares a value and, if it matches, runs the code below it. For addition you write case "+":, put result = first + second; under it, and exit with break;.
Subtraction uses case "-":, multiplication case "*":, division case "/": in the same pattern. If you forget break, execution falls into the next case and the result is wrong.
If no case matches, the default: branch runs; we put an unknown-operation message there.
Exercise Compute the four operations with switch
The existing code has first, second and operator ready. Now write a switch (operator) statement. Add four case branches: "+", "-", "*", "/". In each branch assign the operation result to result. Add a default branch for an unknown operation and assign a message to result. Print the result with console.log.
Show example solution
// The user's first value
const firstInput = "25";
const operator = "+";
const secondInput = "4";
const first = parseFloat(firstInput);
const second = parseFloat(secondInput);
let result;
switch (operator) {
case "+":
result = first + second;
break;
case "-":
result = first - second;
break;
case "*":
result = first * second;
break;
case "/":
result = first / second;
break;
default:
result = "Unknown operation";
}
console.log("Result: " + result);
Test yourself
-
Complete the switch line
let result; ____ default: result = "Unknown operation"; }Show answer
let result; switch (operator) { default: result = "Unknown operation"; } -
When does the default branch run in a switch statement?
- Always, after all cases
- When no case matches
- Only when the first case doesn't match
- Only when break is not used
Show answer
When no case matches — Correct. default runs when no case matches.
-
Match the switch parts
- switch
- Starts statement, evaluates expression
- case
- Compares a value
- break
- Exits the statement
- default
- Runs when no case matches