JavaScript Array Method: fill()

Java Script @ Freshers.in

JavaScript arrays offer a plethora of methods for manipulating and modifying their elements efficiently. Among these methods, fill() stands out as a powerful tool for populating an array with a specified value. In this article, we’ll delve into the fill() method, examining its syntax, functionality, and usage through comprehensive examples.

Syntax:

The syntax of the fill() method is straightforward:

array.fill(value[, start[, end]])

Parameters:

  • value: The value to fill the array with.
  • start (optional): The index at which to start filling the array (default is 0).
  • end (optional): The index at which to stop filling the array (default is array.length).

Return Value:

The modified array with the specified value filled in the specified range.

Examples:

Let’s explore the fill() method with detailed examples:

Example 1:

let numbers = [1, 2, 3, 4, 5];
numbers.fill(0);
console.log(numbers); // Output: [0, 0, 0, 0, 0]

In this example, the fill() method is used to populate the numbers array with the value 0, effectively replacing all existing elements with 0.

Example 2:

let fruits = ['apple', 'banana', 'cherry'];
fruits.fill('orange', 1, 2);
console.log(fruits); // Output: ['apple', 'orange', 'cherry']

Here, the fill() method is employed to replace the element at index 1 (‘banana’) with the value 'orange', while leaving the rest of the array unchanged.

Example 3:

let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
matrix.fill([0, 0, 0]);
console.log(matrix); // Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In this example, the fill() method is used to populate each sub-array within the matrix array with the array [0, 0, 0], effectively replacing all sub-arrays with identical arrays.

Author: user