NaN vs undefined in JavaScript

The concepts of NaN (Not-a-Number) and undefined in JavaScript are both special values, but they serve very different purposes. Below, you'll find a detailed comparison, a table summarizing the key differences, and an example to clarify these distinctions.

NaN vs undefined in JavaScript 

NaN (Not-a-Number)

NaN is a special numeric value that represents the result of an undefined or unrepresentable mathematical operation. For example, dividing 0 by 0 or taking the square root of a negative number will result in NaN. It is important to note that NaN is not equal to anything, even itself.

undefined

undefined is a primitive value automatically assigned to variables that have just been declared or to function arguments for which there are no corresponding parameters. It indicates that a variable exists but has not been assigned a value yet.

Comparison Table

Feature 'NaN' 'undefined'
Type Number Undefined
Value Represents unrepresentable number Indicates a variable hasn't been assigned a value
Usage Result of invalid mathematical operations Result of declaring without initializing
Comparative with '==' NaN == NaN is false undefined == undefined is true
Comparative with '===' NaN === NaN is false undefined === undefined is true

Example

Here’s an example to illustrate the concepts of NaN and undefined.
var a = 0/0; // Invalid division
var b;

console.log(a); // Outputs 'NaN' because 0 divided by 0 is unrepresentable
console.log(b); // Outputs 'undefined' because 'b' is declared but not assigned a value

console.log(a == a);  // Outputs false because NaN is not equal to itself
console.log(b == b);  // Outputs true because 'undefined' is equal to itself

console.log(a === a); // Outputs false because NaN is not strictly equal to itself
console.log(b === b); // Outputs true because 'undefined' is strictly equal to itself

Conclusion

NaN and undefined are both special values in JavaScript, but they represent entirely different concepts. NaN is used to indicate an unrepresentable mathematical result, while undefined is used to signify that a variable has been declared but not yet assigned a value.

Understanding these differences and when each value is likely to occur is crucial for debugging and maintaining clear, functional code. Using functions like isNaN() to check for NaN and being mindful of variable initialization can help prevent unexpected behaviors related to these values in your code.

Comments