JavaScript concatenation of arrays

I am working with two arrays:

    let num1 = [[1]];
    const num2 = [2, [3]];

When I combine these arrays, I create a new array:

    const numbers = num1.concat(num2);
    console.log(numbers);
    // This will result in [[1], 2, [3]]

Next, I add a new value to num1:

    num1[0].push(4);
    console.log(numbers);
    // This will result in [[1, 4], 2, [3]]

However, if I try to reassign a value to num1 like this:

    num1[0] = [1, 4, 5];
    console.log(numbers);
    // This will result in [[1], 2, [3]]

I am puzzled as to why changing the value of num1 does not update the numbers array, while the push method does.

Answer №1

The first element of num1 initially points to an array containing [1]

numbers also references the same array, creating a duplicate reference.

When num1[0].push(4); is executed, it alters the array that both references point to.

However, by setting num1[0] = [1, 4, 5];, the value of num1[0] is changed to a completely new array, while numbers maintains its connection to the original array.

Answer №2

In the world of Javascript, arrays are classified as objects. This means that arrays in Javascript are always treated as references. So, if you push one array into another, you're essentially pushing a reference and not the actual value.

However, when you merge two arrays together, the values (or references) are copied into a brand new array.

Furthermore, when you modify the value at index 0, you're essentially replacing that reference. Nevertheless, the previous reference remains intact in the merged array.

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

Using jQuery to remove the last two characters from a specified class

I have a simple task at hand. I am trying to use the slice method in JavaScript to remove the last two characters from a string that is generated dynamically within a shopping cart. Instead of displaying a product as $28.00, I want it to display as $28. S ...

Unusual actions from the jQuery Steps extension

I am currently utilizing the jQuery Steps plugin (FIND IT HERE). The issue I'm facing lies within an IF statement that is causing the wizard to return to the first step instead of staying on the current indexed step. While all other IF statements are ...

Displaying a Div element containing dynamically calculated values based on selected options in Angular

As a newcomer to Angular, I decided to challenge myself by building a simple app. Currently, my select options only display the keys of a data object. What I really want to achieve is to show a value beneath the second select box for each team, which displ ...

Configuring JSON in PHP and JavaScript

Although I have already asked this question before, I am experiencing some issues in my code. I know that utilizing JSON is necessary and after researching multiple sources, I grasp the concept but somehow am unable to implement it correctly. Here is my co ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Dynamically add a CSS class to the <head> tag in real

Within this function, my goal has been to dynamically append gradClass in order to apply a gradient background to a div. function applyGradient(upto) { var gradStyle = "background: -webkit-linear-gradient(left, #ff1a00 20%,#ffffff 30%);" ...

Modifying the Ext.js TreePanel checkbox component

I've implemented a basic tree panel checkbox example using Ext.js as shown below: Ext.onReady(function(){ var tree = new Ext.tree.TreePanel({ renderTo:'tree-div', title: 'My Task List', height: 300, ...

React Native's fetch function appears to be non-responsive

I am experiencing an issue where the fetch function does not seem to fire in my React Native component: import { Button } from 'react-native'; export function Test() { function submit() { console.log('submit'); fetch('h ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

Enhancing user input with multiple values in a textarea using JSTL

I'm having trouble inputting multiple values into a textarea using JSTL. Here is the coding snippet I am using: <label>Resources</label> : <c:forEach items="${MEETING_ENTITY}" var="resource"> <textarea id ...

What is the most streamlined way to send data from HTML forms using solely JavaScript?

I currently employ jQuery to transmit data from my HTML forms and then I utilize PHP to save it in my database. Below is the code snippet that I am using: HTML FORM: <form id="formpost" action="" method="post" onsubmit="return false"> <input t ...

Determine the absence of values in a randomly generated array and identify the quantity of missing values

My current challenge involves solving CodeSignal projects, and I recently encountered a problem where a random array of numbers is given, requiring me to determine how many additional numbers are needed to make the array consecutive. For instance, if the ...

Clear out all current cookies

I utilized the following JavaScript code to generate a pop-up window on the website that would only appear once. However, my client now wants to launch a new promotion and I am attempting to remove existing cookies so that the pop-up window displays again ...

Step-by-step guide on concealing elements and subsequently displaying them upon clicking the containing DIV

It's a bit tricky to explain without visuals, so I suggest checking out the JSFiddle link provided. Essentially, when a specific div is clicked, it should expand to reveal some inputs and buttons. However, the issue I'm facing is that upon loadin ...

Unable to store multiple users in MongoDB

Currently, I am encountering an issue with passportJS not saving more than one user to MongoDB while using nodeJS with the expressJS server framework. Initially, I successfully set up email registration with passport-local. However, when I added passport- ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...

What is the best way to position a semi-circular donut graph in the center?

I am attempting to showcase a doughnut or semi-circle chart within a materialize card, which is a responsive div element. My goal is to present simple data and utilize the chart as a progress bar. I took inspiration from the example provided in the HighCh ...

I am looking to implement a straightforward drag-and-drop feature using jQuery

Is it possible to drag and select 4 buttons in a browser, similar to how you would do on Windows, using jQuery locally? ...

Animating Sliding Images with jQuery in a Sleek Sliding Page

Just completed a 5-page sliding site, each page featuring an image slider. Utilizing an image slider within a page slider. However, when attempting to use the same image slider with different images for page slide 3, it's not functioning. Any assista ...