Understanding how to work with numbers is fundamental to programming. Numerical operations form the backbone of many programming tasks. As a beginner programmer, mastering basic mathematical operations will enable you to solve real-world problems, from creating shopping cart totals to building complex mathematical applications. JavaScript provides powerful tools for number manipulation which we will learn in this section.
You can represent numbers in many different ways:
Integers are whole numbers, without a decimal point. For example: 1, 10000 , -81 , 0
const sum = 1000;
Floating point numbers also mean numbers with a decimal point
const average = 54.86;
It is possible to represent numbers using exponential notation.
const = 4e10; // 40000000000
const million = 10e6; // 1000000
const electron = 9.1e-31; // very small
To improve readability for large numbers, you can use underscores (_) as separators:
const million = 1_000_000;
const billion = 1_000_000_000;
Pay attention to the following important example
const first = '4';
const second = 4;
typeof first; // 'string'
typeof second; // 'number'
first and second are completely different types! first is a string containing the character ‘4’ while second is the number 4.
<aside> ⌨️
Hands on: Open the Node.JS REPL and replicate the example above to verify the results.
</aside>
<aside> ⚠️
When working with numbers, make sure you do not accidentally use strings that contain numbers.
</aside>
In the next section we will show you how to convert from a string to a number.
Thee are multiple ways converting a string to a number in JavaScript. The best way is to use the special Number function:
Number("42"); // 42
Number("3.14"); // 3.14
Number(" 7 "); // 7
Number("42px"); // NaN --> Failed conversion
However, the function will fail if the string contains an invalid number.
To try parsing string that contains a mix of characters and numbers, use Number.parseInt for integers and Number.parseFloat for floating point numbers:
Number.parseInt("42px"); // 42
Number.parseFloat("3.14kg"); // 3.14
Number.parseInt("hello123"); // NaN --> Failed conversion
parseInt and parseFloat will stop parsing at the first invalid character.
<aside> 💭
You may also see parseInt and parseFloat used without the Number prefix. This is older syntax, but it remains valid.
</aside>
NaN is a special value representing Not-A-Number. It is the result of a failed conversion to a number, indicating to the developer that the conversion was unsuccessful.
You can use the isNaN function to check if a string contains a valid number:
Number.isNaN('123'); // true
Number.isNaN('-32.42'); // true
Number.isNaN('JavaScript') // false
Number.isNaN(' ') // false
<aside> 💡
Checking for NaN is very useful to do before performing the conversion to a number. This way, if we know we will fail, we can show an error the the user.
</aside>
Watch the following 6-minute video, which summarises the concepts covered so far and provides additional examples.
https://www.youtube.com/watch?v=3Ul9gYweEPs
JavaScript supports the common arithmetic operators
+-*/%**8 + 9 // -> 17, adds two numbers together.
20 - 12 // -> 8, subtracts the right number from the left.
3 * 4 // -> 12, multiplies two numbers together.
10 / 5 // -> 2, divides the left number by the right.
8 % 3 // -> 2, as 3 goes into 8 twice, leaving 2 left over.
2**10 // -> 1024, raises 2 to the power of 10.
The remainder operator %, despite its appearance, is not related to percents. It gives you what is left over after you divide one number by another. Here is how it works:
10 % 3
You ask: how many times does 3 fit into 10?
It fits 3 times (3 × 3 = 9), and 1 is left over
So:
10 % 3 // -> 1
Another example
8 % 2 // -> 0 (because 8 divides evenly by 2)
7 % 2 // -> 1 (2 goes into 7 three times = 6, remainder is 1)
The remainder operator found to be extremely useful for different common use cases:
const number1 = 127;
const number2 = 128;
number1 % 2 // -> 1 (odd)
number2 % 2 // -> 0 (even)
const number = 361287;
number1 % 10 // -> 7, the last digit
number1 % 100 // -> 87, the last two digits
const totalSeconds = 5311
const hours = totalSeconds / 3600;
const minutes = (totalSeconds / 60) % 60;
const seconds = totalSeconds % 60;
// 1 hour, 28 minutes and 31 seconds
<aside> ⌨️
Hands on: Create a small application to practice the concepts above:
Define two variables n1 and n2 , assign two numbers to them and using console.log show the results of all the operations we learned: + - * / % ** .
</aside>
We often need to apply an operator to a variable and store the result back in that same variable.
let number = 10;
number = number + 20; // -> number is now 30
number = number * 10; // -> number is now 300;
You can also you the short version of the operators:
let number = 10;
number += 20; // same as `number = number + 20`
number *= 10; // same as `number = number * 10`