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

Array Topic

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

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon