I was killing time reading the underscore.string functions, when I found this weird shorthand:
function count (str, substr) {
var count = 0, index;
for (var i = 0; i < str.length;) {
index = str.indexOf(substr, i);
index >= 0 && count++; //what is this line doing?
i = i + (index >= 0 ? index : 0) + substr.length;
}
return count;
}
Legal: Think twice before using the function above without giving credit to underscore.string
I put the line alone here, so you don’t waste time finding it:
index >= 0 && count++;
I have never seen anything similar to that. I am clueless in what is doing.
First part:
index >= 0returns true if
indexhas a value that is greater than or equal to0.Second part:
a && bmost C-style languages shortcut the boolean
||and&&operators.For an
||operation, you only need to know that the first operand istrueand the entire operation will returntrue.For an
&&operation, you only need to know that the first operand isfalseand the entire operation will returnfalse.Third Part:
count++count++is equivalent tocount += 1is equivalent tocount = count + 1All together now
If the first operand (
index >= 0) of the line evaluates astrue, the second operand (count++) will evaluate, so it’s equivalent to:JavaScript nuances
JavaScript is different from other C-style languages in that it has the concept of
truthyandfalseyvalues. If a value evaluates tofalse,0,NaN,"",null, orundefined, it isfalsey; all other values aretruthy.||and&&operators in JavaScript don’t return boolean values, they return the last executed operand.2 || 1will return2because the first operand returned atruthyvalue,trueor anything else will always return true, so no more of the operation needs to execute. Alternatively,null && 100will returnnullbecause the first operand returned afalseyvalue.