1
var str = '1' || '2'

console.log(str) outputs 1 Okay... makes sense. The 1 is front of the '||', so it should never matter what comes after the '||'

var str = '1' || (true) ? '2' : '3'

console.log(str) outputs 2 ...WHAT?! This should never happen. The '1' was in front of the '||'

var str = '1' || (false) ? '2' : '3'

console.log(str) outputs 2 ...Okay JS go home you're obviously drunk.

  • I'm surprised it's even evaluating after the `||` -- when I recently tried this, I had to group all my statements after the OR statement to get the desired result: `var str = nullString || ( (boolStringTest)? 'stringA' : 'stringB' );` – Doug Jun 18 '18 at 20:25
  • _"console.log(str) outputs 2 ...WHAT?! This should never happen."_ Why not? `1` is truthy so the expression evaluates to true. – j08691 Jun 18 '18 at 20:26
  • 1
    Look up operator precedence. You look at these examples under false assumptions. – idmean Jun 18 '18 at 20:26
  • so, `'1' || (true)` is evaluating first to be true/false statement -- THEN it's looking for the values? For better readability, the code is thinking: `var str = ( '1' || (true/false) )? '2' : '3'; ` ? – Doug Jun 18 '18 at 20:27
  • This question is related to operators precedence and type conversion, there is no answer which is describing both, i wrote an answer but question is closed now, so could not post – dhaker Jun 18 '18 at 21:28

2 Answers2

4

console.log('1' || (true) ? '2' : '3');
//is interpreted as 
console.log(('1' || true) ? '2' : '3');
//you mean to write
console.log('1' || (true ? '2' : '3'));
dgeare
  • 2,618
  • 5
  • 18
  • 28
3

What you expect is

'1' || ((true) ? '2' : '3')

, but basically what you are making is

('1' || (true)) ? '2' : '3'

You are creating shorthand for if statement where left part is evaluated and then proper value is returned, thus '1' is evaluating to true and this way you are getting '2' as a result

Maciej Kwas
  • 6,169
  • 2
  • 27
  • 51