• 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 Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Which Neural DSP Archetype Plugins Should You Buy?
  • Smoke Detector Randomly Goes Off Early Hours of The Morning
  • How To Mock uuid In Jest
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • Web 3.0 may have died before it even started
  • Deno Raises $21M - but is anyone using it yet?
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • How To Install Eufy Security Cameras Without Drilling or Using Screws

Recent Comments

  • Jay on Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • john on Deno Raises $21M – but is anyone using it yet?
  • Oranges on How To Store Users In Firestore Using Firebase Authentication
  • Precious on Fixing Sequel Pro SQL Encoding Error For Imported SQL Files
  • James on A List of WordPress Gutenberg Core Blocks

Copyright © 2022 · Dwayne Charrington · Log in

wpDiscuz