0

Javascript doubt

what is the output of this code and why, thanks var a = 1; var b = 2; var d = "8"; var c = d + (a = b + 1) - d; alert(c);

12th Oct 2019, 12:15 AM
Stiven 98
Stiven 98 - avatar
3 odpowiedzi
+ 3
The expression: d + (a = b + 1) - d; First, parentheses boosts precedence, so let's first handle the part within parentheses: (a = b + 1) // a become 3 Outside the parentheses we see two operators with same precedence. + to the left, and - to the right. We handle the left part first, then on to the right, because they have same precedence. A + operator between a string and a number behaves as string concatenation, so when we deal with this: "8" + (a) "8" + 3 // + act as string concatenation Here we have "83" from concatenating "8" and 3. Lastly, we deal with the - operator: "83" - "8" Wait, string can be concatenated with + operator, but there is no overload for - operator of string class. So JavaScript convert the two string into numbers before proceeding. And then we have this: 83 - 8 Voila! it turned out the output was just that, 83 - 8. Then we tell JavaScript to alert us that value , 75. Hth, cmiiw
12th Oct 2019, 3:06 AM
Ipang
+ 1
thanks I understood perfectly
12th Oct 2019, 3:13 AM
Stiven 98
Stiven 98 - avatar
+ 1
You're welcome, glad if it helps 👍
12th Oct 2019, 3:37 AM
Ipang