Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda