Consider the following:
(EDIT: I've amended the function slightly to remove the use or braces with the ternary operator)
function someFunction(start,end,step){
var start = start || 1,
end = end || 100,
boolEndBigger = (start < end); // define Boolean here
step = step || boolEndBigger ? 1:-1;
console.log(step);
}
someFunction()
// step isn't defined so expect (1<10) ? 1:-1 to evaluate to 1
someFunction(1,10)
// again step isn't defined so expect to log 1 as before
The problem:
someFunction(1,10,2) //step IS defined, shortcut logical OR || should kick in, //step should return 2 BUT it returns 1
I'm aware that this is easily fixed by using braces:
function range(start,end,step){
var start = start || 1,
end = end || 100,
step = step || ((start < end) ? 1:-1);
console.log(step);
}
The question: Why doesn't the
||
operator get short-cut in this case?I'm aware that the Logical OR has the lowest precedence among binary logical conditional operators but thought that it has higher precedence than the conditional Ternary operator?
Am I misreading the MDN docs for Operator precedence?
(step || (start < end)) ? 1 : -1
– Furie||
is evaluated first, i.e.step || (start < end)
is evaluated first. – Tufthunterstep || (start < end) ? 1 : -1
evaluates tostep ? 1 : -1
because||
is evaluated first andstep
is truthy. Then,step ? 1 : -1
is evaluated to1
becausestep
is truthy. – Tufthunter||
operator doesn't shortcut, see @lonesomeday answer. I've edited it now to clarify. – Ionia