hamncheez
hamncheez

Reputation: 739

Javascript using if(foo) exists to check if variable is set

I realize that this question is extremely similar to many others, but I must be missing some nuance with checking whether a variable is set or not. I have seen this in other developers code:

if(foo){
  doSomething(foo);
}
else{
  alert('error of whatever');
}

With the intent that the doSomething() will only execute if foo is set or not undefined. However, when I google this, it seems everyone says "typeof" should be used instead of the above method. I specifically see this in use with angular, like this:

if($scope.property){
  dothis();
}

Am I missing something? When I see the above code, it seems to work, but all the answers I see never say this is the correct way to check if something is set or exists.

Upvotes: 3

Views: 3850

Answers (6)

cfischer
cfischer

Reputation: 470

What you are checking this way is if foo is not:

false
Undefined
Null
+0, −0, or NaN
Empty String

More info here:

https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

This way your function is only executed if foo is valid.

You may want to be more specific and check against a certain type with typeof.

var foo = 'foo';
if (typeof foo === 'string') { // true
  doSomething();
}

The typeof operator returns a string indicating the type of the unevaluated operand. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Upvotes: -1

Christoph Anderson
Christoph Anderson

Reputation: 687

This has to do with the concept of "truthiness". Any value besides false, 0, "", null, undefined, and NaN is "truthy" which means the first block of the if-statement will run. For instance:

if ("") {
    alert("falsie"); // won't run because the empty string ("") is falsie
} else {
   alert("truthie"); // will run
}

whereas

if ("something") {
    alert("truthy"); // will run because "something" is truthy
} else {
    alert("falsie"); // won't run
}

Going back to your example, if foo is truthy (meaning that it has ANY value other than false, 0, "", null, undefined, and NaN) then it will run the first block of the if-statement (which has the doSomething() function in it).

Upvotes: 1

David L
David L

Reputation: 33823

For if() checks, in MOST scenarios where you are checking for the existence of a property on an object (your situation), what you have described is perfectly valid, easy and convenient. It checks for the existence of the property and returns true if it exists.

However, there are plenty of nuanced areas where a typeof check is "more" correct, particularly if your type is being coerced in any way via == or if you want to differentiate between null and undefined.

For instance, if null is a valid value for your property to have but undefined is not, in your example dothis() would still be called. You would prevent this with a typeof check.

if (typeof $scope.property === 'undefined') {
    dothis();
}

Finally, if you are checking for the existence of a variable instead of the existence of a property, an exception will be thrown if the variable you are checking is not defined, forcing you to use a typeof check.

In those scenarios, verbosity is your friend.

Upvotes: 5

David Scott
David Scott

Reputation: 886

The reason the typeof operator is preferred is because it doesn't throw a ReferenceError exception when used with an undeclared variable.

However, it is important to note that variables initialized as null will return "object", so to avoid this issue, the following code is recommended:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

Upvotes: 0

Reda
Reda

Reputation: 1369

It is better to use typeof if you need to explicitly check whether the value is undefined or not. If you just want to check if the value is truthy, then you don't need typeof.

Upvotes: 0

Pascal Winter
Pascal Winter

Reputation: 114

You could also use short circuit evaluation and do this in one line.

($scope.property && doThis())

Upvotes: 0

Related Questions