JavaScript Interview Question: When do we get NaN in output

As a JavaScript developer, you may have come across NaN in your code. NaN stands for "not a number" and is a global property in JavaScript representing non-numerical values. In this article, we will explore what NaN is, when you may encounter it, and how to handle it in your code.

What is NaN?

NaN stands for "not a number". It is a global property in JavaScript that represents non-numerical values. NaN is of type number but is not equal to any number, including itself. NaN is a special value that indicates that an arithmetic operation has failed or that the result of a calculation is undefined.

When do you get NaN as output?

You normally get NaN as output when there is a non-numerical value. For example, if you try to perform a mathematical operation on a string, you will get NaN as the result.

Handling NaN in JavaScript

There are several ways to handle NaN in your JavaScript code. One of the ways is to use the isNaN() function. The isNaN() function returns true if the value is NaN; otherwise, it returns false. Let's take a look at an example:

let a = 2;
let b = "Hello";

if(isNaN(b)) {
  console.log("b is not a number");
} else {
  console.log(a + b);
}

In this example, we declare two variables a and b. a has a numeric value, while b has a string value. We use the isNaN() function to check if b is a number. Since b is not a number, the if block is executed, and the output is "b is not a number".

Another way to handle NaN is to use the Number.isNaN() method. The Number.isNaN() method is similar to the isNaN() function, but it only returns true if the value is NaN; otherwise, it returns false. Here's an example:

let a = 2;
let b = "Hello";

if(Number.isNaN(b)) {
  console.log("b is not a number");
} else {
  console.log(a + b);
}

In this example, we use the Number.isNaN() method instead of the isNaN() function. The output is the same as the previous example.

Using NaN in Arithmetic Operations

When you use NaN in arithmetic operations, the result is always NaN. For example:

let a = 2;
let b = NaN;

console.log(a + b); // Output: NaN
console.log(a - b); // Output: NaN
console.log(a * b); // Output: NaN
console.log(a / b); // Output: NaN

In this example, we declare two variables a and b. a has a numeric value, while b has the value NaN. When we perform arithmetic operations on a and b, the result is always NaN.

Conclusion

In conclusion, NaN is a special value in JavaScript that represents non-numerical values. You may encounter NaN when you try to perform arithmetic operations on non-numerical values. There are several ways to handle NaN in your code, such as using the isNaN() function or the Number.isNaN() method.


The content of this blog post was inspired by the JavaScript - Marathon Interview Questions Series 2023 course on Udemy

(https://www.udemy.com/share/103EGJ3@c1keuOijNDmjnAPChhiWCI2Jlo3fvyCArsjudZa0Y33kk0etkjxUcZSjCoiz8UM30g==/)