Menu Home

isNaN()

Hey there! It’s time for another edition of Boring JavaScript. This time, we talk about the ‘isNaN’ method.

You can watch the Boring JavaScript video here.

A Rose By Any Other Name …

Basically, isNaN() will test to see if a variable is … well … not a Number.

console.log(isNaN(1));   // false
console.log(isNaN("virtuoid")); // true 
console.log(isNaN("1")); // false
console.log(isNaN(0x0a)); // false
console.log(isNaN("0x0a")); // false

Lines 1 and 2 are obvious – but the others? Remember that JavaScript is a typeless language. A number inside of a string is still a “number”. And the “0x0a” notation? That’s hexadecimal notation, which is a valid number.

isNaN(), therefore, will return boolean True if JavaScript sees the variable is not a number (or can’t convert a string to a number), and will return boolean False if JavaScript can indeed convert it to a number.

And That’s It, Right?

Well, yes – and no.

The true definition of the term NaN (which is a valid JavaScript construct – look it up) can be, to put it mildly – a little confusing. Check out these examples:

console.log(isNaN(true));  // false
console.log(isNaN(null));  // false

Yes, that’s right – JavaScript believes that a boolean value of True or False is indeed a number, as is null. Weird, right? That’s because of the typeless neature of JavaScript. Try the following:

console.log(1 + true); // prints 2
console.log(1 + false); // prints 1
console.log(1 + null); // prints 1

JavaScript coerces boolean values to 0 and 1 (false and true respectively), and null to 0. It makes sense, then, that JavaScript believes booleans and null to be numbers.

It gets better.

console.log(isNaN(""));  // prints false

Yes, even a blank string is a Number, according to JavaScript.

What’s the Takeaway?

Mozilla Developer Network has a great article on isNaN (and NaN in general). If you want to look at tll the weird goings-on with this function, that’s a great place to look.

And now, the video

If reading isn’t your thing, here is a video we made about this subject.

Shameless Plug

Make sure you follow us on all our social media sites:

Facebook

YouTube

Twitter


Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: