DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

Swap two numbers without using a temporary variable

let x = 5, y = 3;
x = x + y;
y = x - y;
x = x - y;
console.log(x, y); // 3 5
Enter fullscreen mode Exit fullscreen mode

Thanks for reading đź’™

Follow @codedrops.tech for daily posts.

Instagram â—Ź Twitter â—Ź Facebook

Micro-Learning â—Ź Web Development â—Ź Javascript â—Ź MERN stack â—Ź Javascript

codedrops.tech

Top comments (17)

Collapse
 
sami_hd profile image
Sami

isn't there a more clever way to do this?

Collapse
 
nnowwakk profile image
nnowwakk

There certainly is. The way in the post only works for numbers and not even very large numbers (the sum of a + b has to be less than MAX_SAFE_INTEGER) but applying the destructuring assignment is the simplest and cleanest way in my opinion.

let a = 1;
let b = 2;

[a, b] = [b, a];

a; // => 2
b; // => 1

Collapse
 
wclayferguson profile image
Clay Ferguson

Not to be negative, but something like this would never be used in production code because the overhead of constructing arrays will be significantly larger than the standard approach of a temp variable.

It's more important that the CPU do less work than to save a line of code. Also, in general 10 lines of simple to read code is always preferable to 1 line of more complex to read code, all other things being equal. Some developers get concerned with counting lines of code, and that's not what matters.

Thread Thread
 
steventhan profile image
Steven Than

I disagree, this code is highly readable. In fact, you'll feel right at home if you come from python world. The following piece of code to swap 2 variables is consider pythonic:

a, b = b, a
Enter fullscreen mode Exit fullscreen mode

If you're worry allocating a temporary array causing performance issue, then you should stay away from JavaScript in the first place

Thread Thread
 
yoursunny profile image
Junxiao Shi

The temporary array is most likely optimized away.

Thread Thread
 
steventhan profile image
Steven Than

That's almost certain, iirc most of the array related code are written C++, at least for Chrome's V8 anyway

Collapse
 
amplanetwork profile image
Ampla Network

Destructuring is a good candidate to swap values.

I agree with @wclayferguson that we need to avoid an overhead, but in the other hand, the first class citizen in Javascript is the Object. Even a function is an object in Js.

You will not have more overhead with an array than any other object in fact.

Its more a question of syntax style in the case of destructuring, the temporary variable is the Array but it still acts as an anonymous temporary variable of the same kind at a low level.

Thread Thread
 
wclayferguson profile image
Clay Ferguson • Edited

It depends on what the variables being swapped hold also, to know performance. If you're swapping two primitives (which are not objects) and you use a temp variable, then there is never any heap memory allocate calls at all, because it's all done on the stack. Any time you do something that causes Objects to get created you're putting a load on the memory allocate, and slowing down the eventual garbage collection etc.

My rule of thumb is never do something the slow way intentionally just because it's slightly more elegant code. As long as the code is clear, the clarity itself is the elegance.

And BTW: I'm not saying a temp variable create calls the allocator. It doesn't. I'm saying creating arrays calls the allocator.

Thread Thread
 
amplanetwork profile image
Ampla Network

Yeah I do agree, It works exactly as you describe in .Net, and other managed languages :-).

Just saying that in JS destructuring is syntactic sugar, I worked 5 years making 2D game frameworks for online lottery games, so can only agree. I think it can be tolerated if it is not done in a heavy statment, like a loop etc. Just my opinion by the way.

Thread Thread
 
wclayferguson profile image
Clay Ferguson

My first 10 years of work was C++, so I know a thing or two about stacks and heaps. haha, and I did agree with everything you were saying.

Thread Thread
 
amplanetwork profile image
Ampla Network

I know we were agree from the begining ha ha, I started coding professionally almost 20 years ago with c++ / c# and JS at the same time (My brain must be a little damaged lol), I hope we master a bit heap, stacks and memory allocation even in managed languages loool.

But it is good to remember how optimization works, and always keep in mind that the way we write code does impact heavily the way it will run.

I remember when I learned in c++ to use a 1 dimensional array as it was a 2 one for performance reason, and then understood that in JS an Array ... is not an Array... but an object with numerical key as properties... No comment... Ha ha ha ha (Until you use a real array like a TypedArray for sure). Definition of fun BTW...

Thread Thread
 
amplanetwork profile image
Ampla Network

Did I really wrote "We were agree", sorry for that, I will return to school to re learn grammar :-)

Thread Thread
 
wclayferguson profile image
Clay Ferguson

We probably have a similar belief on most things, sounds like. I branched off to Java in 1998, and never touched C#. I never forgave Bill Gates for trying to "hijack" Java with his Windows proprietary version of the language, and not until recently and because of VSCode and TypeScript did I personally find forgiveness for MSFT.

Collapse
 
michaelphipps profile image
Phippsy

That is beautiful.

Collapse
 
michaelphipps profile image
Phippsy

Great post. Cool trick! Thanks for introducing me to codedrops.tech!

Serious question though - why would you avoid using the temporary variable?

let x = 5, y = 3, temp = null;
temp = x;
x = y;
y = temp;
console.log(x,y);  // 3 5
Enter fullscreen mode Exit fullscreen mode

Just about the same number of characters, more clear what is being done.

Collapse
 
kenbellows profile image
Ken Bellows

This is a very old school trick that is still useful on contexts like embedded development where you have very limited memory available.

Collapse
 
ml318097 profile image
Mehul Lakhanpal

I too feel it has no real-world application. Limited memory would be possible when used in Embedded Systems. And I feel this is more of a logical question.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.