Table of Contents
- Using the fill() method
- Using a for loop
- Using the push() method in combination with for loop
- Using the from() method
- Using the “spread” syntax
- Other Related Concepts
Using the fill() methodThe fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled.
One thing to keep in mind is that this method modifies the original/given array. Also using this method on objects instead of cloning/creating multiple objects, all objects refer to the same instance. We shall look at other methods to overcome this problem.
Using a for loopAnother method by which we can fill the elements of an array is using a simple for loop. Though, using this does not have any specific advantage over the previous method, apart from the ability to also work on old browsers that dont support the fill() method.
Using the push() method in combination with for loopThis, like the previous method, does not have any advantage over the fill() method and is indeed slower than the previous methods. It uses a push() method inside the “for” loop as shown below.
One major difference between this method and the previous methods is that the push() method adds new elements to the end of the array. This means that the existing elements cannot be replaced using push().
Using the from() methodWe had seen that using the fill() method, we cannot create multiple objects because all of the created objects refer to one instance. To prevent this and fill arrays using objects, we can instead use the from() method.
The from() method, returns an array of objects when an object with length property or an iterable object is input
Where, “object” is a required parameter & the other 2(mapFunction, thisValue) are optional parameters
In this case, we are creating an empty object with a length property set to 10
Using the “spread” syntaxThe spread syntax is simply “..” i.e. two dots. What it does is, as the name suggests, expands the entered iterables. Please refer to this article to understand how spread syntax works. Let us now use it to fill an array.
In the above example, using the “spread” syntax helps the map function to map 0 to 10 positions in an array.