Using Array fill() method to coding in Javascript/JS

This JavaScript tutorial explains how to use the Array approach called fill() with syntax and examples.

Description

In JavaScript, fill() is an Array method that is used to populate the elements of an array with a unique value from a beginning index role in the array to an ending index. Because the fill() technique is a method of the Array object, it need to be invoked through a particular instance of the Array class.

Syntax

In JavaScript, the syntax for the fill() approach is:

array.fill(value [, fill_start [, fill_end]] );

Parameters or Arguments

value The fee to use when filling each factor of the array. fill_start Optional. The index position where the fill of the factors will begin. If fill_start is negative, the index role will be applied (in reverse) starting from the stop of the array. If this parameter is not provided, it will default to 0. fill_end Optional. The index position the place the fill of the factors will end, but does now not consisting of the ending aspect itself. If fill_end is negative, the index function will be applied (in reverse) starting from the end of the array. If this parameter is no longer provided, it will default to this.length.

Returns

The fill() approach returns the modified array with the elements filled as detailed through the value, fill_start and fill_end parameters.

Note

The fill() method modifies the original array.

Example

Let’s take a appear at an example of how to use the fill() method in JavaScript.

For example:

var totn_array = ['t','o','t','n'];

console.log(totn_array.fill('z', 0, 2));

In this example, we have declared an array object known as totn_array that has four elements. We have then invoked the fill() approach of the totn_array variable to regulate this array.

We have written the output of the fill() method to the web browser console log, for demonstration purposes, to exhibit what the fill() technique returns.

The following will be output to the web browser console log:

["totn", "z", "z", "t", "n"]

In this example, the fill() technique will return the modified array after filling the first 2 elements with “z” at index function 0 and 1. Notice that it does no longer fill the aspect at index role two

Using Negative Parameter Values

When you use bad parameters, the fill() technique will decide the index positions beginning from the give up of the array.

For example:

var totn_array = [1,2,3,4,5,6,7];

console.log(totn_array.fill(9, -3, -1));

The following will be output to the web browser console log:

[1, 2, 3, 4, 9, 9, 7]

In this example, the fill() method will return the modified array and fill the factors starting at index role -3 and ending at (but no longer including) the issue at index role -1. This skill that the 0.33 ultimate factor and second last element will be populated with the cost of 9. Again, be aware that it does not fill the ultimate component at index role -1.