How to Create a Boolean Array in JavaScript

Published Feb 27, 2022  ∙  Updated May 2, 2022

How can we create a boolean array of all true or all false values in JavaScript?

1. Initialize boolean array with fill()

We can easily initialize a boolean array with the same boolean value using fill().

let arr = new Array(5).fill(true);
// [true, true, true, true, true]

Of course, we can initialize everything to false as well.

let arr = new Array(5).fill(false);
// [false, false, false, false, false]

2. Initialize boolean array with Array.from()

We can pass an empty object of length: 5 into Array.from().

Each value will be undefined, but we’ll iterate through every index.

Naturally, we can generate a simple sequence of numbers.

let arr = Array.from({length: 5}, (value, index) => index);
// [0, 1, 2, 3, 4]

Instead of setting the value to be the index, we can set it to a boolean value.

let arr = Array.from({length: 5}, (value, index) => true);
// [true, true, true, true, true]

3. Initialize boolean array with for loop

The final option is to use a simple for loop.

let arr = [];
for (let i = 0; i < 5; i++) {
  arr.push(true);
}