Project: Calculator
Overview of the 5-lesson calculator project: you will operate on two numbers and an operator.
Project: Calculator
In this 5-lesson project you'll build a calculator. Each lesson adds one piece, and by the final lesson you'll have a complete app.
You'll use:
constandletfor variablesparseFloatto convert a string to a numberswitchto choose the operationifandisNaNfor validationconsole.logto print the result
Ready? Let's start.
Project roadmap
We'll build the calculator step by step. The first lesson introduces user input: we store the first number as a string. The second lesson adds the second number and the operation; we convert the strings to numbers with parseFloat.
The third lesson computes the four operations with switch. The fourth lesson catches invalid input with isNaN. The final lesson adds a division-by-zero check and completes the project.
Each lesson's starting code contains the previous lesson's solution, so you build on top of it.
Calculator flow
The calculator has three stages: input, compute and output. First we take two numbers and an operation from the user. We store the numbers as strings because input always arrives as text.
Then we convert the strings to numbers with parseFloat. We compute the result with switch based on the operation. Finally we show the result with console.log.
Invalid input is caught with isNaN and an error message is shown.
Exercise Store the first value
Start the calculator. Declare a const firstInput variable representing the first number the user entered, and put the string "25" inside it. Then print firstInput with console.log.
Show example solution
// The user's first value
const firstInput = "25";
console.log(firstInput);
Test yourself
-
When you store the user's value in a variable, what is its data type at first?
const firstInput = "25";- String (text)
- Number
- Boolean
- Undefined
Show answer
String (text) — Correct. A value in quotes is a string; you convert it to a number with parseFloat.
-
Match each lesson to the piece it adds
- Lesson 1
- User input and first variable
- Lesson 2
- Second number, operation and parseFloat
- Lesson 3
- Four operations with switch
- Lesson 4
- Validation with isNaN
- Lesson 5
- Division by zero and completion