javascript
  1. javascript-fill

JavaScript fill()

The fill() method in JavaScript is used to fill all elements of an array from a start index to an end index with a static value. This method modifies the original array and returns the modified array.

Syntax

The syntax of the fill() method is as follows:

array.fill(value, start, end)
  • 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 end filling the array (not included). Default is the length of the array.

Example

Consider the following example:

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

In this example, the fill() method is used to fill the elements of the arr array from index 2 to 4 with the value 0.

Output

The output of the above example is:

[1, 2, 0, 0, 5]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fill Array Example</title>
</head>
<body>

<script>
    // Original array
    let arr = [1, 2, 3, 4, 5];

    // Use the fill method to replace elements with 0 from index 2 to index 4 (exclusive)
    arr.fill(0, 2, 4);

    // Log the original and modified arrays
    document.write("<p>Original Array: " + arr.join(", ") + "</p>");

    // If you want to display the modified array using console.log, you can use the following:
    console.log("Modified Array:", arr);
</script>

</body>
</html>

Try Playground

Explanation

The fill() method modifies the original array arr by filling the elements from index 2 to 4 with the value 0. The modified array is then printed to the console.

Use

The fill() method can be used in various scenarios, including:

  • Initializing an array with a default value.
  • Replacing a range of elements in an array with a new value.
  • Creating an array of a given length with a fixed value.

Important Points

The following are some important points to keep in mind when using the fill() method:

  • The fill() method modifies the original array and does not create a new array.
  • If the start index is greater than the end index, no elements will be filled.
  • If the start index is negative, it represents the index from the end of the array.
  • If the end index is negative, it represents the index from the end of the array.

Summary

The fill() method in JavaScript is a useful method for filling elements of an array with a given value. It modifies the original array and is useful in a variety of scenarios, including initializing an array with a default value and replacing a range of elements in an array with a new value. Its syntax is simple, and it can be used easily in programs.

Published on: