Toggle a Boolean in JavaScript

Hero image for Toggle a Boolean in JavaScript. Image by Isabella and Zsa Fischer.
Hero image for 'Toggle a Boolean in JavaScript.' Image by Isabella and Zsa Fischer.

Toggling the value of a variable in JavaScript is an incredibly common task, which can be achieved in a number of different ways.


The not operator (!)

The not operator inverts the boolean value of a variable, so if a variable is true, it will become false and vice versa. For example, let's say we have a variable isOn; this is a boolean representing whether a light is switched on or off.

If we wanted to toggle the value of the variable, it might look something like this:

let isOn = true;isOn = !isOn;console.log(isOn);//=> false

Here, we first assign the isOn variable the value of true. We then use the not operator to invert the value of isOn and assign the inverted value back to isOn. The output will be false; the light is now switched off.


Using a Ternary

We could also use the ternary operator to toggle the value of a variable:

let isOn = true;isOn = isOn ? false : true;console.log(isOn);//=> output: false

In this example, the ternary operator checks the value of isOn. If isOn is true, it will assign the value of false, otherwise, it will assign the value of true.

In this instance, the output will be false again, indicating that the light has been turned off.


Creating a Toggle Function

All of this can be wrapped up until a very simple utility function like this:

const toggleValue = (value) => !value;

All this does is accept a value, and return the inverse of it:

console.log(toggleValue(true));//=> false

Personally, I would take this one step further and introduce the doublebang operator, or in this case the triplebang:

const toggleValue = (value) => !!!value;

I go into this in much more detail in another article, but essentially: the weakness in the original version of this function is that there is no type protection, value could be a boolean, a string, or a number. The doublebang (!!) typecasts this to a strict boolean, the triplebang adds the not operator (!) which then inverts this value.


The Wrap‑Up

Wrappingup: we can toggle the value of a variable in JavaScript by inverting its value using the not operator, ternary operator or even writing a little utility function that incorporates either.

The not operator is the most concise way of toggling a variable, but using a function might be useful in case we want to use the toggle functionality multiple times in our code and want to keep it separate for readability and maintainability purposes.


Categories:

  1. Front‑End Development
  2. JavaScript