This page looks best with JavaScript enabled

Initiate Arrays with Data in Javascript

 ·   ·  ☕ 1 min read

Create arrays and initiate data in a single statement.

Traditionally you would do the below to initiate the array and fill it with values -

1
let planets = ["mercury", "venus", "earth"];

This is a-ok if you know the values, but what if you want array to have fixed elements with pre-defaulted values? This is where fill (an ES6 feature) steps in.

1
2
let planets = new Array(3).fill("");
console.log("planets: ", planets); // [ '', '', '' ]

You could also instantiate only certain elements of the array as well.

1
2
let allMyNums = new Array(5).fill(0, 1, 5);
console.log("allMyNums: ", allMyNums); // <1 empty item>, 0, 0, 0, 0

fill is both fast and efficient. But it can support instantiating with a single value.

We do not have a comparable feature for objects - it may not make a lot of sense to create ten empty properties :)

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things