JavaScript Array.fill() Function

JavaScript Array.fill() Function | You can fill the array with a supplied static value using the Javascript arr.fill() method. You may utilize the value to fill the entire array or just a portion.

The syntax of the fill() method is:-
array.fill(value, start, end)

Changes all array elements from the ‘start’ to ‘end’ index to a static ‘value’ and returns the modified array. Passing start and end values are optional. Here:-

  • value:- value to fill array section with.
  • start:- index to start filling the array at. If the start is negative, it is treated as length+start where length is the length of the array.
  • end:- index to stop filling the array at. If the end is negative, it is treated as length+end.

JavaScript Array.fill() Function Example-1

In JavaScript Array.fill() function passing start and end values are optional and in that case, all existing array elements will be replaced with the passed value.

let arr = [1, 453, 34, 68];
console.log("Original array: " + arr);

// fill array with 99
arr.fill(99);
console.log("New array: " + arr);

Output:-

Original array: 1, 453, 34, 68
New array: 99, 99, 99, 99

Array fill() JavaScript Function Example-2

In this example, the method fill() replaces all of the original values in the array by filling the array from index 1 to index 2, one less than the top index, with the value 90. The start and end indexes are exclusive in the filling operation.

let arr = [1, 453, 34, 68];
console.log("Original array: " + arr);

// here value = 90, start index=1 and
// and last index = 3
arr.fill(90, 1, 3);

console.log("New array: " + arr);

Output:-

Original array: 1, 453, 34, 68
New array: 1, 90, 90, 99

JavaScript Array.fill() Function Example-3

If we don’t pass the end index then the passed element will be filled from the start index to the end of the array i.e till the length-1 index.

let arr = [1, 453, 34, 68];
console.log("Original array: " + arr);

// here value = 90, start index=2 and
// and last index = arr.length
arr.fill(90, 2);

console.log("New array: " + arr);

Output:-

Original array: 1, 453, 34, 68
New array: 1, 453, 90, 90

JavaScript Array.fill() Function Example-4

All the above programs demonstrate filling elements when the array already contains some elements. Let us see an example when the array doesn’t contain elements.

let arr = new Array(5);
console.log("Original array: " + arr);
arr.fill(9);
console.log("Updated array: " + arr);

Output:-

Original array: ,,,,
Updated array: 9, 9, 9, 9, 9

Also see:- JavaScript Array shift() Function

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *