29 September 2011

How to check is if an object property in JavaScript is undefined?

 If you not familiar with difference  between null (something is defined but doesn't have assign any valueno value) and undefined (  something was not defined) then look to my post below:
What is a difference between null and undefined

During learning you discover how amazing thing can be done with if statement... and how useful it is.
Then during your practice your skill on examples, you will discover is good to check if something doesn't have a value ... so you just write:

if (typeof example === null) {
  alert("booo!example doesn't have any value!");

Job done ...  but you want check is something exists...  you heard about undefined... but as you know undefined is not a reserved word ,so you can't do the same away as above... what to do ? You actually can do it in similar way  you need to "compare" using string "undefined".
Let's see  a example for check object property exist.
if (typeof example === "undefined") {
  alert("example is undefined");

It will be very useful for you. in  your deep relationship with javascript.