30 Days Of JavaScript

Day 1: Simple Types

Lesson 5: Numbers

We can store numbers in variables as well.

1const myAge = 35;

Of course in this case my age changes every year so we shouldn't store it as a const if we want to increase it. We should use a variable instead.

1let myAge = 35;
2myAge = myAge + 1;

You can see here I have taken myAge added 1 to it and set the new value to myAge this is very common and totally ok todo in JavaScript. The code to the right of the = runs and then the result is stored in myAge

Test this yourself in the play ground below:

Was this what you expected? myAge starts at 35, we then add 1 to it so it goes to 36. So in that final calculation we do 36 + 36 + 1 which is 73.

All mathematical operators are available to us:

1const add = 3 + 5;
2const subtract = 3 - 4;
3const multiply = 3 * 3;
4const divide = 3 / 2;

JavaScript will even handle negative and decimal numbers for us with no problem. So the result of subtract and divide above won't cause a problem and can be used in further calculations as well (this isn't the case in all programming languages).

There is one more handy mathematical operator I want to talk about here, the modulo operator. This is like divide but it gives you the remainder as a number. Which sounds weird and useless but it gets used more than you would think, and is a key part of solving a well known interview questions called Fizz Buzz.

Let's take a look, heightOfBrick and heightOfWallNeeded are both in cm, by using the modulo operator we find out that the last brick row height will have to be 9 cm

Take a minute to use this playground to work something out. Maybe how to convert from one type of measurement units (like cm) to another (such as inches).

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co