Creating a fresh array in JavaScript

Attempting to create a new array with specified values.

Scenario 1:

var x = new Array(3).map(()=>1);

At this point, x equals [undefined * 3]

Scenario 2:

var x = [...new Array(3)].map(()=>1);

Now x is [1,1,1]

Can anyone provide assistance on why the spread operator yields different results?

Furthermore, what causes Scenario 1 to fail?

Answer №1

In summary: The first array contains holes, while the second one does not. When using .map, it will skip over any holes present in the array.


When you use a spread element, the array is treated as an iterable, meaning you get an iterator to go through each value in the array. This iterator functions like a for loop, iterating from index 0 to array.length - 1. However, since your array has no values at these indices, array[i] will return undefined.

Therefore, [...new Array(3)] results in an array with three instances of undefined rather than just an empty array with length 3.

If you observe this in Chrome, you can see the distinction:

https://i.sstatic.net/kbUqx.png

We refer to arrays with holes as "sparse arrays."

The key point: Several array methods, such as .map, will ignore these holes! They do not treat the hole as simply an undefined value; instead, they disregard it entirely.

You can test this by adding a console.log statement inside the .map callback:

Array(3).map(() => console.log('call me'));
// no output

This explains why your initial example did not produce the expected outcome. The sparse array contained only holes, which were ignored by .map. In contrast, creating a new array with the spread element eliminated the holes, allowing .map to function correctly.

Answer №2

Array

arraySize

When you pass a single argument to the Array constructor and it is an integer between 0 and 232-1 (inclusive), it will create a new JavaScript array with the size set to that number.

new Array(3) doesn't actually populate values in the created array, it simply sets the .length property to 3.

Check out this discussion on Undefined values with new Array() in JavaScript.

You can utilize Array.from() in the first example to get the desired output

var x = Array.from(Array(3)).map(()=>1);

Spread operator

The spread operator allows an expression to be expanded in situations where multiple arguments (for function calls) or elements (for array literals) or variables (for destructuring assignment) are expected.

var x = [...new Array(10)].map(()=>1);

This code creates an array filled with undefined values and sets the .length to 10 from Array(10), making it iterable for .map().

Answer №3

Why is case 1 not functioning as expected?

The map function calls the callback function in each element in ascending order.

In the first scenario (breaking down..),

var y = new Array(3);
y = y.map( () => 1 );

y is an array with uninitialized indexes. Hence, the map function does not know where to start iterating the array from, leading to it not iterating at all ('Not working').

You can test this by (in Chrome),

var y = new Array(5);
// This will display '[undefined x 5]' in chrome, because their indexes are uninitialized

y[1] = undefined;
// '[undefined x 1, undefined, undefined x 3]' Only array[1] that has its index.
// And you can use 'map' function to change its value.

y = y.map( () => 1 );
// '[undefined x 1, 1, undefined x 3]'

What difference does using the spread operator make?

In the second instance,

The spread operator allows parts of an array literal to be initialized from an iterable expression.

Enclose it in square brackets to properly utilize it.

Thus, [...new Array(2)] represents an indexed array of [undefined, undefined].

Since your array in the following example has been indexed. Let's take a look (in Chrome),

var y = [...new Array(2)];
// Now 'y' is an array with indexes [undefined, undefined]

y = y.map( () => 1 );
// Will return [1, 1]

Each value in y now has its own indexes. Consequently, the map function is able to iterate over it and call the callback function for each element in ascending order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leetcode problem 833 deals with replacing strings based on their index positions

Accessing Values by String IndexThis specific query is linked to a prior inquiry. Example 1: Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] Output: eeebffff Explanation: a is found at index 0 in S and is replaced by eee ...

What causes the AngularJS variable to receive a null value following an HTTP request?

Using AngularJS on the frontend, I have a variable named ttest defined before making an $http call. Subsequently, data is assigned to this variable. The value of ttest[0] is available within the $http function but not outside of it. angular.module(&apos ...

After npm installation and running the dev command, an error is displayed in the console, despite the project functioning properly on a different

After successfully installing a reliable project on my personal computer and compiling it without any issues, I encountered an error message in the console. Uncaught ReferenceError: regeneratorRuntime is not defined at eval (index.umd.js?e3f3:5) at eval ( ...

Locate connections between elements within an array

I've been working on a program to input data into an array named numbers, and then utilize nested while loops to check for duplicates within that array. The number of matches found for each element would be stored in the matches array. Although the c ...

What is the best way to incorporate a smooth transition for an object as it appears on the screen in React?

After configuring my code to display a component in the HTML only if a specific hook is set to true, I encountered an issue with a CSS transition. The problem arises because the 'open' class is triggered at the same time the element becomes true, ...

File index with Node.js server for handling files

I currently have a code snippet for setting up a file server that serves files from a static folder named "public1". However, I am facing difficulties in making an HTML page display by default when a user navigates to the IP address in a browser. Although ...

What is the best way to send my string through the email intent?

@OverrideView view){ StringBuffer buffer = new StringBuffer(); buffer.append(textQr = text.getText().toString().trim()); buffer.append(text2Qr = text2.getText().toString().trim()); buffer.append(text3Qr = tex ...

Passing a particular method of a specific instance as an argument

I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance w ...

Having trouble storing information in a leveldb file with a batch operation

I recently delved into learning level.db with the level module in node.js var level = require('level') var db = level('batch.db', { valueEncoding: 'json' }) var batch = [] for (var i = 0; i < 10; i++) { batch.push({ key ...

Guide to transferring a JavaScript/Ajax variable to a PHP webpage with the help of AJAX

function initiateIperfSpeedRequest(speedVar, actualIp) { var xmlhttp = getAjaxObject(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { handleIperfResponse(xmlhttp.respo ...

Methods for applying a style property to a div element with JavaScriptExecutor in Selenium utilizing C#

I have been attempting to change the style of a div element using JavascriptExecutor in C#, but so far, nothing has happened. IJavaScriptExecutor js = (IJavaScriptExecutor)driver; IWebElement element = driver.FindElement(By.XPath("//div[contains(@class, ...

Is there a way to invoke a JavaScript function specifically for a given link?

I am trying to make the JavaScript only apply to a specific A LINK (#tornado,_bar -> ul -> li -> a links) when clicked, but it is applying to all A links. How can I specify the particular link in the JS? The JavaScript code is not functioning cor ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

:onchange event triggering iteration through a function

My Vue.js application is experiencing issues with infinite post requests when a selectbox value changes. I have a table component that needs to display students from different 'tutorgroups'. Each tutorgroup, like '4M07a', has its own se ...

What is the best way to conceal a Boostrap Navbar using jQuery?

Attempting to create a hidden side navbar using Jquery and Bootstrap 4. Struggling with the .on('click', ...) event handler for a button not hiding the sidebar as expected despite all files loading correctly according to the developer tools. Atte ...

Secure your accounts with our innovative password manager tool that allows you to easily create, manage

Is there a way to show text in dots format using HTML, similar to how it appears in a password field, like this: Password: <input type="password" name="pwd">This text looks like dots</input> Without relying on an <input>? I'm inter ...

Is it possible to initiate an animation in a child component using an input variable?

I have a specific animation that I would like to trigger once an *ngFor loop completes ngAfterViewInit(): void { this.items.changes.subscribe(() =>{ Promise.resolve().then(() => { this.everythingLoaded(); }) }) } After the loop fini ...

Issues with React Native: Struggling to iterate through an array and show it with an image URL stored

Just diving into React and I'm facing a challenge with my code. I have an array stored in my .state that I want to loop through and display the images. (I'm using 'Image' and a Card object from https://github.com/lhandel/react-native-ca ...

Leveraging backstretch.js in combination with blur.js (or equivalent)

Query Update I provided a response to the query below, however, I am experiencing some lag and a noticeable stepped transition between images. Can anyone offer advice on how to optimize this issue? Perhaps it would be better to go back to using a static ...

Please add a new row following the date that falls on a Sunday using Google Apps Script

I have a dataset in my google sheets where one of the columns contains various dates. My objective is to add an empty row under every date that falls on a Sunday (regardless of the year). I am only concerned with identifying the day of the week. I have co ...