5

I am trying to declare and initialize an array with 0, in javascript. I created an array and set the length like this.

var previousRow = [];
previousRow.length = 5;

Then, I did this.

console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);

and I got,

[ , , , ,  ]
[ , , , ,  ]

But, when I did

console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf, 0);
console.log(previousRow);

I got what I expected

[ , , , ,  ]
[ 0, 0, 0, 0, 0 ]

Why the first code didn't work?

1

1 Answer 1

14

Read the MDN documentation for map. It clearly states:

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

The previousRow array is an empty array of length 5. However the elements have never been assigned a value:

var previousRow = [];
previousRow.length = 5;

Since the elements of previousRow have never been assigned a value they will never be processed by map. Hence mapping Number.prototype.valueOf over previousRow will result in an empty array of 5 elements:

console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);

However when you apply previousRow to the Array constructor the constructor creates a new array and assigns the values of previousRow to the new array.

It doesn't matter whether the elements of previousRow were assigned a value. When JavaScript can't find a value it supplies undefined instead.

Hence the net effect is that the new array has 5 elements all of which are assigned undefined explicitly by the Array constructor. Hence you can use map to process the entire array:

console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf, 0);
console.log(previousRow);

You should read the following answer for a more in depth explanation: https://stackoverflow.com/a/18949651/783743

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

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.