Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Strange behavior of ^= assignment operator chains in javascript

I was playing with the XOR trick for swapping values of variables, it works fine if I write it in 3 (or 2) lines, but not when I write it in 1 line, which shows some strange behavior of the ^= operator. What is going on here? Why are the 1-line and 3-line versions not equivalent?

let a = 55, b = 31;
console.log('values to swap:', a, b);

// swap with XOR trick
a ^= b;
b ^= a;
a ^= b;
console.log('swap in 3 lines', a, b);
// output: 31 55

// swap in 1 line
a = 55; b = 31;
a ^= b ^= a ^= b;
console.log('swap in 1 line', a, b);
// output: 0 55

// swap in 2 lines
// chaining only 2 ^= operations works as expected
a = 55; b = 31;
console.log('b ^= a ^= b returns ', b ^= a ^= b);
a ^= b;
console.log('swap in 2 lines', a, b);

I tested it in Chrome and Safari, got same results.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It is not possible. In JavaScript, expressions are evaluated left-to-right. You have to put this (a ^= b ^= a) && (b ^= a) equation.

That means that your condition is evaluated like this:

   a ^= b ^= a ^= b;
=> a = a ^ (b = b ^ (a = a ^ b))
=> a = 55 ^ (b = 31 ^ (a = 55 ^ 31))
=> a = 55 ^ (b = 31 ^ 40)
=> a = 55 ^ 55 = 0
   b = 31 ^ 40 = 55
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!