11 March 2011

What is differenece between null and undefined ?

When you start learning how to develop software , then you learned that null means lack of  value (and associated annoying error related to null called NullPointerException which cause people to madness and frenzy).

When you start learning javascript you discover that javascript is like other languages with some  freaks,so  i usually said that javascript is a language created by Monty Python.

Anyway.. back to topic, so ....
null means lack of value  and when you see null it can indicate that something does not contain a valid string, number,  boolean , array or ... object.

However Javascript loves conversion (that cause lots of bugs and problems when you develop your application  and this will be main reason why you will hate this language in many cases but loves by some geeks in some rare cases).
Why ?
Javascript will convert :
In a string context to null
In  a number context to 0
In boolean context to false

Keep this in mind , specially when you will do lots of comparisons.
For example compare null to undefined ,why ??

Let's explain what undefined means:

Undefined appear when
  • Something wasn't declared and you try to call this.  (like Object)
  •  Variable  has been declared but never had a value assigned
  •   property of Object which you refer to doesn't exist. 
Conversion .....in undefined will be even more crazy that in null.
In string context to null
In number context you will see NaN (which means Not A Number) (why ? this is another story which will explain in one of future posts)
In boolean context to false

Few interesting things on end of this post:

 Remeber:
  •  null is related as lack of  variable of something that exist 
  •  undefined means that something doesn't exist.

 In book : Javascript: The deinitive Guide i found that " Unlike null, undefined is not a reserved word in JavaScript."


And last .... people who are very sensitive in speaking/writing correctly always get mad because they said that "do not say/write  null value .. say/write null ... why ? because null means lack of value)

So if you have no f... idea why result of your comparison is weird ambiguous unexpected or not logical .. look to this post again. It can save your nervous system!

No comments:

Post a Comment