totn JavaScript

JavaScript: Array fill() method

This JavaScript tutorial explains how to use the Array method 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 specified value from a starting index position in the array to an ending index. Because the fill() method is a method of the Array object, it must be invoked through a particular instance of the Array class.

Syntax

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

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

Parameters or Arguments

value
The value to use when filling each element of the array.
fill_start
Optional. The index position where the fill of the elements will begin. If fill_start is negative, the index position will be applied (in reverse) starting from the end of the array. If this parameter is not provided, it will default to 0.
fill_end
Optional. The index position where the fill of the elements will end, but does not including the ending element itself. If fill_end is negative, the index position will be applied (in reverse) starting from the end of the array. If this parameter is not provided, it will default to this.length.

Returns

The fill() method returns the modified array with the elements filled as specified by the value, fill_start and fill_end parameters.

Note

  • The fill() method modifies the original array.

Example

Let's take a look 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 called totn_array that has 4 elements. We have then invoked the fill() method of the totn_array variable to modify this array.

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

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

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

In this example, the fill() method will return the modified array after filling the first 2 elements with "z" at index position 0 and 1. Notice that it does not fill the element at index position 2.

Using Negative Parameter Values

When you use negative parameters, the fill() method will determine the index positions starting from the end 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 elements starting at index position -3 and ending at (but not including) the element at index position -1. This means that the third last element and second last element will be populated with the value of 9. Again, notice that it does not fill the last element at index position -1.