0

I want to initialize an array of a given size with elements set to undefined by default.

new Array(5) returns an array of 5 empty items. Array.apply(null, Array(5)) returns exactly what I want: a five element array with each element as undefined.

Why does the second option produce a different array value than the first?

This distinction is important because I can map over an array of empty items but I can for undefined elements.

new Array(5).map(Boolean) // [false, false, false, false, false]

Array.apply(null, Array(5)) // [ <5 empty items>]
1

3 Answers 3

1

.map is a native Array object method that is expected to return a value for every iteration over the array to create a new copied array from the array. Boolean can be used as a constructor function to create a boolean object with a true or false value. Try the same thing with Number like:

new Array(5).map(Number)

In your second example, .apply calls a function with a supplied context value as the first parameter, and the parameter the function takes in as the second parameter. Also here, Array can be used as a constructor function, to construct a new Array (just like with Number and Boolean of their respective types)

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

Comments

0

First of All, Javascript array is a Object. If you check this, you will understand it. ONly specialty is,it has length property that regular object in javascript.

var array = new Array(5) 
typeof array

And other thing is Array.apply mean, it will call array native function with setting given context which is null for your case and parameters are in another array.

Array.apply(null, [,,,,,]);

output will be [undefined, undefined, undefined, undefined, undefined]

Comments

0

I personally would use Array.from

console.log(Array.from({ length: 5 }))

// if you want to initialise the values you can add a constructor function

console.log(Array.from({ length: 5 }, (_, index) => index + 1))

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.