0

Can anyone explain the next weird behavior?

This works:

const defaultSides = 10;
const stats = Array.apply(null, { length: defaultSides }).map(() => 100);
// Array [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

This doesn't:

const stats2 = new Array(defaultSides);
const res = stats2.map(() => 100);
console.log(res)
//Array [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

I've already solved the problem using either Array.from or Array.of. However, I want to know what causes Javascript to still return me an undefined array after obviously having mapped through it in the second code block.

2 Answers 2

2

new Array(defaultSides) creates a sparse array.

Array#map iterates only non sparse items with the callback.

Due to the algorithm defined in the specification, if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.

Sign up to request clarification or add additional context in comments.

Comments

0

Array constructor does different things depending on the number of arguments. If you give it a number value as it's sole argument it will set the array length property to that value. E.g.

let arr = [];
arr.length = val;

This doesn't actually sets any value from property 0 to val.

If you feed the Array constructor a list of values however (which is what your apply call is doing) it will create an array with those values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.