Swapping the values without using temp variable in JavaScript

Introduction:

  It might sound like a very simple interview question but people will struggle sometime to crack it without using the temporary variable in JavaScript.

Swap the values

There are many ways to solve this, but my favorite method is handling it through an array with a single statement.  

var x=10, y =20
[x,y]= [y,x] // the y value will assigned to x and vice versa 
console.log(x,y) 
Figure 1

From the above figure in the browser console you can notice the values are swapped between the two variables.

Summary:

You have learned how to swap the values without using the temporary variable in JavaScript. It might be a simple but always a trick one to handle it in a better way.

I hope you enjoyed this blog.

Happy coding, Cheers!!!

gowthamk91

Leave a Reply

%d bloggers like this: