More than often, you need to access an element of an array or a property of an object, but it isn’t guaranteed that the array or object being queried actually exists. This often happens in AJAX callbacks, where the returned data might not be what you expected. When you try to grab that chunk of data, JavaScript throws a tantrum and starts yelling about how it “cannot read [the] property!”

var arr = null;
var element = arr[0];       // error!

var obj = undefined;
var property = obj['key'];  // error!

There is an obvious, common way to fix this: check if it exists before you query it.

var element;
if (arr) {
  element = arr[0];
}

var property;
if (obj) {
  property = obj['key'];
}

While this works, this exorbitantly verbose code is unappealing and looks clunky. There is a much more succinct way to accomplish this, using &&.

Consider the following snippet:

var result = a && b && c && d;

When the JavaScript engine attempts to determine the value of result, it will begin evaluating the expression a && b && c && d, starting by evaluating a, then evaluating b, and so forth. As soon as the engine discovers that one of the expressions evaluates to a falsy value, it will stop the processing and return that value back to result. It the engine reaches the end of the chain and hasn’t had to stop at a falsy value, it will return the value of the last expression in the list, even if the last item is falsy.

null  && "foo"           // returns null
"foo" && null            // returns null
"f"   && "oo"  && "bar"  // returns "bar"
"foo" && false && "bar"  // returns false
true  && true  && false  // returns false

This property of && can be used to solve our problem.

To check if a variable exists before trying to use it, use the following paradigm:

var element  = arr && arr[0];
var property = obj && obj['key'];

This works because the engine will stop trying to evaluate the expression as soon as it hits a falsy value. In the case of arr && arr[0], arr will return as falsy and break the chain before arr[0] is processed. Since arr[0] is never processed, no error is thrown.

As seen below, this shortcut leads to (what I consider to be) much cleaner code:

// without &&
var tryLogin = function (data) {
  var name;
  if (data) {
    name = data.user.name;
  }
  login(name);
};

// with &&
var tryLogin = function (data) {
  login(data && data.user && data.user.name);
}

What about ||?

You may have seen or used JavaScript’s analogy to a null coalescing operator, ||:

var result = a || b;

In the expression above, result will get the value of a if a is truthy, else it will get the value of b. You may ask yourself, “Why can’t I just use this instead?

To answer this astute question, consider when a is null (meant to be an array) and we try to access the 0th element.

var a = null;
var result = a[0] || b;

When the JavaScript engine tries to figure out what value result is, it first needs to evaluate a[0]. Since a is null, JavaScript is trying to look up null[0]. Accessing a property on null will, of course, throw an error.

Too Long; Didn’t Read

Use &&:

var arr1 = null;
var arr2 = ['a', 'b'];

var result1 = arr1 && arr[0];  // null
var result2 = arr2 && arr[0];  // 'a'