educative.io

Educative

Data types in javascript

let x = 2 + 3 + “5”;
this equation results in “55”
but
let x = “5” + 2 + 3;
this results in “523”
we have not performed any data type changes if in 2nd equation data type changes in string than why is not changed in first one?


Course: Introduction to JavaScript: First Steps - Free Interactive Course
Lesson: Introduction - Just Get Started - Introduction to JavaScript: First Steps

Hey @Asma_Ismail!
This is because the JavaScript interpreter works from left to right.
So for the first equation:

let str= "5"    
let x = 2+ 3 + str

2+3 results in 5 as both are numbers. Then 5 is concatenated with a str i-e “5”. So the result is 55.
Now for the second equation:

let str= "5"    
let x = str + 2+ 3 

The str i-e “5” is contaminated with the number 2 and results in a string “52”. Then this string is again concatenated with the number 3. So the final result is 523.