JavaScript Array fill() Tutorial

In this section, we will learn what the fill() method is and how to use it in JavaScript.

JavaScript Arrays fill() Method

The `fill()` method is used to insert the same value into all or part of an existing array.

For example, let’s say you have a value like “John” and for some reason want to fill the entire indices of this array with this value! The fill() method is the key to do so.

Array fill() Syntax:

array.fill(value, start, end)

Array fill() Method Parameters:

The method takes 3 arguments:

  • The first argument is the value that we want to fill the array with.
  • The second argument is the start index that instructs the fill to begin at that index. This value is optional and, if ignored, the fill starts at the index 0.
  • The third argument, which is again optional, declares the end index where the fill operation should stop. If this value is ignored, the fill will continue to the end of the array.

Note: for the second and third arguments of the array, the negative indices are interpreted from the end of the array; another way to think of this is that negative indices have the array length added to them to calculate a positive index. For example, if the length of an array is 10, and we set the index number -2, that means the position must be the index number 8.

Array fill() Method Return Value:

The return value of this method is a reference to the changed array.

Example: using Array fill() method in JavaScript

const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"];

arr.fill(0);

console.log(arr);

Output:

[0, 0, 0, 0, 0, 0]

JavaScript Array fill() Method Example:

const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"];

arr.fill("John",2);

console.log(arr);

Output:

["Tesla", "Google", "John", "John", "John", "John"]

Example: filling an array with JavaScript fill() method

const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"];

arr.fill("John",2, 5);

console.log(arr);

Output:

["Tesla", "Google", "John", "John", "John", "Twitter"]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies