-3

I am confusing with following outputs.

> console.log('0&&1')
0&&1 // ok  
> console.log(0&&1)
0 //ok

But when i console this below expression then it give 1. So please help me to understand this concept

> console.log('0&&1'+0&&1)
1 
31piy
  • 23,323
  • 6
  • 47
  • 67
Ravi Malviya
  • 121
  • 1
  • 13
  • 4
    As with other questions of this nature, I have to ask, who cares? If you're trying to add a string and a number with a boolean operator in the mix, you're just asking for trouble and should go do something more sensible :D – Niet the Dark Absol Aug 02 '18 at 13:38

1 Answers1

4

+ has higher precedence than &&. So your last snippet is essentially equivalent to:

console.log(('0&&1' + 0) && 1)

which will become this:

console.log('0&&10' && 1)

Since a non-empty string is a truthy value, thus, the return value is 1.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • 1
    Worth mentioning that this is related to [type coercion](https://stackoverflow.com/questions/19915688/what-exactly-is-type-coercion-in-javascript) – Liam Aug 02 '18 at 13:38