Thursday, October 21, 2021

Difference between null and undefined in Javascript

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var testVar;
alert(testVar); //shows undefined
alert(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;
alert(testVar); //shows null
alert(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.

null === undefined // false
null == undefined // true
null === null // true

and

null = 'value' // ReferenceError 

undefined = 'value' // 'value' 

references:

https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript

No comments:

Post a Comment