Search code examples
javascriptincrement

JavaScript Increment operator weird expression


Why the output of the bellow expression is 2,1?

let a = 1
let b = 2

a = (b+=a -=b)-a

console.log(`${a,b}`)


Solution

  • let a = 1
    let b = 2
    a = (b+=a-=b)-a (*)
    
    a-=b means a = a-b = 1-2 = -1
    a = -1
    Substitute into (*) => a = (b+=(-1))-a
    b+=(-1) means b=b + (-1) = b - 1 = 1
    
    Substitute into (*) => a = (1)-a = 1-(-1) = 2
    a=2 b=1