Skip to main content

Posts

Showing posts with the label typeof

Difference between undefined and null

Today we are gonna talk about the famous question in Javascript which all of us must have faced in interview.

The difference between undefined and null.

But before we talk about their differences, lets first think, why are we comparing undefined and null and why not undefined and string or string and null?

So there must be something common,in general, between undefined and null. And that commonality is both of have them represents NO VALUE for the variable.

You can also call this NO VALUE as void or empty.

So basically when we say as variable is undefined or null that mean the value doesn't exist for the variable. Lets see how is it so.

1.   undefined == null     // true, so the value is same

Now lets check each one of them.First lets talk about undefined.

When do we get this undefined? Generally when we declare a variable but doesn't initialise it we get undefined. e.g

1.   var foo;
2.   console.log(foo);   // undefined

Also when we try to access a variable before its initialis…