Reputation: 5051
Why below code is giving different outputs?
var test;
var output = test ? 'Test' : 'No Test' || true;
var output2 = true || test ? 'Test' : 'No Test'
console.log(output); // No Test
console.log(output2); // Test
Upvotes: 2
Views: 45
Reputation: 6755
var output2 = true || test ? 'Test' : 'No Test'
in this above code you used
true
thats why it has printedTest
your conditional operator here got as true
var output2 = test ? 'Test' : 'No Test'
if you have tried like this it will print No Test
var test;
var output = test ? 'Test' : 'No Test' || true;
var output2 = test ? 'Test' : 'No Test'
console.log(output); // No Test
console.log(output2); // Test
Upvotes: 0
Reputation: 370979
Because of operator precedence. The conditional operator has precedence 4, while logical OR has precedence 5, so your code is equivalent to:
var test;
var output = test ? 'Test' : ('No Test' || true);
// undefined ? 'Test' : 'No Test'
var output2 = (true || test) ? 'Test' : 'No Test'
// true ? 'Test' : 'No Test'
console.log(output);
console.log(output2);
The OR grouping has a higher priority - its surrounding tokens are grouped together first.
Upvotes: 5