Check out a free preview of the full Getting Started with JavaScript, v2 course

The "NaN" Lesson is part of the full, Getting Started with JavaScript, v2 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle explains what NaN is, when a NaN will be returned, how to test if a value is of the type NaN, and in what situations it is beneficial to test for NaN values.


Transcript from the "NaN" Lesson

>> Kyle Simpson: There are values that we wanna call out, they have special behaviors, and one that I specifically want to focus on is the NaN value. This is probably one of the most misunderstood of all the values in the JavaScript language. So let's just take a moment to make sure we understand NaN.

If I say var greeting = "Hello class!"; and then I do something with that there value string that doesn't make sense for a string, like I try to divide it by two like we are here in line three. JavaScript is gonna throw up its hands and say, what are you trying to do?

You can't take a string and divide it by two, that doesn't make any sense. That's not a mathematic operation. I can't make Hello, class into a number and then divide it by two, so what am I gonna get? Well, I'm actually get a special kind of value called the NaN value.

So something here is gonna have the NaN value. And it's gonna have it specifically because the divide operator on line three tried to turn the value Hello, class, that string, into a number and that's not a valid number. [LAUGH] So we end up this invalid number called NaN.

Now a lot of people think NaN means is not a number, but it's not quite that. And I wanna call this out because we have a utility called Number.isNaN which would tell us, yes, you do in fact have a NaN. But let me ask you a question, is greeting a number?

Well, clearly greeting is not a number, clearly it's a string. So you'd say, no, it's not a number. And it's definitely not a number, but is it the not a number special NaN value? And the answer is no, it's not. If we say, Number.isNaN for greeting, we get false.

So NaN is a special value that sort of indicates that we've had an invalid numeric operation of some sort. And you should be aware that you should be testing for those. Any place that you do math in your programs, you need to be aware that NaNs can happen.

And once you get a NaN, it's gonna mess up all the other math, so it sort of pollutes all the other operations. It's a really good idea to get familiar with testing the results of mathematic operations, to make sure that you didn't get a NaN.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now