Null Vs. Undefined in Javascript

Nov 15th, 2012 | By | Category: Programming & Languages

In my last post on TypeScript I had mentioned about the null & the undefined data types very briefly.Both these are present in Javascript and, TypeScript being a superset of Javascript includes the same.But there are certain confusing aspects in terms of these two data types and I wanted to discuss these in a little more detail in this post.

First let’s take a look at null.

  • Null value needs to explicitly assigned to a variable in order to indicate it stores nothing.null is used to initialize a variable.

image

  • null is of type object.

image

On the other hand, undefined is

  • Value of a variable which is not initialized e.g.

image

  • Value of  a property which is not present in an object e.g.

image

  • A function argument which is not being passed e.g.

image

  • The type of an undefined variable is not object.it is undefined. e.g.

image

Now the way I see it, the first use of undefined i.e. a variable not passed is confusingly close to the use of null. In many other programming language an uninitialized variable holds null value.But for a dynamic language like javascript where the objects are not strongly typed “undefined” makes perfect sense for properties which “are not defined” or “not present” in an object. The similar logic holds true for function arguments which are not being passed.


Kick It on DotNetKicks.com
Tags: , ,