Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5051

Why logical OR working differently if change the order contains terinary operator

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

Answers (2)

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

var output2 = true || test ? 'Test' : 'No Test'

in this above code you used true thats why it has printed Test 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

CertainPerformance
CertainPerformance

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

Related Questions