gotchajavascriptCritical
What is the difference between null and undefined in JavaScript?
Viewed 0 times
andbetweenthedifferenceundefinedwhatjavascriptnull
Problem
What is the difference between
null and undefined in JavaScript?Solution
undefined means a variable has been declared but has not yet been assigned a value :var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value :var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that
undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'Code Snippets
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'Context
Stack Overflow Q#5076944, score: 1663
Revisions (0)
No revisions yet.