JavaScript Numbers

JavaScript Numbers

ยท

4 min read

The Number data type in JavaScript represents numeric data. JavaScript does not define different types of numbers like integers, floating-point, etc. JavaScript has only one type of number and the numbers can be written with or without decimals. The maximum number of decimals is 17.

var x = 3.14;
var y = 3;

console.log(x);
console.log(y);

Integers (numbers without a period or exponent notation) are accurate up to 15 digits.

var x = 999999999999999;       // x will be 999999999999999
var y = 9999999999999999;    // y will be  10000000000000000

Extra large or small numbers can be written with exponent notation.

var x = 123e5;     // x will be 12300000
var y = 123e-5;   // y will be 0.00123

Adding numbers and strings

JavaScript uses the + operator for both addition and concatenation. Numbers are added and strings are concatenated.

When you add two numbers, the result is a number.

var x = 50;
var y = 50;
var z = x + y;        // z will be 100

When you add two strings, the result is string concatenation.

var x = "50";
var y = "50";
var z = x + y;       // z will be 5050(a string)

When you add a number and a string, the result is string concatenation.

var x = 10;
var y = 20;
var z = "30";
var result = x + y +z;       //result will be 3030

The JavaScript interpreter works from left to right. 10 and 20 will be added because x and y are both numbers. Then 30 + "30" is concatenated because z is a string.

Numeric Strings

JavaScript strings can have numeric content. In numeric operations, JavaScript will try to convert strings to numbers.

var x = "40";
var y = "20"
var z = x - y;       // z will be 20

var x = "40";
var y = "20";
var z = x * y;     // z will be 800

var x = "40";
var y = "20";
var z = x / y;     // z will be 2

However, in addition, JavaScript will concatenate the strings.

var x = "40";
var y = "20";
var z = x + y;    // z will be 4020(it will not be 60)

NaN - Not a Number.

NaN represents that the value is not a legal number. When you try to do arithmetic on a non-numeric string, the result will be NaN.

var x = 100 / "Laptop";      // x will be NaN

Conclusion

JavaScript Number data type helps us store numerical data and perform arithmetic operations on the values.