JS Tips for using the .push() function with Multidimensional Arrays in JavaScript

After coming across this code example online, I decided to give it a try. The code snippet involved using the JavaScript array push method to add new elements to an inner sub-array, which was exactly what I needed to achieve!

The code successfully demonstrated adding two new elements to the inner sub-array.

However, when I attempted to replicate the process myself, I encountered some unexpected results:

let mainArr = [];

console.log("mainArr: ", mainArr);
// Expected outcome: created an empty array

let emptyArr = [];

console.log("emptyArr: ", emptyArr);
// Expected outcome: created an empty array

for (i = 0; i < 3; i++) {

  mainArr.push(emptyArr);
}

console.log("mainArr: ", mainArr);
// Expected outcome: pushed "emptyArr" into "mainArr" three times

let newArr = [["X"], [90]];

  mainArr[0].push(newArr);
  
console.log("mainArr[0]: ", mainArr[0]);
console.log("mainArr[1]: ", mainArr[1]);
console.log("mainArr[2]: ", mainArr[2]);
// Unexpected outcome: "newArr" got pushed into each of the three arrays within "mainArr"!
// How can I resolve this issue?

If anyone has any tips or suggestions, I would greatly appreciate it :)

Thank you!

Answer №1

Arrays in JavaScript behave as objects, which are considered non-primitive variable types.

Detailed Explanation

JavaScript has 5 data types that are passed by value: Boolean, String, Number, null, and undefined, known as primitive types.

Additionally, there are 3 data types that are passed by reference: Array, Function, and Object, all of which are technically Objects.

When assigning a non-primitive value to a variable, what actually happens is the assignment of a reference to that value, not the value itself. This reference points to the object's memory location, with variables essentially storing references rather than values.

In Your Scenario

Pushing emptyArr multiple times does not insert new values, but rather inserts references to the same memory location where emptyArr is stored. As a result, any modifications made to mainArr[0] affect all other elements like mainArr[1], mainArr[2] since they all point to the same empty array.

I hope this clarifies things for you.

If needed, more information can be found on Stack Overflow at this link, or through a helpful article on passing by value versus by reference in Java available at this website.

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

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

Using a variable in a Joomla module to create a JavaScript object with PHP

I am currently developing a Joomla module that features a progress bar utilizing the ProgressBar.js plugin. Since this module is designed to load multiple objects on a single page, hardcoding the IDs of these objects is not feasible. To address this, I uti ...

Adjust the navigation text and logo color as you scroll on the page

I am new to HTML and CSS and I am working on a website with PagePiling.js scrolling feature. I want to change the color of my logo image and navigation text dynamically as I scroll to the next section. Specifically, I only want the part of the logo and tex ...

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Applying the jqtransform plugin to all forms except for one

We've implemented the jQuery jqtransform plugin to enhance the appearance of our website's forms. However, there is one particular form that we'd like to exclude from this transformation. I made adjustments to the script that applies jqtrans ...

Determining the installation duration of the React Native screen

Several questions have been asked about this topic, but none of them seem to have a definitive answer. What I am looking to do is calculate the time it takes to navigate to a screen. The timer will start here: navigation.navigate("SomePage") Essentially, ...

Tips for including a new class in an HTML element

My goal is to add a specific class to an HTML tag, if that tag exists. This is the code I have attempted: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>index</title> <style> ...

Error in Angular: Trying to access property 'setLng' of a null component variable

Just starting out with Angular and I've come across the error message Cannot read property 'setLng' of null. Can anyone help explain why this is happening? import { Component, OnInit, Input } from '@angular/core'; @Component({ ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

"Concealing tooltip boxes in Vue: A step-by-step guide

I am trying to achieve a functionality where a tooltip box appears on each incorrect or empty input field when the 'Save' button is pressed. I have been able to display the tooltip boxes upon clicking the 'Save' button, but the issue ar ...

Display and conceal multiple div elements using a timer

Currently, I am working on creating a message box that will display active messages one by one from a MySQL table. The challenge is that the number of divs needed can vary depending on the number of active messages in my database. Using an ajax timer and P ...

Having trouble accessing a JavaScript variable in Javascript due to reading null property 'value'

What I Require I am in need of passing a URL variable from an HTML document to a JavaScript file. HTML Snippet <script> var urlParam = "{{ page_param.asy_request | replace('&','&')}}"; urlParam = urlParam.rep ...

The Full Screen Button on Google Maps isn't functioning properly in a third-party mapping application

Below you will see the '+' icon which is also supposed to function as the full screen button. https://i.stack.imgur.com/IMvHa.png However, when clicked on, it does not expand to full screen as intended. I have attempted using some basic jQuery ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

React-select: issue with maintaining selected option on input

Hello everyone, I am new to React and seeking some assistance in reviewing my code. I have a component called Bucket that contains multiple challenges as separate components. Here is a simplified version of the code: class CLL_Bucket extends Component { ...

Troubleshooting a problem with a personalized webkit scrollbar in Chrome

Using the CSS property scroll-snap-type: y mandatory; to customize my scrollbar with the following styles: ::-webkit-scrollbar { width: 12px; background: transparent; } ::-webkit-scrollbar-track { background-color: rgba(0, 0, 0, 0.5); -webkit-box-s ...

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.</p> I'm looking for ways to disable this troublesome feature of ESl ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...