Skip to content

Instantly share code, notes, and snippets.

@cheeaun
Created July 5, 2010 02:26
Show Gist options
  • Save cheeaun/463940 to your computer and use it in GitHub Desktop.
Save cheeaun/463940 to your computer and use it in GitHub Desktop.
JavaScript one-liner to swap two variables
// via http://twitter.com/izs/statuses/17744109574
var foo = 1;
var bar = 2;
foo = [bar, bar = foo][0];
@suifengtec
Copy link

swap(x,y){ y = (function(x){ return x })(x, x=y); }

ES6+:
swap(x,y){ return [y,x] }

@jerrylau91
Copy link

ES6 is much better.

@esco
Copy link

esco commented Jul 5, 2018

let x=1
let y=2
{x,y} = {x:y, y:x}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment