Skip to main content

Checking for NaN in JavaScript

What is NaN?

NaN, in JavaScript, can be many things. In fact, it can be almost anything, so long as it is Not a Number. Its type is technically “number” (when evaluated with “typeof”), although it stands for Not a Number.

What causes values to become NaN?

Values can become NaN through a variety of means, which usually involve erroneous math calculations (such as 0/0), or as a result of type coercion, either implicit or explicit. A common example is when you run parseInt on a string that starts with an alphabetical character. This isn’t exclusive to parseInt, as it also applies when using explicit coercion with Number(), or with the unary “+” operator.

How do you check for NaN?

Before selecting a method for checking for NaN, how should you not check for NaN?

NaN is a bizarre value in JavaScript, as it does not equal itself when compared, either with the loose equality (==) or strict equality (===) operator. NaN is the only value in the entire language which behaves in this manner with regards to comparisons.

For example, if parseInt(“a”) returns NaN, then parseInt(“a”) === NaN will return false. This may seem strange, but it makes perfect sense after thinking about what NaN really is.

NaN doesn’t tell you what something is, it tells you what it isn’t.

These two different strings being passed to parseInt() will both return NaN.

parseInt(“abc”) // NaN
parseInt(“def”) // NaN

Both statements return NaN, but are they really the same? Maybe, but it certainly makes sense why JavaScript would disagree, given that they are derived from different string arguments.

Here are a few examples of strict inequality comparisons, which demonstrate the inconsistency of NaN.

2 !== 2 // false
true !== true // false
abc” !== “abc// false
...
NaN !== NaN // true

Method 1: isNaN or Number.isNaN

JavaScript has a built-in method, appropriately named “isNaN,” which checks for NaN. There is a newer function called Number.isNaN, which is included in the ES2015 spec.

The difference between isNaN and Number.isNaN is that isNaN coerces the argument into a number type. To avoid complicated and unexpected outcomes, it is often advised to use the newer, more robust Number.isNaN to avoid these side effects. Number.isNaN does not perform any forcible type conversion, so it simply returns the boolean based on the parameter.

Here is an example of the difference between the two methods:

isNaN(undefined) // true
Number.isNaN(undefined) // false

isNaN, when passed undefined, returns true because undefined becomes NaN after number coercion. You can test this yourself by running Number(undefined). You will find that it returns NaN.

Number.isNaN, on the other hand, returns false. This is because no coercion takes place, and undefined is not NaN, it is simply undefined.

It is also important to note that Number.isNaN is a newer (ES2015) method in JavaScript, so browser support for Number.isNaN is not as stable as isNaN, which has been around since ES1 (1997).

Method 2: Object.is

Object.is is a JavaScript method which checks for sameness. It generally performs the same evaluations as a strict equality operator (===), although it treats NaN differently from strict equality.

Object.is(0, -0) will return false, while 0 === -0 will return true. Comparisons of 0 and -0 differ, as do comparisons of NaN. This concept is called “Same-value-zero equality.”

NaN === NaN // false
Object.is(NaN, NaN) // true

Object.is(NaN, NaN) will in fact return true, while we already know that NaN === NaN returns false. That makes this yet another valid way to check if something is not a number.

Conclusion

Between the given methods of checking for NaN, the most common is to use the global isNaN function, or the ES2015 Number.isNaN method. While method #2 is valid, most people will typically use isNaN or Number.isNaN, which were created specifically for checking for NaN.

Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...