Checking for null vs using || when getting length - javascript

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?

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.

Related

How to verify if array exist and its length in fewest steps?

I have some if statement, where I want to verify the length of an array. Let's say it is the following:
if (object.someArray.length > 1){
doSomething()
}
However, when someArray is not defined (maybe it is not defined for some object, which is possible), I get an error:
Cannot read property 'length' of null
Which makes sense, as object.someArray is not defined.
My question is: what is the best way to verify that the array exists AND its length, in fewest steps?
Thanks!
The very generic and full test : if array exist and is not empty
if(object && object.someArray && object.someArray.length)
For your case :
if(object.someArray && object.someArray.length > 1)
Edit : For those who don't know this is called duck-typing : we aren't checking really if the object is an array, we're considering that if that object has a property length, it is an array. Lot of library do that. As long as you don't store different types of javascript object (string/array/object) in the same variable, this code is safe.
Try to check array through Array.isArray
if (Array.isArray(object.someArray) && object.someArray.length > 1)
You can do it in one single condition like
if (object.someArray && object.someArray.length > 1){
//Do Something
}
if object.someArray is undefined, it will return false and the next condition will not be evaluated
the best way to verify that the array exists AND its length
The best way is to do exactly as you wrote:
if (array && array.length > 0 { ... }
You can check it this way.
if(object.someArray && object.someArray.length > 1) {
doSomething();
}
If the someArray does not exist then it will be false and it will never check for its length because of the short-circuit.

Why using for is faster than some() or filter()

I tried two different way to do something and I am surprised by the performance result :
I have 2 versions of a function :
Using a for :
$scope.hasBlockResult = function (IS, area, block) {
if (!block)
return false;
for (var i = 0; i < $scope.filteredCartoList.length; i++) {
if ($scope.filteredCartoList[i].informationSystem === IS
&& $scope.filteredCartoList[i].area === area
&& $scope.filteredCartoList[i].block === block)
return true;
}
return false;
};
And using some() function :
$scope.hasBlockResult = function (IS, area, block) {
if (!block)
return false;
return ($scope.filteredCartoList.some(function (carto) {
if (carto.informationSystem === IS && carto.area === area && carto.block === block)
return true;
return false;
}));
};
Same thing here :
Between the for :
for (var i = 0; i < $scope.filteredCartoList.length; i++) {
if ($scope.filteredCartoList[i].informationSystem == IS
&& $scope.filteredCartoList[i].type != 'AM'
&& $scope.filteredCartoList[i].type != 'IF'
&& $scope.filteredCartoList[i].area == area
&& $scope.filteredCartoList[i].block == block)
$scope.resultList.push($scope.filteredCartoList[i]);
}
and the filter() :
$scope.resultList = $scope.filteredCartoList.filter(function (carto) {
if (carto.informationSystem == IS
&& carto.type != 'AM'
&& carto.type != 'IF'
&& carto.area == area
&& carto.block == block)
return true;
return false;
});
I expected the filter() and the some() methods to be faster than the for method, but in both case, according to angularjs batarang performance tab, the foris faster.
I took a look at the benchmarksyou posted in the comments. These benchmarks have a few flaws:
The loop example uses console.timeEnd and console.log within the benchmark itself, which are both slow. None of the other examples did this at time of writing.
The some example performs type coercion.
All of the tests are performing string concatenation within their loops.
In order to draw any conclusions from these benchmarks, we first need to eliminate these sources of bias.
Here are the results on an 8GB DDR3 i5 Laptop with these biases eliminated, re-ordered in terms of fastest to slowest (lower numbers are better):
OBJECT Average 0.0010666643114139636
SEEK Average 0.00593666957380871
LOOP Average 0.008436664550875625
SOME Average 0.013993332007279
FILTER Average 0.02592999837361276
These are what is to be expected, and here is why:
Object Access
Object access is very quick because objects are essentially hash maps. Regardless of the size of the object, accessing an element will be a constant speed.
Seek
Seek is implemented as using indexOf to locate an element and then accessing that element at the direct array index. While the actual method of doing this is implementation-specific, it is going to be very similar to object access and thus very fast.
Loop
The loop approach is slower primarily because unlike the 'seek' test, the loop test iterates over the entire array and does both array access AND object access. The seek method doesn't do this. It breaks out almost immediately after finding the element.
This means that in all except the worst cases, seek will be faster than loop.
Some
Some has the overhead of a function invocation to be invoked every single iteration. In addition, this cannot be optimized at all by the JIT compiler because the JIT compiler doesn't know what you're going to pass into some. Some will, at best, perform the same as loop in the most optimized cases but because of the function invocations it will always be slower.
Filter
Filter has all the caveats of "some", but it will always iterate over the entire array instead of halting at a single element. Due to this, you should always expect filter to be much slower than a for loop - especially when you consider that filter also creates a new array which it returns!
Nothing beats native (vanilla) javascript when it comes to performance. Question boils down to "Do you want to spend time and resources in re-inventing the wheel by doing it yourself or just leveraging an external lib that does it for you?". Yes you sacrifice load time and performance but you save time and time is money. You can make your for loop faster by also caching the length of the array as such
for (var i = 0, len = $scope.filteredCartoList.length; i < len; i++)
This is going to work faster especially in IE because here you are caching the length of your $scope.filteredCartoList instead of calculating it every iteration of the loop.
Consider these two examples:
for (var i = 0; i < array.length; i++) {
doThing(array[i]);
}
vs.
function processItem(item) {
doThing(item);
}
for (var i = 0; i < array.length; i++) {
processItem(array[i]);
}
This is basically the difference between the two. There also has to be some logic inside of filter and some for handling the return value from processItem but basically you're stacking a whole extra function call on top of your loop.

&& / || operator strangeness in JavaScript

So, I was working on a project of mine, when I came across a problem like this:
var one = 1;
var two = 2;
var three = 7;
if (one === 1 || two === 2 && three === 3) {
console.log("ok"); // prints out ok
}
I'm pretty confused with this since I don't think it should print out "ok". I thought that since the condition after the && operator was false, it shouldn't run, but I'm evidently wrong. Can anyone clarify why it's working?
In Javascript, operators are not just evaluated left-to-right, certain operators have more precedence than others. Those with higher precedence (in this case, the && operator of precedence 13) will be evaluated before others (||, precedence 14).
For your particular case, you need to group your conditionals in order to achieve the functionality you want:
if ((one === 1 || two === 2) && three === 3) {
console.log("ok"); // prints out ok
}
JSFiddle

How to shorten my conditional statements

I have a very long conditional statement like the following:
if(test.type == 'itema' || test.type == 'itemb' || test.type == 'itemc' || test.type == 'itemd'){
// do something.
}
I was wondering if I could refactor this expression/statement into a more concise form.
Any idea on how to achieve this?
Put your values into an array, and check if your item is in the array:
if ([1, 2, 3, 4].includes(test.type)) {
// Do something
}
If a browser you support doesn't have the Array#includes method, you can use this polyfill.
Short explanation of the ~ tilde shortcut:
Update: Since we now have the includes method, there's no point in using the ~ hack anymore. Just keeping this here for people that are interested in knowing how it works and/or have encountered it in other's code.
Instead of checking if the result of indexOf is >= 0, there is a nice little shortcut:
if ( ~[1, 2, 3, 4].indexOf(test.type) ) {
// Do something
}
Here is the fiddle: http://jsfiddle.net/HYJvK/
How does this work? If an item is found in the array, indexOf returns its index. If the item was not found, it'll return -1. Without getting into too much detail, the ~ is a bitwise NOT operator, which will return 0 only for -1.
I like using the ~ shortcut, since it's more succinct than doing a comparison on the return value. I wish JavaScript would have an in_array function that returns a Boolean directly (similar to PHP), but that's just wishful thinking (Update: it now does. It's called includes. See above). Note that jQuery's inArray, while sharing PHP's method signature, actually mimics the native indexOf functionality (which is useful in different cases, if the index is what you're truly after).
Important note: Using the tilde shortcut seems to be swathed in controversy, as some vehemently believe that the code is not clear enough and should be avoided at all costs (see the comments on this answer). If you share their sentiment, you should stick to the .indexOf(...) >= 0 solution.
A little longer explanation:
Integers in JavaScript are signed, which means that the left-most bit is reserved as the sign bit; a flag to indicate whether the number is positive or negative, with a 1 being negative.
Here are some sample positive numbers in 32-bit binary format:
1 : 00000000000000000000000000000001
2 : 00000000000000000000000000000010
3 : 00000000000000000000000000000011
15: 00000000000000000000000000001111
Now here are those same numbers, but negative:
-1 : 11111111111111111111111111111111
-2 : 11111111111111111111111111111110
-3 : 11111111111111111111111111111101
-15: 11111111111111111111111111110001
Why such weird combinations for the negative numbers? Simple. A negative number is simply the inverse of the positive number + 1; adding the negative number to the positive number should always yield 0.
To understand this, let's do some simple binary arithmetic.
Here is how we would add -1 to +1:
00000000000000000000000000000001 +1
+ 11111111111111111111111111111111 -1
-------------------------------------------
= 00000000000000000000000000000000 0
And here is how we would add -15 to +15:
00000000000000000000000000001111 +15
+ 11111111111111111111111111110001 -15
--------------------------------------------
= 00000000000000000000000000000000 0
How do we get those results? By doing regular addition, the way we were taught in school: you start at the right-most column, and you add up all the rows. If the sum is greater than the greatest single-digit number (which in decimal is 9, but in binary is 1) we carry the remainder over to the next column.
Now, as you'll notice, when adding a negative number to its positive number, the right-most column that is not all 0s will always have two 1s, which when added together will result in 2. The binary representation of two being 10, we carry the 1 to the next column, and put a 0 for the result in the first column. All other columns to the left have only one row with a 1, so the 1 carried over from the previous column will again add up to 2, which will then carry over... This process repeats itself till we get to the left-most column, where the 1 to be carried over has nowhere to go, so it overflows and gets lost, and we're left with 0s all across.
This system is called 2's Complement. You can read more about this here:
2's Complement Representation for Signed Integers.
Now that the crash course in 2's complement is over, you'll notice that -1 is the only number whose binary representation is 1's all across.
Using the ~ bitwise NOT operator, all the bits in a given number are inverted. The only way to get 0 back from inverting all the bits is if we started out with 1's all across.
So, all this was a long-winded way of saying that ~n will only return 0 if n is -1.
You can use switch statement with fall thru:
switch (test.type) {
case "itema":
case "itemb":
case "itemc":
case "itemd":
// do something
}
Using Science: you should do what idfah said and this for fastest speed while keep code short:
THIS IS FASTER THAN ~ Method
var x = test.type;
if (x == 'itema' ||
x == 'itemb' ||
x == 'itemc' ||
x == 'itemd') {
//do something
}
http://jsperf.com/if-statements-test-techsin
(Top set: Chrome, bottom set: Firefox)
Conclusion :
If possibilities are few and you know that certain ones are more likely to occur than you get maximum performance out if || ,switch fall through , and if(obj[keyval]).
If possibilities are many, and anyone of them could be the most occurring one, in other words, you can't know that which one is most likely to occur than you get most performance out of object lookup if(obj[keyval]) and regex if that fits.
http://jsperf.com/if-statements-test-techsin/12
i'll update if something new comes up.
If you are comparing to strings and there is a pattern, consider using regular expressions.
Otherwise, I suspect attempting to shorten it will just obfuscate your code. Consider simply wrapping the lines to make it pretty.
if (test.type == 'itema' ||
test.type == 'itemb' ||
test.type == 'itemc' ||
test.type == 'itemd') {
do something.
}
var possibilities = {
"itema": 1,
"itemb": 1,
"itemc": 1,
…};
if (test.type in possibilities) { … }
Using an object as an associative array is a pretty common thing, but since JavaScript doesn't have a native set you can use objects as cheap sets as well.
if( /^item[a-d]$/.test(test.type) ) { /* do something */ }
or if the items are not that uniform, then:
if( /^(itema|itemb|itemc|itemd)$/.test(test.type) ) { /* do something */ }
Excellent answers, but you could make the code far more readable by wrapping one of them in a function.
This is complex if statement, when you (or someone else) read the code in a years time, you will be scanning through to find the section to understand what is happening. A statement with this level of business logic will cause you to stumble for a few seconds at while you work out what you are testing. Where as code like this, will allow you to continue scanning.
if(CheckIfBusinessRuleIsTrue())
{
//Do Something
}
function CheckIfBusinessRuleIsTrue()
{
return (the best solution from previous posts here);
}
Name your function explicitly so it immediately obvious what you are testing and your code will be much easier to scan and understand.
You could put all the answers into a Javascript Set and then just call .contains() on the set.
You still have to declare all the contents, but the inline call will be shorter.
Something like:
var itemSet = new Set(["itema","itemb","itemc","itemd"]);
if( itemSet.contains( test.type ){}
One of my favorite ways of accomplishing this is with a library such as underscore.js...
var isItem = _.some(['itema','itemb','itemc','itemd'], function(item) {
return test.type === item;
});
if(isItem) {
// One of them was true
}
http://underscorejs.org/#some
another way or another awesome way i found is this...
if ('a' in oc(['a','b','c'])) { //dosomething }
function oc(a)
{
var o = {};
for(var i=0;i<a.length;i++) o[a[i]]='';
return o;
}
of course as you can see this takes things one step further and make them easy follow logic.
http://snook.ca/archives/javascript/testing_for_a_v
using operators such as ~ && || ((),()) ~~ is fine only if your code breaks later on. You won't know where to start. So readability is BIG.
if you must you could make it shorter.
('a' in oc(['a','b','c'])) && statement;
('a' in oc(['a','b','c'])) && (statements,statements);
('a' in oc(['a','b','c']))?statement:elseStatement;
('a' in oc(['a','b','c']))?(statements,statements):(elseStatements,elseStatements);
and if you want to do inverse
('a' in oc(['a','b','c'])) || statement;
Just use a switch statement instead of if statement:
switch (test.type) {
case "itema":case "itemb":case "itemc":case "itemd":
// do your process
case "other cases":...:
// do other processes
default:
// do processes when test.type does not meet your predictions.
}
Switch also works faster than comparing lots of conditionals within an if
For very long lists of strings, this idea would save a few characters (not saying I'd recommend it in real life, but it should work).
Choose a character that you know won't occur in your test.type, use it as a delimiter, stick them all into one long string and search that:
if ("/itema/itemb/itemc/itemd/".indexOf("/"+test.type+"/")>=0) {
// doSomething
}
If your strings happen to be further constrained, you could even omit the delimiters...
if ("itemaitembitemcitemd".indexOf(test.type)>=0) {
// doSomething
}
...but you'd have to be careful of false positives in that case (e.g. "embite" would match in that version)
For readability create a function for the test (yes, a one line function):
function isTypeDefined(test) {
return test.type == 'itema' ||
test.type == 'itemb' ||
test.type == 'itemc' ||
test.type == 'itemd';
}
then call it:
…
if (isTypeDefined(test)) {
…
}
...
I think there are 2 objectives when writing this kind of if condition.
brevity
readability
As such sometimes #1 might be the fastest, but I'll take #2 for easy maintenance later on. Depending on the scenario I will often opt for a variation of Walter's answer.
To start I have a globally available function as part of my existing library.
function isDefined(obj){
return (typeof(obj) != 'undefined');
}
and then when I actually want to run an if condition similar to yours I'd create an object with a list of the valid values:
var validOptions = {
"itema":1,
"itemb":1,
"itemc":1,
"itemd":1
};
if(isDefined(validOptions[test.type])){
//do something...
}
It isn't as quick as a switch/case statement and a bit more verbose than some of the other examples but I often get re-use of the object elsewhere in the code which can be quite handy.
Piggybacking on one of the jsperf samples made above I added this test and a variation to compare speeds. http://jsperf.com/if-statements-test-techsin/6 The most interesting thing I noted is that certain test combos in Firefox are much quicker than even Chrome.
This can be solved with a simple for loop:
test = {};
test.type = 'itema';
for(var i=['itema','itemb','itemc']; i[0]==test.type && [
(function() {
// do something
console.log('matched!');
})()
]; i.shift());
We use the first section of the for loop to initialize the arguments you wish to match, the second section to stop the for loop from running, and the third section to cause the loop to eventually exit.

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

Categories

Resources