If n and guard do not exist, n==null is true, and guard is undefined in the ternary operator. If the Boolean value is converted to false, it will be equal to n, that is, the final return is undefined.
But why does it return 1?
var test=function(array,n,guard){
return (n==null || guard ? 1 : n);
};
console.log(test([]));//1
仅有的幸福2017-05-19 10:35:27
First of all, you misunderstood the order of operations
var test=function(array,n,guard){
return (n==null || guard ? 1 : n);
};
console.log(test([]));//1
The operation precedence of || (logical OR) is greater than that of the ternary operator
So (n==null || guard ? 1 : n) here first calculates the logical OR, and then calculates the ternary operator
Here it becomes true ? 1 : n
So output n
Attached is a picture of the priority of operations. I don’t remember which book I took it from
巴扎黑2017-05-19 10:35:27
var test=function(array,n,guard){
console.log(n==null);//true
return (n==null || guard ? 1 : n);
};
console.log(test([]));//1
||The priority is higher than trinocular, so it is (true || guard)? 1: n ===> true ? 1 :n