According to MDN Array.prototype.map
maps the calls of the provided callback function once for each element to an array, in order, and builds a new array from the results. Call back only for indexes of the array which have assigned values , including undefined. It is not called missing array elements (that is, indexes that have never been set, that have been deleted, or that have never been assigned a value).
Both arrays differ in how Array.map performs the callback. Since there are no indexes in the second scenario, map returns empty
CAUSE
The answer lies in the Array constructor
In the first scenario, you pass an array with a length of 5 to the Array constructor, which will be index the array based on the length , but in the second scenario, you just use an array of length 5
You will know the difference when starting Object.keys(initialArray) with Object.keys(normalArray)
Try checking the example below.
function helloMap(value, index) { return "Hello " + index; } console.clear(); var initialArray = Array.apply(null, new Array(5)); console.log("Array initialised with apply:"); console.log(initialArray); console.log(initialArray.map(helloMap)); var normalArray = new Array(5); console.log("Array constructed normally"); console.log(normalArray); console.log(normalArray.map(helloMap));
.as-console-wrapper { max-height: 100% !important; }
source share