Image for post
Image for post
NaN or Not A Number can cause issues when you’re trying to pay your gas bill.

In JavaScript, the number type can be either an integer or a float, as such…

let integer = 10;

Now, NaN stands for “Not A Number”, and it means, well, whatever you’re looking at is not a number, that being said we can’t do something like…

let example = 'banana';

Because even though our example variable is not a number, it is still a valid data type and JavaScript tells us what that type is. However, if we did something like this…

let example = 'banana' * 10;

There’s our NaN! (A quick aside, our typeof(example) outputs number because NaN is still a number type, according to JavaScript, however it does not equal any value, even itself. NaN === NaN yields false) This example kind of highlights the main benefit of NaN, which is to find where we might have a failed operation on a number.

To manually test if an operation will yield NaN, we can use the global function isNaN()

let answer = 100 + 0 / 0;

We could also use Number.isNaN()

let answer = 100 + 0 / 0;

The difference between Number.isNaN() and isNaN() is that Number.isNaN() will not convert its argument into a number…

isNaN('bananas') // Outputs true

In these examples, isNaN() converts ‘bananas’ into a number, which it is of course not, and tells us that it is true that ‘bananas’ is NaN. Conversely, Number.isNaN() does not perform this conversion and tells us that it is false that ‘bananas’ does not equal NaN.

Situations where you may run into NaN

1. Parsing Integers

When parsing fails in JavaScript you’ll get a NaN

parseInt('bananas') // Outputs NaN

2. Using undefined as an operand

If we try to use undefined in arithmetical operations…

console.log( undefined + 10 ) // Outputs NaN

3. Using NaN as an operand

The same idea as above…

console.log( NaN + 10 ) // Outputs NaN

4. When there is an indeterminate form

When arithmetical operations can’t quite give us a straight answer…

console.log( 100 + 0 / 0 ) // Outputs NaN

5. Invalid arguments in a math function

More things that math doesn’t like…

Math.pow(-1, 1.5) // Outputs NaN

Well there you have it, a quick run through of NaN or “Not a Number” and some situations where you may run into it in the wilds. Just remember that NaN can be your friend and help you find some errors in operations in your code.

I hope this helps, and thanks for reading!

Computer Support Tech turned Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store