Skip to main content

Command Palette

Search for a command to run...

Populating all values in an array

Updated
1 min read
Populating all values in an array

I was recently tinkering away with JavaScript, when I needed to quickly fill an array with a default value of 0. At the risk of showing my age and JavaScript naivety, I naturally reached for a for loop:

const list = [];

for (let i = 0; i < 10; i++) {
    list[i] = 0;
}

// [0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0]

This is fine and will do what I need. However, one of the benefits of JavaScript these days is the syntactic sugar that has been added in more recent releases of ECMAScript. So why not take advantage of Array.fill()?

const list = Array(10).fill(0);

// [0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0]

The fill() method also accepts two further, optional parameters to define the starting and ending indexes. For example, the code below states that we should set the fifth through ninth values of the list array with a 0.

const list = Array(10).fill(0, 5, 10);

// [5: 0, 6: 0, 7: 0, 8: 0, 9: 0]

More from this blog

Today I Learned

15 posts