Question 13
Question
Explain the difference between null
, undefined
, and NaN
.
Answer
1. null
:
Meaning: Represents the intentional absence of a value. It signifies that a variable or property is explicitly set to nothing.
Example:
let myVariable = null; // We intentionally assigned 'nothing' to myVariable
2. undefined
:
Meaning: Indicates that a variable has been declared but hasn't been assigned a value yet. It's the default state of a variable until you give it a specific value.
Example:
let anotherVariable; // anotherVariable is now 'undefined' because we declared it but didn't assign a value console.log(anotherVariable); // Output: undefined
3. NaN
(Not a Number):
Meaning: Represents an invalid or unrepresentable numerical value. This usually occurs when you perform mathematical operations that result in a non-numeric outcome.
Example:
console.log(Math.sqrt(-1)); // Output: NaN
Key Differences:
Intent:
null
is explicit (intentional absence), whileundefined
is implicit (no value assigned).NaN
indicates a computation error.Comparison: You cannot directly compare
null
,undefined
, andNaN
using==
or===
. Use specific checks:if (value === null) { /* Handle null */ } else if (typeof value === 'undefined') { /* Handle undefined */ } else if (isNaN(value)) { /* Handle NaN */ }
Last updated