How to use the fill() Method In Javascript
The fill() method in JavaScript is a method that is used to populate an array with a static value. It accepts two arguments: the first argument is the value that will be used to fill the array, and the second argument is the starting index from where the filling process will start.
The fill method is useful in situations where we need to initialize an array with a default value or when we need to reset the values of an array to a specific value.
Syntax:
const zeros = new Array(size_array).fill(item);
Example: In the given example, we are creating an array of 0s of size 5 using the fill method.
const zeros = new Array(5).fill(0);
console.log("Zeros: " + zeros);
Output
Zeros: 0,0,0,0,0
Different ways to populate an array in JavaScript
Populating an array in JavaScript means initializing it with elements. This could involve adding values manually, dynamically generating values using loops or functions, or copying elements from another array. It’s a fundamental operation for creating and manipulating arrays in JavaScript programs.
These are the following ways to populate an array:
Table of Content
- Using Array literal notation
- Using a for loop
- Using the fill() Method
- Using the from() Method
- Using the map() Method
- Using Spread Operator