JS: Array.prototype.fill

By Xah Lee. Date: . Last updated: .

New in ES2015.

Replace all elements by value, from start_index to end_index, not including end_index.

Return the modified myArray.

myArray is modified.

If start_index is negative, it's the same as length+start_index (same as counting from right).

If end_index is negative, it's the same as length+end_index (same as counting from right).

const ar = [0,1,2,3];

console.log ( ar.fill (7) ); // [ 7, 7, 7, 7 ]

// original array is changed
console.log ( ar ); // [ 7, 7, 7, 7 ]

With 2 arguments:

// example of using Array.prototype.fill()

console.log( [0,1,2,3].fill(9, 0)); // [ 9, 9, 9, 9 ]

console.log( [0,1,2,3].fill(9, 1)); // [ 0, 9, 9, 9 ]

console.log( [0,1,2,3].fill(9, 2)); // [ 0, 1, 9, 9 ]

console.log( [0,1,2,3].fill(9, 3)); // [ 0, 1, 2, 9 ]

console.log( [0,1,2,3].fill(9, 4)); // [ 0, 1, 2, 3 ]

With 3 arguments:

// example of using Array.prototype.fill()

console.log( [0,1,2,3].fill(9,0,0)); // [ 0, 1, 2, 3 ]

console.log( [0,1,2,3].fill(9,0,1)); // [ 9, 1, 2, 3 ]

console.log( [0,1,2,3].fill(9,0,2)); // [ 9, 9, 2, 3 ]

console.log( [0,1,2,3].fill(9,0,3)); // [ 9, 9, 9, 3 ]

console.log( [0,1,2,3].fill(9,0,4)); // [ 9, 9, 9, 9 ]

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.fill

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To
  6. Array Object
  7. Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog