JavaScript "new Array(n)" and "Array.prototype.map" Weirdness
Last Updated :
29 Aug, 2024
In JavaScript, working with arrays is a fundamental part of manipulating and structuring data. Two commonly used tools in array manipulation are new Array(n)
and Array.prototype.map()
. While these tools are powerful on their own, combining them can sometimes lead to unexpected or "weird" behavior, particularly for developers who are not familiar with how JavaScript handles arrays with uninitialized slots.
These are the following topics that we are going to discuss:
new Array(n)
We use new Array(n) to
create a new array of a specified length n
in JavaScript. This creates an array with a length of 5, but the array contains empty slots where these empty slots are not the same as undefined
or null
. They are uninitialized, and no value exists in them or we can say that the array exists, but nothing is "inside" the slots yet.
Example: This example shows the use of new Array(n) for creation of an array.
JavaScript
let arr = new Array(5);
console.log(arr);
Output[ <5 empty items> ]
Array.prototype.map()
Array.prototype.map()
is a method used to transform each element of an array by applying a callback function to each element. It returns a new array with the results of calling the provided function on every element in the original array.
JavaScript
let arr = [1, 2, 3, 4, 5];
let squared = arr.map(x => x * x);
console.log(squared);
Output[ 1, 4, 9, 16, 25 ]
The "Weirdness" with new Array(n)
and map()
As understood from above we know that map()
method in JavaScript only works on defined array elements. It ignores any empty slots in the array. This is why when we use map ()
on an array created with new Array(n)
, nothing happens — because there are no actual elements to map over.
Example: In this example we create an array with 5 empty slots using new Array (5) but when we try to call map method on this array, nothing happens. The callback function i => i
is not applied because map ()
skips over empty slots and because of this the result is still an array with 5 empty slots, because there were no actual elements in the array for map ()
to iterate over and transform.
JavaScript
let arr = new Array(5);
let mappedArr = arr.map((x, i) => i);
console.log(mappedArr);
Output[ <5 empty items> ]
Solutions to Avoid Weirdness
In order to solve the above weirdness, we can use different methods in JavaScript let us study them in detail.
Fill the Array with Values Using Array.prototype.fill()
We can avoid the above issue by using fill()
method to populate the empty slots with values (e.g., undefined
, null
, or anything else). This will ensure that map()
has actual elements to work with.
JavaScript
let arr = new Array(5).fill(undefined).map((_, index) => index);
// Fills the array with undefined and
// maps over the array to replace the values
console.log(arr);
Use Array.from() to Create Populated Arrays
We can use Array.from() to create an array of the specified length and then apply the mapping function to each element
JavaScript
let arr = Array.from({ length: 5 }, (_, index) => index);
// Creates an array of 5
// elements and maps index values directly
console.log(arr);
Use Spread Operator with Array Keys
We can use spread operator and Array.keys()
to create and initialize arrays
JavaScript
let arr = [...Array(5).keys()];
// Uses Array.keys() to get an iterator
// and spreads the keys into an array
console.log(arr);
Conclusion
Through this article we understood that the issue with new Array(n)
and map()
arises because new Array(n)
creates an array with empty slots, not actual elements. Since map()
only works on existing elements, it ignores these empty slots. To resolve this issue, we can use methods like fill()
, Array.from()
, or other approaches that ensure the array has elements to map over.
Similar Reads
Difference Between Array.prototype.map() and Array.prototype.flatMap() in JavaScript In JavaScript, Array.prototype.map() and Array.prototype.flatMap() are both the methods used to the transform elements in arrays but they differ in their behaviors regarding handling and flattening of the nested arrays.What is Array.prototype.map()?The map() method creates a new array populated with
3 min read
JavaScript Array prototype Constructor The JavaScript array prototype constructor is used to allow to add new methods and properties to the Array() object. If the method is constructed, then it will be available for every array. When constructing a property, All arrays will be given the property, and its value, as default. Syntax: Array.
2 min read
JavaScript - Add Array to Array of Array Here are the different methods to Array to an Array of Array (Multidimensional Array) in JavaScript1. Using push() MethodThe push() method is one of the most common ways to add an array to an array of arrays. It adds a new element (in this case, an array) to the end of the array.JavaScriptlet mat =
4 min read
JavaScript Map.prototype[@@iterator]() Method Map[@@iterator]( ) method is used to make Map iterable. Map[@@iterator]( ) method returns iterator object which iterates over all code points of Map. Map[@@iterator]( ) is built-in property of Map. We can use this method by creating Map iterator. We can make Map iterator by calling the @@iterator pr
2 min read
JavaScript Array map() Method The map() method is an ES5 feature that creates a new array by applying a function to each element of the original array. It skips empty elements and does not modify the original array.JavaScriptconst a = [1, 2, 3, 4]; // Use map to create a new array with elements doubled const b = a.map(x => x
4 min read
Map to Array in JavaScript In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
3 min read
How does JavaScript .prototype work ? In JavaScript when adding behaviour to objects, then if creating multiple objects using the constructor (calling the constructor function with the 'new' keyword) then the new keyword is the one that is converting the function call into constructor call and every time a brand new empty object is crea
4 min read
Implement polyfill for Array.prototype.map() method in JavaScript In this article, we will learn how to implement a polyfill for an Array.prototype.map() method in JavaScript. What is a polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser y
4 min read
JavaScript - Create an Array Containing 1...N Numbers Here are some methods to create an array containing 1...N numbers1. Using for LoopThe for loop iterates from 1 to N, adding each number to the array. JavaScriptfunction create(N) { let a = []; for (let i = 1; i <= N; i++) { a.push(i); } return a; } let n = 12; let a = create(n); console.log(a);Ou
3 min read
JavaScript Array from() Method The Array.from() method is used to create a new array from any iterables like array, objects, and strings.JavaScriptconst a = Array.from("GeeksforGeeks"); console.log(a);Output[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' ] SyntaxArray.from(object, mapFunction, thisValue);Paramet
2 min read