Node.js
Putting it together
Combine all parts into a working CLI calculator.
Putting it together
In the final lesson we will combine all pieces: four functions, process.argv reading, and branching with switch. The calculator will run with commands like node calc.js add 5 3.
The op variable holds the operation type ('add', 'subtract', 'multiply', 'divide'). a and b are the numbers.
With switch, the correct function is called based on op and the result is printed. This is the heart of a small CLI application.
A menu with switch
switch branches based on a variable's value. Each case label matches one value; the code of the matching case runs.
Example: switch (op) { case 'add': console.log(add(a, b)); break; ... }. With break you exit the branch; otherwise the following cases also run (fall-through).
If no case matches, the default block runs. This is a safety net against unknown commands.
Exercise Full calculator with switch
Write a switch(op). Under case 'add': call console.log(add(a, b)), under case 'subtract': call console.log(subtract(a, b)), under case 'multiply': call console.log(multiply(a, b)), under case 'divide': call console.log(divide(a, b)). Add break; to each case. The program is run as node calc.js add 5 3.
Show example solution
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) return 0;
return a / b;
}
const op = process.argv[2];
const a = Number(process.argv[3]);
const b = Number(process.argv[4]);
switch (op) {
case "add":
console.log(add(a, b));
break;
case "subtract":
console.log(subtract(a, b));
break;
case "multiply":
console.log(multiply(a, b));
break;
case "divide":
console.log(divide(a, b));
break;
}
Test yourself
-
What does a switch statement do?
- Starts a loop
- Defines a function
- Branches based on a value
- Throws an error
Show answer
Branches based on a value — switch branches based on a value.
-
case block
switch (op) {
____
console.log(add(a, b));
break;
}
Show answer
switch (op) {
case "add":
console.log(add(a, b));
break;
}
-
Match the switch concepts
- switch
- Branch statement
- case
- Value label
- break
- Exit the branch
- default
- When none matches
Next lesson: Arithmetic operators