DEV Community

mmvergara
mmvergara

Posted on

The Array Way to Swap Variable - js,py and etc. i think.

This will pretty much will work in any data types im assuming?

let a = 'a1'
let b = 'b1'

a = [a,b]
b = a[0]
a = a[1]

console.log(a,b) // b1,a1
Enter fullscreen mode Exit fullscreen mode
a = 'a1'
b = 'b1'

a = [a,b]
b = a[0]
a = a[1]

print(a,b) # b1,a1
Enter fullscreen mode Exit fullscreen mode

There are better ways like, destructuring, this is just an alternative

Top comments (8)

Collapse
 
fjones profile image
FJones

As a code golf answer, this can be done better, as a lot of languages now support some form of destructuring.

let a = 1, b = 2;
[b, a] = [a, b];
console.log(a, b);
Enter fullscreen mode Exit fullscreen mode
$a = 1; $b = 2;
[$b, $a] = [$a, $b];
echo $a.$b;
Enter fullscreen mode Exit fullscreen mode
a = 1
b = 2
[b, a] = [a, b]
print (a, b)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mmvergara profile image
mmvergara

yeah we probably all know this. im just sharing this alternative. do you know about which one is faster or like takes less memory? im genuinely curious

Collapse
 
fjones profile image
FJones

Should be faster with my solution compared to yours, but slightly heavier on memory.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

10/10
Didn't thought on that one! 😂

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Yes it will work in most languages, it's the same from the behaviour point of view than doing:

let a = 1, b = 2;
let c = a;

a = b;
b = c;
// set c = undefined or let the GC do its thing
Enter fullscreen mode Exit fullscreen mode

But the memory footprint is higher using arrays plus the JIT will translate the code above to something like

let a=2, b=1;
Enter fullscreen mode Exit fullscreen mode

Either way I never needed to do such thing in real projects, just in college exercises a decade ago😅

Collapse
 
fjones profile image
FJones

It has some applications in hashing and cryptography, to be fair. Rapid shifting of multiple values between variables. Though there's certainly easier (faster, and more lightweight) ways to achieve that.

Collapse
 
mmvergara profile image
mmvergara

Yeah i agree, I just thought of sharing it, when I ask people in my campus they are always saying use the + - method which only works on ints. goodness.

Collapse
 
redhap profile image
HAP

Suddenly, a integer-only solution appears that doesn't use an array/tuple. 'Tis a fun little value exchange routine w/o a third variable. Not useful, but fun.

# python
a = 1
b = 2
a = a + b
b = a - b
a = a - b
print(a, b)  # 2 1
Enter fullscreen mode Exit fullscreen mode
# bash
a=1
b=2
a=$(( $a + $b ))
b=$(( $a - $b ))
a=$(( $a - $b ))
echo "$a $b"
Enter fullscreen mode Exit fullscreen mode