Reputation: 21
var a = '1';
console.log(a == ('2'||'1')?'hi':'hello');
Doing so the condition get failed as a = 1
.
It is comparing a's value 1 with 2 as this condition failed. so it always print hello.
Is there any way to check for value('1') also which is after "||" so that it print hi?
Upvotes: 1
Views: 71
Reputation: 21
var a = 1; a == '2'?'hi': a=='1'?'hello' :'';
i Found this is also working.... Thanks to everyone who answered using different ways..
Upvotes: 0
Reputation: 370979
Either list the different possibilities out separately:
a === '2' || a === '1' ? 'hi' : 'hello'
Or use an array and .includes
:
['2', '1'].includes(a) ? 'hi' : 'hello'
The problem with ('2'||'1')
is that the whole section there gets evaluated to a single expression before the comparison against a
is made, and ||
will evaluate to the initial value if it's truthy. So ('2' || '1')
resolves to '2'
.
Upvotes: 5