0

How am I getting 339 as output of the following code ?

console.log(3 + '4' + 5 - 6)

can anyone please explain me?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • duplicated https://stackoverflow.com/questions/40848551/how-does-adding-string-with-integer-work-in-javascript#:~:text=In%20JavaScript%2C%20the%20%2B%20operator%20is,string%20and%20concatenates%20both%20together. – kerm Jun 15 '22 at 17:01

1 Answers1

2

3 + "4" yields "34" due to the implicit string conversion. Implicit string conversion seems to have higher priority than implicit number conversion.

"34" + 5 yields "345"

"345" - 6 yields 339 due to the implicit number conversion

Vivick
  • 3,434
  • 2
  • 12
  • 25
  • "*Implicit string conversion seems to have higher priority than implicit number conversion.*" no, it's just processed left-to-right and that's the first operation: `1 + 2 + "3"` is `"33"` because the first operation is `1 + 2` and then it's `3 + "3"`. There is no priority of conversions. – VLAZ Jun 16 '22 at 06:08
  • If there's no string in play, there's no need for conversion. – Vivick Jun 16 '22 at 06:15
  • You said that there was some priority to the conversion. There isn't. It's just processing the operations in sequence. And a ` + ` will always convert to a string. – VLAZ Jun 16 '22 at 06:16