Tuesday, March 6, 2012

Javascript: variable_name is not defined

In Javascript, if your're are using a variable or a property and what you get is an error like "variable_name is not defined".
The message is pretty clear, but what is the best way to check and handle it?

There are some, but the best is:

   if (typeof my_variable === "undefined") {
      alert("my_variable is undefined");

There are some others way, but they could have some problems, for example:

   if (my_variable === undefined) {
      alert("my_variable is undefined");
This one doesn't work if in your scope is defined a variable called undefined.
This way also return true if my_variable is null.

Happy scripting =)

No comments:

Post a Comment