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
a = 'a1'
b = 'b1'
a = [a,b]
b = a[0]
a = a[1]
print(a,b) # b1,a1
There are better ways like, destructuring, this is just an alternative
Top comments (8)
As a code golf answer, this can be done better, as a lot of languages now support some form of destructuring.
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
Should be faster with my solution compared to yours, but slightly heavier on memory.
10/10
Didn't thought on that one! 😂
Yes it will work in most languages, it's the same from the behaviour point of view than doing:
But the memory footprint is higher using arrays plus the JIT will translate the code above to something like
Either way I never needed to do such thing in real projects, just in college exercises a decade ago😅
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.
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.
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.