How to Swap Two Variables in JavaScript

How to swap two variables in JavaScript

Here's a one-liner to swap the values of two variables.

Given variables a and b:

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

Demonstration below:

var a=1,
b=2,
output=document.getElementById('output');

output.innerHTML="<p>Original: "+a+", "+b+"</p>";

// swap values for variables "a" and "b"
b = [a, a = b][0];

output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
<div id="output"></div>

Swapping object variables in Javascript without using a 3rd variable

var a=1,
b=2,
output=document.getElementById('output');
output.innerHTML="<p>Original: "+a+", "+b+"</p>";
b = [a, a = b][0];
output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";

<div id="output"></div>

which way to swap two variable values is more optimised?

Here you can see by yourself.

Change the NUMBER_OF_TIMES as you would like.

Also run it as many times as you want to get the average.

let NUMBER_OF_TIMES = 1000000console.time("Method1")for (let i = 0; i < NUMBER_OF_TIMES; i++) {  var a = 0, b = 1, c = a;  a = b;  b = c;}console.timeEnd("Method1")console.time("Method2")for (let i = 0; i < NUMBER_OF_TIMES; i++) {  var [a, b] = [0, 1];  [a, b] = [b, a];}console.timeEnd("Method2")

Swapping Two Numbers, but only in a special case

You could take an object for swapping the values and the value directly as default value, like

a = { 3: 4, 4: 3 }[a] || a;

If you like to work with a falsy value, like zero, you could take the Nullish coalescing operator ?? instead of logical OR ||.

a = { 3: 4, 4: 3 }[a] ?? a;

Javascript. Swap two variables. How it works?

This notation is called destructuring assignment and is part of Javascript 1.7:

Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.

The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.

One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.

The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.

Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.



Related Topics



Leave a reply



Submit