Javascript Array fill()

Introduction

The fill() method changes all array elements to a static value.

We can set from index (default 0) and end index (default array.length).

It returns the modified array.

arr.fill(value[, start[, end]])
Parameter
Optional
Meaning
value

Not

Value to fill the array with.
All elements in the array will be this exact value.
start

Optional

Start index, default 0.
If start is negative, it is treated as array.length + start.
end

Optional

End index, default arr.length.
If end is negative, it is treated as array.length + end.

fill all the array elements with the value "SQL".

var languages = ["CSS", "HTML", "Java", "Javascript"];
console.log(languages);//from   www  .  j  ava  2 s. c o m

console.log(languages.fill("SQL"));

More example

const zeroes = [0, 0, 0, 0, 0];//ww w  .ja va 2  s  .  c om

// Fill the entire array with 5 
zeroes.fill(5);
console.log(zeroes); // [5, 5, 5, 5, 5] 
zeroes.fill(0); // reset 

// Fill all indices >=3 with 6 
zeroes.fill(6, 3);
console.log(zeroes); // [0, 0, 0, 6, 6] 
zeroes.fill(0); // reset 

// Fill all indices >= 1 and < 3 with 7 
zeroes.fill(7, 1, 3);
console.log(zeroes); // [0, 7, 7, 0, 0];  
zeroes.fill(0); // reset 

// Fill all indices >=1 and < 4 with 8 
// (-4 + zeroes.length = 1) 
// (-1 + zeroes.length = 4) 
zeroes.fill(8, -4, -1);
console.log(zeroes); // [0, 8, 8, 8, 0]; 

More examples.

let a = [1, 2, 3].fill(4)                // [4, 4, 4]
console.log(a);//ww w .  j  a  va2  s  .  c o  m
a = [1, 2, 3].fill(4, 1)             // [1, 4, 4]
console.log(a);
a = [1, 2, 3].fill(4, 1, 2)          // [1, 4, 3]
console.log(a);
a = [1, 2, 3].fill(4, 1, 1)          // [1, 2, 3]
console.log(a);
a = [1, 2, 3].fill(4, 3, 3)          // [1, 2, 3]
console.log(a);
a = [1, 2, 3].fill(4, -3, -2)        // [4, 2, 3]
console.log(a);
a = [1, 2, 3].fill(4, 3, 5)          // [1, 2, 3]
console.log(a);
a = Array(3).fill(4)                 // [4, 4, 4]
console.log(a);

fill() method fills the same object reference to each array element.

let arr = Array(3).fill({}) // [{}, {}, {}]
arr[0].hi = "hi"            // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
console.log(arr);/*w ww  . jav  a  2  s  .c  o m*/

fill() silently ignores ranges that

  • exceed the boundaries of the array,
  • are zero length, or
  • go backwards:
const zeroes = [1, 1, 1, 1, 1];/*w ww . j  a  v a 2  s.  c om*/

// Fill with too low indices is noop 
zeroes.fill(1, -10, -6);
console.log(zeroes); // [1, 1, 1, 1, 1] 

// Fill with too high indices is noop 
zeroes.fill(1, 10, 15);
console.log(zeroes); // [1, 1, 1, 1, 1] 

// Fill with reversed indices is noop 
zeroes.fill(2, 4, 2);
console.log(zeroes); // [1, 1, 1, 1, 1]  

// Fill with partial index overlap is best effort 
zeroes.fill(4, 3, 10)
console.log(zeroes);



PreviousNext

Related