All You Need to Know About Numbers in JavaScript
Table of contents
Number is a datatype in JavaScript that can hold all types of integers, whether signed or unsigned, as well as floating-point numbers.
let number = 60;
let floatingPointNum = 59.89;
We all know that JavaScript is a dynamically typed language, meaning we don't explicitly define the type of a variable. However, if you want to strictly specify that the value you are assigning is of the Number
type, you can use the Number constructor. This will create a Number object, which is not a primitive.
const number = new Number(90);
const number = new Number("90"); // can also pass string
console.log(typeof number);// object
Now there are certain things to you must keep in mind, when we pass undefined
it gives us NaN
which means not a number. When you pass boolean values, true
will result to 1 and false
will be 0. Likewise null
will also give zero. 0 and null are falsy values and 1 is truthy value.
const num = new Number('a45'); //it will give NaN
const num = new Number(undefined); //it will give NaN
const num = new Number(true); //it will give 1
const num = new Number(false); //it will give 0
const num = new Number(null); //it will give 0
Opeartors and comparators
A single js expression like sum = a + 2
is called token, sum
and a
are variables, +
, =
are operators and 2
is a literal. These are some jargons that you need to know but no need to memorize them. There are various kind of opeartors in JavaScript. All the operators that you use to perform arithmetic operation are called arithmetic opeartors like(+,-*,/,%). The =
has a speacial name assignment operator, because we use it to assign a value.
//this will make all arithmetic operators clear to you
console.log(2+2);// 4
console.log(2-2);// 0
console.log(2*2);// 4
console.log(2/2);// 1
console.log(2%2);// 0 this is modulo operator, gives us remainder
console.log(2**3);// 8 this basically means 2^3
Lot of the times in your code you will find adding 1 to a value or subtract 1 from a value. In coding we call it increment (adding 1 to a value) and decrement (subtracting 1 from a value). For that we have increment and decrement opeartors.
let num = 10;
num++;// 11 increment operator, same as num=num+1
num--;// 10 decrement operator, same as num=num-1
This opeator can be used in two ways and both have different meaning. When you put ++ before the variable it performs differently from when you use it after the variable. Take a look at the code below.
//first prints the value and then increments it
let num = 10;
console.log(num++);// 10
//first increments the value and then prints it
let num = 10;
console.log(++num);// 11
//same with -- as well
you can apply some checks on variables, like checking wether two variables have same value or not. For that we use comparators, basically operators that are used to compare values. Based on the check they return true
or false
. Here are some self explainatory examples.
// Equal to (checks only value, not type)
console.log(2 == 2); // true
// Strict equal to (checks both value and type)
console.log(2 === '2'); // false
// Not equal to (checks only value, not type)
console.log(4 != 2); // true
// Strict not equal to (checks both value and type)
console.log(4 !== '4'); // true
// Greater than
console.log(4 > 2); // true
// Less than
console.log(4 < 2); // false
// Greater than or equal to
console.log(5 >= 5); // true
// Less than or equal to
console.log(5 <= 5); // true
BigInt
The Number type in JavaScript can hold numbers in a certain range, when it exceeds the range it cannot hold that number. In that case we have a type known as BigInt
. If you want to learn more about BigInt visit the mdn docs BigInt mdn docs .
//two ways to declare BigInt values
let hugeNumber = new BigInt(9007199254740991);// using BigInt constructor
let otherHugeNum = 9007199254740991n;// appeding n to the end
More about Number object
If you just create a Number object in the browser console, like this new Number()
and then you will see that there are lot of properties attached to it. You can read about all of them in the mdn docs. I will explain some of the important ones, and rest you can learn from docs. Here is an image of the result.
To access the static properties or methods,use dot notation after Number
just like this.
Number.MIN_SAFE_INTEGER
this will give you the minimum safe integer in JavaScript. and Likewise Number.MAX_SAFE_INTEGER
will give you the maximum safe integer in JavaScript.
console.log(Number.MIN_SAFE_INTEGER);//-9007199254740991
console.log(Number.MAX_SAFE_INTEGER);// 9007199254740991
Number.isFinite()
tells you wether the number is finite or not.
console.log(Number.isFinite(1/0));//false
parseInt()
converts a valid string to Integer number and parseFloat()
to floating point number.
console.log(typeof parseInt('123'));// number
console.log(typeof parseFloat('123.45'));// number
Even the opposite can be done using Number.toString()
, to convert number to string.
While working with floating point numbers this method is very useful. Number.toFixed()
. This function works on floating point numbers, Suppose you have a number till 3 decimal places like 123.456
and you want it to show till 1 decimal place then you will do this.
const number=123.456789;
console.log(number.toFixed(2));// 123.46 , change the arg accordingly
Last but not the least we have another method .toLocalString()
. In an e-com app when you have an ammount, let say 10000 and you want to show it in notation; for that you can use this function on that number. This works something like this.
let number = 10000;
// the object argument is optional
let moneyNotation = number.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(moneyNotation); // Output: $10,000
Those were some of the must know static functions and properties of the Number object; you can learn more about them from the mdn docs. Sice we have talke about numbers, there is also another object; specifically to perform mathematical functions and get Mathematical constant. It is the Math
object.
Math Object
Math Object works with Number and not BigInt. to get the value of pi you can use Math.PI
and unlike that you can also retrive the value of some other mathematical constant. Along with that Math object provides functions to perform mathematical operations. Some of them are as follows.
Math.abs(x)
: Returns the absolute value of a numberx
. It makes negative numbers positive and leaves positive numbers unchanged.let absoluteValue = Math.abs(-5); // Result: 5
Math.ceil(x)
: Rounds a numberx
up to the nearest integer.let roundedUp = Math.ceil(4.2); // Result: 5
Math.floor(x)
: Rounds a numberx
down to the nearest integer.let roundedDown = Math.floor(4.8); // Result: 4
Math.round(x)
: Rounds a numberx
to the nearest integer.let rounded = Math.round(4.5); // Result: 5
Math.max(x, y, ...)
: Returns the highest value among the provided numbers.let maxNumber = Math.max(2, 7, 1, 9, 5); // Result: 9
Math.min(x, y, ...)
: Returns the lowest value among the provided numbers.let minNumber = Math.min(2, 7, 1, 9, 5); // Result: 1
Math.random()
: Returns a pseudo-random floating-point number between 0 and 1 (exclusive).let randomValue = Math.random(); // Result: a number between 0 (inclusive) and 1 (exclusive)
Math.sqrt(x)
: Returns the square root of a non-negative numberx
.let squareRoot = Math.sqrt(25); // Result: 5
Math.pow(x, y)
: Returns the result of raisingx
to the power ofy
.let powerResult = Math.pow(2, 3); // Result: 8 (2^3)
Math.sin(x)
,Math.cos(x)
,Math.tan(x)
: Trigonometric functions that return the sine, cosine, and tangent of an angle in radians, respectively.
let sinValue = Math.sin(Math.PI / 2); // Result: 1 (sin(π/2))
So that was a long but still a brief about the number datatype, Number and Math object in JavaScript. I hope you found this article helpful. Try these things on your own to better understand them and keep practicing. If you like tech and coding content like this you can follow me on youtube, facebook and instagram. I post content like this over there. That was it for this blog, peace out.