views:

497

answers:

3

We are frequently using the following code pattern in our javascript code

if(typeof(some_variable) != 'undefined' && some_variable != null)
{
    // do something with some_variable
}

and I'm wondering whether there is a less verbose way of checking that has the same effect. According to some forums and literature saying simply

if(some_variable)
{
    // do something with some_variable
}

should have the same effect. Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for him. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways ?

+1  A: 

If you try and reference an undeclared variable, an error will be thrown in all javascript implementations. if (some_variable) is equivalent to if (some_variable != null), but you still need to check the variable has been declared first.

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property)

With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:

if (window.some_variable)
{
    // do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.

Andy E
As usual, downvoter leaves comment - no chance of enlightenment then? I'd love to know exactly what was incorrect about my answer ;-)
Andy E
+1  A: 

You have to differentiate between two cases

1) Undefined variables , like 'foo'. You'll get an error if you access an undefined variable in any context other than typeof.

  if(typeof someUndefVar == whatever) -- works
  if(someUnderVar) -- error  

so for variables typeof check is a must. On the other side, it's only rarely needed - you usually know if your variables are defined or not.

2) Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns "undefined", which, when converted to boolean, evaluates to false. So, if you don't care about '0' and 'false', if(obj.undefProp) is ok. There's a common idiom based on this fact:

 value = obj.prop || defaultValue

which means "if obj has a prop, use that, otherwise default".

Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using in operator instead

 value = (prop in obj) ? obj.prop : defaultValue
stereofrog
Then you could talk about hasOwnProperty and prototypes. 'indexOf' in [] !== [].hasOwnProperty('indexOf')
Alsciende
Yes, i thought about adding this, but decided to sacrifice completeness for brevity. ;)
stereofrog
A: 

You should never have to check for typeof myVar != "undefined". If you try to reference an undeclared variable, something should be wrong in your code and an exception should be fired. Undeclared variables are a very bad thing in javascript, because of a few things, like:

  1. They pollute the global namespace, ie. window
  2. They can easily collide inside this namespace
  3. They are not garbage-collected before the window closes
  4. They require security tests like typeof myVar != "undefined"

So declare your variables and treat undefined and null like two distinct values, because 4 different things can happen with a variable:

  1. When a variable is not defined and you try to know its value, javascript throws a ReferenceError exception (is not defined). That's a bad thing, ergo the exception.
  2. undefined means that the variable value has not been defined. So the variable value is unknown ; it is not known if the variable has a value and what it is.
  3. null means that the variable value, which is defined, is null. So the variable has no value ; it is known that the variable doesn't have a value.
  4. Else, you have a value, enjoy!
Alsciende
@Alsciende: I'm not sure I understand how undeclared variables can pollute the global namespace (they're undeclared!). I do understand how undeclared variables might not be garbage-collected however, since you can't garbage collect something that doesn't exist in the first place ;-)
Andy E
Right I'm talking about 2 different things here, undeclared variables when you _get_ them (throws an exception) and undeclared variables when you _set_ them (adds a property to the global object). In that sense, an undeclared variable can exist as an implicit property of the global object.
Alsciende