JavaScript Toggles

Introduction

This page takes a look at the best methods of toggling, switching or swapping JavaScript variables and boolean values. Over the course of researching and writing this page I ran all the methods numerous times. Even when run millions of times there is very little difference in the speed any this code but there are trends appearing with some of the codes running twice as fast as others.

Swapping Any Two Values

Thee are several methods of swapping the values of two variables. Some are better than others in that they are faster, use less memory, make more accurate exchanges and can handle a wider range of variable types.

The following supposes you have two variables a and b and want to swap their values.

Using a Third Variable

This method uses a third variable, c, to temporarily hold the value of one of the variables while it is being swapped. This works on every data type and is still one of the fastest methods of swapping variables:

c = a;
a = b;
b = c;

Using an Array

This method creates an array from both variables. It can be used for any data type, it is very fast, and is:

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

What is happening is that when the array is created the first index a (it would normally be [0] is set to the value of variable b. The second index b, which would normally be [1] is set to the value of variable a.

Arrow Function Expression

This uses an arrow function expression which is an alternative to normal functions. It can be used on any data type but is slower than both the third variable and array swapping methods.

b = (a=>a)(a,a=b);

Destructuring Assignment Array

Destructuring assignment arrays is a method that makes it possible to unpack values from arrays. It can be used on any data type but is slower than both the third variable and array swapping methods.

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

Swapping Any Two Integers

The following codes only work reliably for integer variable swapping.

Using Mathematics

This method uses mathematics to swap the variables. This method should only be used with integers. Using decimal numbers with the code as it is can give slight rounding errors which probably is not what is needed.

a = a + b
b = a - b
a = a - b

Which can be rewritten as:

a += b;
b = a - b;
a -= b;

What is happening and how does this work? It might be easier to put it into words:

Variable a becomes a + b, b retains its original value. Variable b becomes a - b which is a's value. Variable a becomes a - b, which means it is taking it's old value from step 1 from itself, whch leaves b's original value.

Using XOR

The XOR swap algorithm is fairly well-known and detailed on Wikipedia. This method is only suitable for integers. If decimals are used the decimal part is stripped off and if strings are used both variables are set to zero. This is the fasted method of swapping two integer values.

a = a ^ b;
b = a ^ b;
a = a ^ b;

or it can be rewritten as

a ^= b;
b ^= a;
a ^= b;

Single line XOR swapping

This method is only suitable for integers. If decimals are used the decimal part is stripped off and if strings are used both variables are set to zero. This method is simply:

a = a^b^(b^=(a^b));

Toggle a Boolean

The simplest method is to use:

bool = !bool;

Code


<p><button type="button" onClick="boolSwap()">Toggle Boolean</button> <span id="showBool"></span></p>
	  
<script type="text/javascript">
var bool = true;
document.getElementById('showBool').innerHTML = bool;
	
function boolSwap() { 
bool = !bool;
document.getElementById('showBool').innerHTML = bool;
}
</script>

Toggle a Binary

The simplest method is to use a Bitwise XOR Assignment Operator. This probably is most useful where the variable is a 0 or 1, and the operator toggles between those two values. If the variable is setto another integer, then the operator toggles between that number and the one above it, for example bwtween 12 and 13. If a decimal number is used, for example 12.456 then the number is first rounded up to 13 then toggles between 13 and 12.

bin ^= 0;

Code


<p><button type="button" onClick="binSwap()">Toggle Binary</button> <span id="showBin"></span></p>
	  
<script type="text/javascript">
var bin = 0;
document.getElementById('showBin').innerHTML = bin;
	
function binSwap() { 
bin ^= 1;
document.getElementById('showBin').innerHTML = bin;
}
</script>

Speed Tests

These are very simple tests where the variables are swapped 1 million times and the time taken in milliseconds returned.

Any Two Variable Swaps

Third variable swaps: ms
Array swaps: ms
Arrow function swaps: ms
Destructuring assignment array swaps: ms

Integer Only Swaps

Math swap: ms
XOR swap: ms
Single line XOR swap: ms

Toggles

Boolean toggle: ms
XOR toggle: ms

Ternary Conditional Operator

A ternary operator can be viewed as a simple if ... else statement. The form of it is:

condition ? valueIfTrue : valueIfFalse;

They can also be used as an if statement with no else using:

condition ? valueIfTrue : null;

Like if ... else statement they can also be nested:

condition1 ? valueIfTrue1 : condition2 ? valueIfTrue2 : valueIfFalse2

Whether an if ... else, ternary operator or switch statement is used it should be remembered that clarity in the code is important. Ternary operator statements may be very short but that may not be much help if it becomes necessary to amend the code.

This page created February 8, 2023; last modified February 12, 2023