Initialize an Array of Boolean Values in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Anthony Tran

Initialize an Array of Boolean Values #

To initialize an array of boolean values, use the Array() constructor to create an array of a specific length and call the fill() method on the array to populate it with booleans, e.g. new Array(3).fill(false) creates an array with 3 elements with a value of false.

index.js
const arr1 = new Array(3).fill(false); // ๐Ÿ‘‡๏ธ [false, false, false] console.log(arr1);

The only parameter we passed to the Array() constructor is the number of empty elements the array should contain.

index.js
console.log(new Array(3)); // ๐Ÿ‘‰๏ธ [ , , ]

The Array() constructor basically creates a new array and sets its length property to the provided integer.

index.js
const arr = []; arr.length = 3; console.log(arr); // ๐Ÿ‘‰๏ธ [ , , ]

Either way the new array contains 3 empty elements, which we can set to a boolean value using the fill() method.

The only parameter we passed to the fill method is the value we want to assign to each element in the array.

In the specific example, each of the 3 array elements get assigned a value of false.

The fill() method is not supported in Internet Explorer. If you have to support the browser, use a for loop instead.

Initialize an Array of Boolean Values using for loop #

To initialize an array of boolean values, use the Array() constructor to create an array of a specific length and use a for loop to iterate over the array and assign a boolean value to each element.

index.js
const arr2 = new Array(3); for (let i = 0; i < arr2.length; i++) { arr2[i] = false; } // ๐Ÿ‘‡๏ธ [false, false, false] console.log(arr2);

We used the Array() constructor to create an array of 3 empty elements, just like in the last example.

The next step is to use a for loop to iterate over the array, assigning a boolean value to each empty element.

The Array.fill() method is my preferred approach when supported. The method is more concise and declarative than a for loop and solves the specific problem of filling an array with a provided value.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee