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.

start_index defaults to 0. end_index defaults to length of myArray.

If start_index is negative, it is treated as length+start_index

If end_index is negative, it is treated as length+end_index

// example of using array.fill()
const ar = [0,1,2,3,4,5];

console.log( ar.fill (7) ); // [ 7, 7, 7, 7, 7, 7 ]
console.log( ar.fill (8, 1) ); // [ 7, 8, 8, 8, 8, 8 ]
console.log( ar.fill (9, 1, 3) ); // [ 7, 9, 9, 8, 8, 8 ]

// the variable is changed
console.log ( ar ); // [ 7, 9, 9, 8, 8, 8 ]

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

  1. JS: Array Object
  2. JS: Array.prototype
Like what you read? Buy JavaScript in Depth