Home > Software engineering >  JavaScript variable - need an answer for this with some explanations [duplicate]
JavaScript variable - need an answer for this with some explanations [duplicate]

Time:09-22

const a = 2 3 "4";

const b = "4" 2 3;

console.log(a); //return 54

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

CodePudding user response:

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 "".

  • Related