Skip to content

How to avoid NaN in JavaScript | Basic code

  • by

JavaScript NaN is the return value from operations that have an undefined numerical result. NaN is an error value that means not a number. Below are 4 methods with examples to avoid NaN in JavaScript.

Avoid NaN in JavaScript

Simple example code.

1. Mathematical operations with non-numeric string values

Sometimes stringed values may come back from an API, just check if the value is NaN in the first place.

const y = 5 * "Apples"; // NaN

isNaN("5") || 0

To avoid it completely, it’s best if you do all your mathematical operations with numbers.

2. Mathematical operations with functions

Doing mathematical operations with a function will result in a NaN value.

function fooBar() {
  // ...stuff
fooBar * 5 // NaN

3. Mathematical operations with objects

Doing mathematical operations with a JavaScript object will result in a NaN value.

const obj = {};

obj * 5 // NaN

4. Mathematical operations with falsy values

Avoid doing mathematical operations with falsy values such as:

<!DOCTYPE html>


    const a = undefined + 5; // NaN

    const b = NaN / 5; // NaN

    const c = null - 5; // -5. Null behaves like a 0.

    const d = false * 5; // -5. False behaves like a 0.

    const e = "" + 10; // 10. Empty string behaves like a 0.





How to avoid NaN in JavaScript

Return Zero if the input value is NaN

The shortest way:

var number = (yourVariable || 0)

Because NaN is a falsey value, this will return 0 whenever yourVariable is NaN.

A way to check, if a number is NaN or not is to use the isNaN function.

isNaN(yourVariable); // Returns true is yourVariable is NaN

How do I prevent my output from being Nan?

Answer: Just set a variable to parseInt(…) and check to make sure that it is a number using if(!isNaN(val).

let val = parseInt(Value);
    if (!isNaN(val))

Do comment if you have any doubts or suggestions on this JS NaN topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

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