• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Swapping Javascript Variables Without A Third Variable

Fun, Javascript · July 30, 2015

While most developers will probably never encounter a situation where they’ll need to swap two integer values without a third variable unless you’re heavily into code golf.

While novel and impractical for most purposes, it can be nice to improve your problem solving skills and learn new things by solving problems without choosing the most obvious solution.

A little bit of trivia: I was actually asked to swap two integer values in a technical interview once-upon-a-time. So you never know if you find yourself going for a front-end development position and you’re asked during the coding test to swap two integer values without a third variable.

Using an array:

var a = 1;
var b = 2;
a = [b, b = a][0];

Simple math:

var a = 1;
var b = 2;
a = a + b; // a = 3 (1 + 2)
b = a - b; // b = 1 (3 - 2)
a = a - b; // a = 2 (3 - 1)

Simple math condensed:

var a = 1; 
var b = 2;
b = (a += b -= a) - b;

Bitwise XOR Swap:

var a = 1;
var b = 2;
a ^= b;
b ^= a;
a ^= b;

ECMAScript 2015 (formerly ES6) Destructuring:
This is my favourite solution of them all. It feels the cleanest, the intent is clearer and it doesn’t rely on any hard to follow math or operators to swap values.

var a = 1;
var b = 2;
[a, b] = [b, a];

Dwayne

Leave a ReplyCancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Handling Errors with the Fetch API
  • How To Get The Hash of A File In Node.js
  • Testing Event Listeners In Jest (Without Using A Library)
  • The Quad Cortex Desktop Editor is Finally Announced
  • How To Paginate An Array In Javascript

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz