Project design
- Node.js course
- Beginner
- Lesson 19/116
- 6 min
Design the structure of the calculator project and write the skeleton code.
Project: Calculator
In this 5-lesson project you will build a calculator. Each lesson adds one piece, and by the final lesson you will have a complete command-line application.
You will use what you learned before:
- defining functions with
function - writing output with
console.log - declaring variables with
constandlet - conditions with
if
You will also learn to read command-line arguments with process.argv and to branch with switch.
Defining add with function
In JavaScript, you define a function with the function keyword. Example: function add(a, b) { ... }.
The a and b inside the parentheses are parameters; when the function is called, values arrive here. The code between the curly braces is the function body.
To return a result, you use return. The expression return a + b gives back the sum of a and b. The calling code uses this value.
Practice Define the add function
Define an add(a, b) function that returns a + b. The console.log(add(3, 4)) call at the end of the file is ready; you only write the function.
Starter code
// Define the add function here
console.log(add(3, 4));Sample solution
function add(a, b) {
return a + b;
}
console.log(add(3, 4));Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the first step in this project?
- Define all functions at once
- Process command-line arguments first
- Start with a single function like add Correct answer
- Write the test file
Explanation: Starting with small steps is best.
2 Match the project pieces
| Term | Meaning |
|---|---|
add |
Addition function |
subtract |
Subtraction function |
multiply |
Multiplication function |
divide |
Division function |
3 Function skeleton
function add(a, b) {
____
}
function add(a, b) {
return a + b;
}
Explanation: return a + b; returns the sum.