Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What happens when we try to add a number to undefined value?
If you try to add a number to an undefined value, you will get NaN (Not a Number). This happens because JavaScript cannot perform mathematical operations when one operand is undefined.
Understanding NaN
NaN stands for "Not a Number" and is returned when a mathematical operation cannot produce a meaningful numeric result. When you add a number to undefined, JavaScript attempts type coercion but fails, resulting in NaN.
Case 1: Direct Addition with Undefined
Here's what happens when you directly add a number to undefined ?
var result = 10 + undefined; console.log(result); console.log(typeof result);
The output of the above code is ?
NaN number
Case 2: Addition with Undefined Variable
When you declare a variable without initializing it, its value is undefined by default ?
var value1 = 10; var value2; // undefined by default var result = value1 + value2; console.log(result);
The output of the above code is ?
NaN
Checking for NaN
You can check if a value is NaN using the isNaN() function or Number.isNaN() method ?
var result = 5 + undefined; console.log(isNaN(result)); console.log(Number.isNaN(result));
The output of the above code is ?
true true
In conclusion, adding any number to undefined always results in NaN, which is still of type "number" but represents an invalid numeric value. Always ensure variables are properly initialized to avoid unexpected NaN results in calculations.
