Saturday, May 12, 2018

JS Number

NaN - NOt a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):

Example

var x = 100 / "Apple" // x will be NaN (Not a Number)
However, if the string contains a numeric value , the result will be a number:

Example

var x = 100 / "10";     // x will be 10
Try it Yourself »
You can use the global JavaScript function isNaN() to find out if a value is a number:

Example

var x = 100 / "Apple";
isNaN(x);               // returns true because x is Not a Number
Try it Yourself »
Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:

Example

var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN
Try it Yourself »
Or the result might be a concatenation:

Example

var x = NaN;
var y = "5";
var z = x + y;         // z will be NaN5
Try it Yourself »
NaN is a number: typeof NaN returns number:

Example

typeof NaN;            // returns "number"
Try it Yourself »

Infinity (https://www.w3schools.com/js/js_numbers.asp)

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Example

var myNumber = 2;
while (myNumber != Infinity) {          // Execute until Infinity    myNumber = myNumber * myNumber;
}
Try it yourself »
Division by 0 (zero) also generates Infinity:

Example

var x =  2 / 0;          // x will be Infinityvar y = -2 / 0;          // y will be -Infinity
Try it Yourself »
Infinity is a number: typeof Infinity returns number.

Example

typeof Infinity;        // returns "number"

Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals:
var x = 123;
But numbers can also be defined as objects with the keyword new:
var y = new Number(123);

Example

var x = 123;
var y = new Number(123);

// typeof x returns number// typeof y returns object
Try it yourself »
Do not create Number objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
When using the == operator, equal numbers are equal:

Example

var x = 500;             
var y = new Number(500);

// (x == y) is true because x and y have equal values
Try it Yourself »
When using the === operator, equal numbers are not equal, because the === operator expects equality in both type and value.

Example

var x = 500;             
var y = new Number(500);

// (x === y) is false because x and y have different types
Try it Yourself »
Or even worse. Objects cannot be compared:

Example

var x = new Number(500);             
var y = new Number(500);

// (x == y) is false because objects cannot be compared
Try it Yourself »
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects will always return false.

No comments:

Post a Comment