As always, I was working on a project and some code I wrote came up to PR Review. The problem in question was I had some data in an array, and I needed to initialize a new array for UI state, determine whether the item would be shown or not. By default everything was shown, so I needed to initialize my "UI State" array to all true boolean values.

The way I did it was this:

view plain print about
1myStateArray = [];
2myDataArray.forEach(() =>
{
3 myStateArray.push(true);
4});
5console.log(myStateArray);

This worked great...

...but is a bit old school. If you poke around the Internet there are other options. I experimented with two of them.

But, before we get to that, you should know you can create an array of any length by passing a number into the Array constructor:

view plain print about
1myStateArray = new Array(myDataArray.length);

All the items in the array are empty, but we do get an array with a specific size.

This is worth noting before we get to future examples.

First, I tried apply().

view plain print about
1myStateArray = Array.apply(null, Array(myDataArray.length)).map(() => true)
2console.log(myStateArray);

This worked, but felt super wordy.

I eventually landed on using the JavaScript Fill method:

view plain print about
1myStateArray = new Array(myDataArray.length).fill(true);
2console.log(myStateArray);

This worked great. I'm reusing the same screenshot, but trust me there are no changes:

Play with the code in this Plunker