Putting it together
- Node.js course
- Beginner
- Lesson 23/116
- 6 min
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.
Practice 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.
Starter code
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]);
// Use switch on op to select the right operation and log the resultSample 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;
}Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a switch statement do?
- Starts a loop
- Defines a function
- Branches based on a value Correct answer
- Throws an error
Explanation: switch branches based on a value.
2 case block
switch (op) {
____
console.log(add(a, b));
break;
}
switch (op) {
case "add":
console.log(add(a, b));
break;
}
Explanation: case 'add': label matches the op value.
3 Match the switch concepts
| Term | Meaning |
|---|---|
switch |
Branch statement |
case |
Value label |
break |
Exit the branch |
default |
When none matches |