-2

const a = 2 + 3 + "4";

const b = "4" + 2 + 3;

console.log(a); //return 54

console.log(b); //return 423 how this happen??

1 Answers1

2

Computation is being done left to right.

const a = 2 + 3 + "4";

Left to right, 2 + 3 is done first. Becomes 5. 5 + "4" becomes "54" because "4" is a string.

const b = "4" + 2 + 3;

Left to right, we are starting with a string so "4" + 2 becomes "42". "42" + 3 becomes "423".

One with strings is string concatenation, and one with numbers is addition.

Note: I have mentioned string values inside "".

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Now, I understand properly. Thank you so much – Muhammad Asif Sep 21 '21 at 18:10
  • Sure please use the green tick to accept the answer, completing the question – Tushar Shahi Sep 21 '21 at 18:11
  • To elaborate on, check this cases: `const a = 1 + "2";` and `const b = "1" + 2;`. Value for both constants is (string) "12". More info [here](https://stackoverflow.com/questions/24383788) and [here](https://www.quirksmode.org/js/strings.html). – Dym Sep 21 '21 at 18:57