DEV Community

Cover image for Swapping Values in Es7
Uriel Bitton
Uriel Bitton

Posted on

Swapping Values in Es7

News of JavaScript ES7 has recently been around boasting its new features. After reading various articles on its cool new features,i decided to share my favorite of them.

Before ES7 swapping 2 values was annoying and counterintuitive, the idea is to store one value in a temporary variable so that you can exchange them, adding extra lines of code. In total you need minimum 3 lines of code to swap to values. Say we want to swap the contents of a and b, we need to introduce a third variable, c:

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

With ES7, the new way is super simple and intuitive:

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

Amazing, isn't it? Super simple and just one line!

Hope you enjoyed that one!

Discussion (3)

supportic profile image

Destructuring came with ES6

raddevus profile image

Wow! That is interesting. I wonder if that is because all variables are in the global scope or something and then this is referencing the array of variables in the global scope?? Thanks for writing this up.
Are you going to enter the #dohackathon challenge here? I completed my entry yesterday. If you get a chance take a look at it and let me know what you think. Let me know if you enter the challenge. I'd be interested in seeing what app you will build. thx

theeasydev profile image
Uriel Bitton Author

Hey raddevus, thanks for reading my short post! I have been so busy with work and projects i cannot find time to enter the challenge haha. But let's connect and talk more!