To initialize an array of Boolean values in JavaScript, you can use any of these methods –
- Use Array(n).fill(false) to create an array of n elements where all the elements are set to false. (same for true values)
- Use Array.apply(null, {length: n}).map(Boolean) to create an array of n elements where all the elements are set to Boolean.
- Use for loop to fill an array with Boolean values.
Let’s discuss each of these methods in detail below.
Initialize An Array Of Boolean Values In JavaScript
Use Array(n).fill() To Initialize Boolean Values
Array.fill() is an inbuilt function that fills all the elements of an array from a start index to end index with a static value. The fill() method changes the contents of an array by filling it with a static value, from a start index (default 0) to an end index (default array.length). It modifies the original array in-place.
Syntax:
arr.fill(value)
Parameters: This method accepts three parameters as mentioned above and described below:
value: Value to fill the array with. If it is undefined, then the undefined values are filled in that array.
start (optional): Start index to fill the value from. Default is 0.
end (optional): End index to fill the value till. Default is array length.
Return Value: It returns the modified array object.
Example 1: This example initializes an array of Boolean values by using fill() method.
var arr = new Array(5).fill(false);
console.log(arr);
Output:
[false, false, false, false, false]
Example 2: We can also fill the array with true values.
var arr = new Array(5).fill(true);
console.log(arr);
Output:
[true, true, true, true, true]
Use for Loop To Initialize Boolean Values
A for loop is used to initialize an array of Boolean values. A loop executes a set of statements repeatedly until a condition is satisfied. Initially, the condition is checked and if it evaluates to true then only the code inside the body of for loop will execute, otherwise not.
Syntax:
for(initialization; condition; increment/decrement){
// Statements to be executed
}
Example: This example initializes an array of Boolean values by using for loop.
var arr = new Array(5);
for (var i = 0; i < 5; i++) {
arr[i] = false;
}
console.log(arr);
Output:
[false, false, false, false, false]
Example 2: We can also fill the array with true values.
var arr = new Array(5);
for (var i = 0; i < 5; i++) {
arr[i] = true;
}
console.log(arr);
Output:
[true, true, true, true, true]
Conclusion – Initialize An Array Of Boolean Values In JavaScript
In this article, you have learned how to initialize an array of Boolean values in JavaScript. You can choose any method depending on your requirement and the size of the array. I hope this article was helpful and informative. Thank you for reading!