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


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

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s