DEV Community

Discussion on: 8 JavaScript Tips & Tricks That No One Teaches 🚀

Collapse
 
lkarabeg profile image
lkarabeg

I kind of disagree, finding map much more readable.
Array.from({length: 4}).map((_value, index) => (index + 1) * 3)

Thread Thread
 
peerreynders profile image
peerreynders

With

const array = (new Array(length)).fill().map(init);
Enter fullscreen mode Exit fullscreen mode

it always ground my gears that to arrive at the desired array another disposable array had to be created and "filled" just to convey that I want length elements. And

const array = (new Array(length)).fill();
array.forEach((_v, i, a) => {
  a[i] = (i + 1) * 3;
});
Enter fullscreen mode Exit fullscreen mode

was clunky enough to make me want to use a for loop.

So if I'm are already using Array.from() I might as well use the optional mapFn and thisArg parameters.

function init(_value, index) {
  return (index + 1) * this.factor;
}

const config = { length: 4 };
const two = { factor: 2 };
const three = { factor: 3 };
const array2 = Array.from(config, init, two);
const array3 = Array.from(config, init, three);

const checkArray = (expected, actual) => {
  const actualMatches = (value, index) => value === actual[index];
  console.assert(
    expected.length === actual.length && expected.every(actualMatches),
    'array mismatch - expected: %o actual: %o',
    expected,
    actual
  );
};
const TWOS = [2, 4, 6, 8];
const THREES = [3, 6, 9, 12];
checkArray(TWOS, array2);
checkArray(THREES, array3);
Enter fullscreen mode Exit fullscreen mode

... but that's just me.

Some comments have been hidden by the post's author - find out more