The Challenge

You have two numeric variables


let a = 1;

let b = 2;

They need to be swapped, so that:

a === 2

b === 1


Simple Swap – No Restrictions

Solution Strategy

Since there are no restrictions, why not just introduce a third variable as temporary storage?

See the Pen Simple Swap by Gil (@gilst) on CodePen.0

Easy peasy. Moving on.

Numeric Swap – Using only A and B

Solution Strategy

The variables serve as storage and you don’t have any storage, so one will need to contain both somehow with the ability to extract the original values.


What happens when you combine both values? You’re left with the combined value on the one hand and one part of the combined value on the other. Can that be served to determine both values in reverse?

See the Pen Numeric Swap by Gil (@gilst) on CodePen.0

Note: this solution is very likely to appear in code interviews. Want to make the interviewer feel a bit less confident? Ask to check this using a=0.1 and b=0.2 and prepare yourself for a good laugh on the interviewer’s expense…

String Swap – Using only A and B

Solution Strategy

Again we’ll need to store the combined value of both vars inside one of them and then extract the information somehow. This time we’ll need to employ some string related functions.

See the Pen String Swap by Gil (@gilst) on CodePen.0


Any Swap – Swap Any Two Variables

Solution Strategy

You can’t assume anything, so combining the vars is out of the question. At least not directly…


Would it be possible to convert the var types without losing their original values?

See the Pen Any Swap by Gil (@gilst) on CodePen.0

Categories: Algorithms

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.