• 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

  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How To Decompile And Compile Android APK's On A Mac Using Apktool
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • Wild Natural Deodorant Review

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz