JavaScript Code


JavaScript Array fill()


fill() – Fills Array with Static Value

array1.fill(value)
array1.fill(value, start)
array1.fill(value, start, end)
  • array1 is an array
  • value is a static value which is filled in the array
  • start is the starting index (inclusive) from which filling happens
  • end is the ending index (exclusive) upto which filling happens

fill() method fills the array with given value from start index upto end index, and returns the resulting array

fill() method modifies the original array array1

if end index is not provided, filling happens upto the end of the array

if both start and end indices are not provided, filling happens for entire array

Examples

1. fill entire array with given value

const array1 = [2, 5, 8, 1, 6, 14, 22, 10];
const value = 0;
array1.fill(value);
console.log(array1);

2. fill array with given value from a specific start index

const array1 = [2, 5, 8, 1, 6, 14, 22, 10];
const value = 0;
const start = 4;
array1.fill(value, start);
console.log(array1);

3. fill array with given value from a specific start index upto specific end index

const array1 = [2, 5, 8, 1, 6, 14, 22, 10];
const value = 0;
const start = 4;
const end = 7
array1.fill(value, start, end);
console.log(array1);

Copyright @2022