uesports135
uesports135

Reputation: 1123

Checking for null vs using || when getting length

I have been working on a project and I often have to get the length of a variable. I recently started using the following syntax because I think it looks better and is faster to type, especially when I have long variable names and multiple conditions.

if ((myArrayVariable || "").length > 0) {
    // Do stuff...
}

Previously, I did it like this:

if (myArrayVariable != null && myArrayVariable.length > 0) {
    // Do stuff...
}

What I want to know is, if/(how much) the first syntax is less efficient?

Upvotes: 0

Views: 110

Answers (1)

David
David

Reputation: 383

To test the performance, I made a jsperf test that test null, an empty array, and an array with one element on the following variants:

  • The first style (array || '').length > 0
  • The second syntax array != null && array.length > 0
  • The third version array && array.length

The initial run indicates that the first variation is 96% slower than the others. Additionally the other two are nearly the same, though adeneo's suggestion is about half a percent faster than the second.

The first is 96% slower than the others

Upvotes: 1

Related Questions