Infinity and NaN (numeric global properties)

JS
S
JavaScript

Some basic examples of Infinity and NaN usage. These are special values that can be the result of operations that normally return numbers: NaN and Infinity. Further reading: http://2ality.com/2012/02/nan-infinity.html https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Infinity

1// Infinity
2// ------------------------------
3// Zero Results
4const divide = 1 / Infinity;
5const divide0 = 0 / Infinity;
6
7// Negative Infinity
8const log = Math.log(0);
9const anythingMinus = 1000 - Infinity
10
11// Positive
12const pwr = Math.pow(10, 1000);
13const anythingPlus = 5000 + Infinity
14
15// Division by zero
16const divZero = 4/0; // infinity
17
18
19// NaN
20// ------------------------------
21// String parsing went wrong (NaN)
22const nan = Number("xyz");
23
24console.log(typeof NaN); //number
25
26const check1 = isNaN(NaN); // true
27const check2 = isNaN(22); //false
28const check3 = isNaN('xx'); //true
29
30// ValueOf Override
31// JavaScript calls the valueOf method to convert an object to a primitive value. 
32const obj = { 
33  valueOf: () => NaN
34};
35
36const castToNumber = Number(obj); // NaN
37isNaN(obj); // true
38
39// Valid way of checking of a value is a number
40Number.isNaN = function (value) {
41  return typeof value === 'number' && isNaN(value);
42};
43
44
45function alwaysNaN(x) {
46  this.val = x;
47}
48alwaysNaN.prototype.valueOf = function(){
49  return NaN;
50};
51const n1 = new alwaysNaN(1);
52console.log(n1+6); // implicit call to valueOf
53

Created on 12/6/2017