Reputation: 1123
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
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:
(array || '').length > 0
array != null && array.length > 0
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.
Upvotes: 1