Number in Javascript in detail

ยท

7 min read

Number is a datatype in javascript that can hold all types of Integers, be it signed or unsigned, floating point numbers, etc.

let number = 60;
let floatingPointNum = 59.89;

We all know that JavaScript is a dynamically typed language that means we don't explicitly define the type of a variable, so if you want to Strictly say that the value you are assigning is a Number type, for that 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.

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 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 js 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 js 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 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 and you can learn more about them from the mdn docs. Sice we have talke about numbers, there is also another object to perform mathematical functions and get Mathematical constant. It is the Math object.

Math

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 just like this. The Math object also provides you some functions to perform mathematical operations. Some of them are as follows.

  1. Math.abs(x): Returns the absolute value of a number x. It makes negative numbers positive and leaves positive numbers unchanged.

     let absoluteValue = Math.abs(-5); // Result: 5
    
  2. Math.ceil(x): Rounds a number x up to the nearest integer.

     let roundedUp = Math.ceil(4.2); // Result: 5
    
  3. Math.floor(x): Rounds a number x down to the nearest integer.

     let roundedDown = Math.floor(4.8); // Result: 4
    
  4. Math.round(x): Rounds a number x to the nearest integer.

     let rounded = Math.round(4.5); // Result: 5
    
  5. Math.max(x, y, ...): Returns the highest value among the provided numbers.

     let maxNumber = Math.max(2, 7, 1, 9, 5); // Result: 9
    
  6. Math.min(x, y, ...): Returns the lowest value among the provided numbers.

     let minNumber = Math.min(2, 7, 1, 9, 5); // Result: 1
    
  7. 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)
    
  8. Math.sqrt(x): Returns the square root of a non-negative number x.

     let squareRoot = Math.sqrt(25); // Result: 5
    
  9. Math.pow(x, y): Returns the result of raising x to the power of y.

     let powerResult = Math.pow(2, 3); // Result: 8 (2^3)
    
  10. 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 js. 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 and facebook. I post content like this over there. Have a good day, keep coding and Goodbye.

ย