By Dmitri Pavlutin

Translation: Crazy geek

Original text: dmitripavlutin.com/nan-in-java…

Reproduced without permission

Number types in JavaScript include integers and floating point numbers:

const integer = 4;
const float = 1.5;

typeof integer; // => 'number'
typeof float;   // => 'number'
Copy the code

There are also two special numeric values: Infinity (the Number larger than any other Number) and NaN (the concept of “Not A Number”) :

const infinite = Infinity;
const faulty = NaN;

typeof infinite; // => 'number'
typeof faulty;   // => 'number'
Copy the code

While the direct use of NaN is rare, it can come up surprisingly after ineffective manipulation of numbers.

Let’s take A closer look at NaN special values: how to check if A variable has NaN, and how to create A “Not A Number” value.

NaN number

A Number type in JavaScript is A collection of all numeric values, including “Not A Number”, plus infinity, and minus infinity.

“Not A Number” can be accessed using A special expression NaN, A global object, or an attribute of the Number function:

typeof NaN;        // => 'number'
typeof window.NaN; // => 'number'
typeof Number.NaN; // => 'number'
Copy the code

Despite the numeric type, “Not A Number” is A value that does Not represent A real Number. NaN can be used to represent bad number operations.

For example, multiplying a number by undefined is not a valid operation, so the result is NaN:

1 * undefined;     // => NaN
Copy the code

Likewise, trying to parse an invalid numeric string (such as ‘Joker’) also results in NaN:

parseInt('Joker'.10); // => NaN
Copy the code

Check if nans are equal

An interesting feature of NaN is that it does not equal any value even when NaN itself is used:

NaN= = =NaN; // => false
Copy the code

This behavior is useful for checking if a variable is NaN:

const someNumber = NaN;

if(someNumber ! == someNumber) {console.log('Is NaN');
} else {
  console.log('Is Not NaN');
}

// logs "Is NaN"
Copy the code

Only if someNumber is a NaN, someNumber! == someNumber is true. Therefore, the output of the above code snippet to the console Is “Is NaN”.

JavaScript uses built-in functions to detect NaN: isNaN() and number.isnan () :

isNaN(NaN); // => true
isNaN(1);   // => false

Number.isNaN(NaN); // => true
Number.isNaN(1);   // => false
Copy the code

The difference between these functions is that number.isnan () does not convert its arguments to numbers:

isNaN('Joker12');        // => true
Number.isNaN('Joker12'); // => false
Copy the code

IsNaN (‘Joker12’) converts the argument ‘Joker12’ to a number, NaN. So this function returns true.

On the other hand, number.isnan (‘Joker12’) checks if the parameter is a NaN without converting. This function returns false because ‘Joker12’ is not equal to NaN.

The operation that results in NaN

1 Parsing numbers

In JavaScript, you can convert strings of numbers to numbers.

For example, you can easily convert the string ‘1.5’ to float 1.5:

const numberString = '1.5';
const number = parseFloat(numberString);

number; / / = > 1.5
Copy the code

When a string cannot be converted to a number, the parsing function returns NaN: indicating parsing failure. Here are some examples:

parseFloat('Joker12.5'); // => NaN
parseInt('Joker12'.10); // => NaN
Number('Joker12');       // => NaN
Copy the code

When parsing a number, it is best to verify that the result is NaN:

let inputToParse = 'Invalid10';
let number;

number = parseInt(inputToParse, 10);
if (isNaN(number)) {  number = 0;
}

number; / / = > 0
Copy the code

Parsing inputToParse failed, so parseInt(inputToParse, 10) returns NaN. The condition if (isNaN(number)) is true and number is assigned to 0.

2 undefinedAs an operand

Using undefined as an operand in arithmetic operations such as addition and multiplication produces NaN.

Such as:

function getFontSize(style) {
  return style.fontSize;
}

const fontSize = getFontSize({ size: 16 }) * 2;
const doubledFontSize = fontSize * 2;

doubledFontSize; // => NaN
Copy the code

GetFontSize () is a function that accesses the fontSize property from the style object. When getFontSize({size: 16}) is called, undefined (fontSize does not exist in {size: 16} objects).

FontSize * 2 is evaluated as undefined * 2, resulting in NaN.

“Not A Number” is generated when A missing attribute or function that returns undefined is used as A value in an arithmetic operation.

A good way to prevent NaN is to ensure that undefined does not perform arithmetic operations and needs to be checked at all times.

3 NaNAs an operand

NaN values are also generated when the operand of an arithmetic operation is NaN:

1 + NaN; // => NaN
2 * NaN; // => NaN
Copy the code

NaN pervades arithmetic operations:

let invalidNumber = 1 * undefined;
let result = 1;
result += invalidNumber; // appendresult *= 2; // duplicate
result++;                // increment

result; // => NaN
Copy the code

After appending an invalidNumber value (with ‘NaN’) to result, the operation on the result variable is broken.

4 Indeterminate form

NaN values are generated when the arithmetic operation takes an uncertain form.

Division operations like 0/0 and Infinity/Infinity

0 / 0;               // => NaN
Infinity / Infinity; // => NaN
Copy the code

Multiply 0 and Infinity:

0 * Infinity; // => NaN
Copy the code

Infinity addition with different symbols:

-Infinity + Infinity; // => NaN
Copy the code

Invalid mathematical function argument

Square root of a negative number:

Math.pow(2 -.0.5); // => NaN
(2 -) * *0.5;       // => NaN
Copy the code

Or the logarithm of a negative number:

Math.log2(2 -); // => NaN
Copy the code

conclusion

The JavaScript concept of “Not A Number” represented by NaN is useful for representing bad Number operations.

Even NaN itself is not equal to any value. The recommended way to check if a variable contains NaN is to use number.isnan (value).

Failure to convert A string Number to A Number type may result in “Not A Number” being displayed. It’s a good idea to check whether parseInt(), parseFloat(), or Number() returns NaN.

Undefined or NaN as operands in arithmetic operations usually result in NaN. Handling undefined correctly (providing default values for missing attributes) is a good way to prevent this.

Uncertain forms or invalid arguments of mathematical functions can also result in “Not A Number”. But that rarely happens. Here’s my pragmatic suggestion: NaN? Check for undefined!

Welcome to the front End public account: Front End Pioneer, get free front end TypeScript tutorials.