Programming Basics

Simple calculator

⬅ Version FR

We’re going to explore the fundamentals of JavaScript by building a calculator. You will therefore learn to manipulate variables, operators, conditions…

Setting up the workshop

Prerequisites: JS Basics 01, JS Basics 02

Important: the first steps must be done with your terminal!

Create a new simple-calculator folder and create an empty index.html file inside.

Open index.html with VSCode and add HTML5 structure.

In the <body> tag add a <script> tag with the following code:

console.log("Hello wilders!");

Open the index.html file in a browser, and display the console (F12), what do you see? If you see your message above, it means everything is working fine!

To be sure, explain what you did to your colleagues.

What you get

Here is the basic HTML5 structure as well as the addition of the <script> tag with the console.log("Hello wilders!"); code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Simple calculator</title>
  </head>
  <body>
    <script>
      console.log("Hello wilders!");
    </script>
  </body>
</html>

In the inspector:

"Hello wilders!" in the inspector

The first instructions

Prerequisites: JS Basics 03, JS Basics 04

The first step in creating our calculator is to instantiate variables.

Create 3 variables:

Now you will do as many console.log as you have variables. What do you see ?

What if we ask the user? Replace the 1 and 2 values with calls to the prompt function (see documentation). Warning, not the + value of operator, just the values 1 and 2 !

What do console.logs display?

We understand the console

Add a console.log of firstValue + secondValue: what does it show? Why ? What do we have to do ? Hint: look at this documentation.

And now, what does the console.log show? Why ?

To be sure, explain what you did to your colleagues.

We work on the operator

Prerequisites: JS Basics 05

A little housekeeping: delete all console.log.

You are going to add a condition on the operator variable:

Explain what you did to your colleagues.

Latest instructions

Prerequisites: JS Basics 05

You are almost done, now that you have made a first condition, add the conditions for all operators:

☆ Prerequisites: JS Basics 06

☆ Bonus: Move all code into a function to make it reusable.

The price is right

For highly motivated people 🤘

Do you like to play?

So it’s time to create a little game!

Same steps as for the part “Setting up the workshop”, you just have to change the name of the folder.

gift: const rightPrice = Math.ceil(Math.random() * 100);

The game ends when it is won.