Null Vs Undefined 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: undefinedis a type itself (undefined) while null is an object.

Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

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

and

 null = 'value' // ReferenceError
 undefined = 'value' // 'value'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s