253 - 1 = 9007199254740991
Any number greater than this value will be represented as
You can use this property to check if a number is within the maximum integer range. For example:
Keep in mind that
Infinity, which represents an infinitely large value.
For example, suppose you have the following code:
let x = Number.MAX_SAFE_INTEGER; // 9007199254740991 let y = x + 1; console.log(y); // 9007199254740992
In this example, the variable
However, if we add a larger number to
x, such as 2, the behavior becomes unpredictable:
let x = Number.MAX_SAFE_INTEGER; // 9007199254740991 let y = x + 2; console.log(y); // 9007199254740992
In this case, the addition operation does not produce the expected result. Instead, the value of
y is the same as the value of
So what happens if you need to work with a number larger than this maximum value? There are a few approaches you can take:
- Use a string: If you need to perform calculations on a very large number, you can represent it as a string and perform string operations on it. This approach allows you to work with numbers that are too large to fit into the Number data type, but it can be slower and more cumbersome.
- Use scientific notation: If you just need to display a very large number, you can use scientific notation to represent it. For example, 1000000000000000000 can be represented as 1e+18.
The Math object provides us with various methods and properties that can be used to handle numbers easily. Some of the most commonly used methods of the Math object are:
Math.floor(): This method returns the largest integer less than or equal to a given number.
Math.ceil(): This method returns the smallest integer greater than or equal to a given number.
Math.round(): This method returns the value of a number rounded to the nearest integer.
Math.abs(): This method returns the absolute value of a given number.
Math.random(): This method returns a random number between 0(inclusive) and 1(exclusive).
Math.floor() method to round down a number to the nearest integer. Similarly, the
Math.ceil() method can be used to round up a number to the nearest integer.
The Math object also provides us with various mathematical constants such as
Math.PI which gives us the value of π, and
Math.E which gives us the value of the mathematical constant e.