0

assignment operators

in this code: var x = 2 var y = 3 x +=y console.log(x) how JS knows that it should calculate x from 3-rd row of code? and not the x from first row? or here: var x = 2 var y = 3 x -= y += 9 console.log(x) why on earth the output is: -10??? x-=y that will be in my case: 2-3=-1 and y+=9 that will be 3+9=12

26th Aug 2021, 9:00 AM
Pawel
3 Respostas
+ 2
Yes, that's right. Variable <x> at line 3 and 4 are the same <x> that was initially defined at line 1. Javascript knows this by differentiating variable scope, a specification that defines where a certain variable is recognisable. https://www.w3docs.com/learn-javascript/variable-scope.html
26th Aug 2021, 12:11 PM
Ipang
+ 2
I didn't get your doubt about the first snippet. Can you elaborate further? About second snippet, the += and -= operator associativity is right-to-left. So ... x -= y += 9; Will be processed from right to left, like so ... x -= ( y += 9 ); x -= ( 3 + 9 ); x -= ( 12 ); // this is <x> (2) - (12) => -10 http://www.scriptingmaster.com/javascript/operator-precedence.asp
26th Aug 2021, 9:23 AM
Ipang
+ 1
thank you :) you gave me some hope to try further :) my first doubt, regards to this: in this code, te X is used twice. In first row as var and in third (x+=y). var x = 2 var y = 3 x +=y console.log(x) How JS knows that when I wrote console.log(x) it regards x from third row, and not x from first (when it is defined as variable). For me those are the same values...
26th Aug 2021, 9:40 AM
Pawel