working with variables in javascript

let elements = new Array("apple", "banana", "orange");
let elementsRef = elements;
elements.push("grape");
console.debug(elementsRef);
console.debug(elements);

I find it confusing how elements and elementsRef are considered the same even after adding "grape" to elements while referencing elementsRef. Shouldn't elementsRef only have ("apple", "banana", "orange")?

If elementsRef continuously points to elements, why do we bother with an argument like elements = elementsRef? I'm still unable to grasp the concept. Can someone explain how this works and why JavaScript allows variables to reference each other indefinitely?

Answer №1

When working with Javascript, it's important to remember that assignments of Objects and Arrays are done by reference, not by value/copy. This explains the behavior you have observed. There are numerous online resources that provide further information on this concept.

If your objective is to create a copy of an array, you can achieve this by using the following code:

var copiedArray = originalArray.slice(0);

Answer №2

When looking at this scenario, we see that itemsRef does not simply refer to items directly, but rather to the specific object (array) that items reference is directed towards. In simpler terms, both items and itemsRef are pointing to the same object, as opposed to each other.

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

Dynamic parameters in the Vue router

Struggling to find the right syntax for passing dynamic param data. Experimented with multiple approaches, but I thought I could pass someValue like this: <router-link :to="{ name: 'Foo', params:{ bar: ${someValue} } }"> Unfortunately, co ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

The search feature on mobile devices is currently malfunctioning

The jQuery code below is used to search for products. It works perfectly in desktop view, but the responsive mobile view does not seem to be functioning correctly. Can someone assist me with fixing this issue? $("#search-criteria").keyup(function() { ...

Is the 404 error a result of the ajax code?

I'm currently working on a form that utilizes AJAX to validate and interconnect various form elements. Below is a simplified version of my code: <?php if( isset( $_POST['create_transaction'] ) ) { // do something } ?> <div> ...

The curious case of looping and peculiar Vue actions

I've been working on a project where I am looking to dynamically add more input fields upon clicking a button. My initial attempt using jQuery.append ran into issues with detecting v-model. Switching gears, I decided to try achieving the same outcom ...

Tips on showcasing a set number of elements from an array in React

How can I modify my code to display only a specific number of items from the 'portfolioComponents' array, starting at a designated index ('startArrayHere') and incrementing or decrementing that index based on user interaction? I've ...

The behavior of Date's constructor differs when applied to trimmed versus untrimmed strings

Although it's commonly advised against creating a date from a string, I stumbled upon an interesting phenomenon: adding a space before or after the date string can impact the resulting date value. console.log([ new Date('2019-03'), ...

Manipulating an Array of Objects based on conditions in Angular 8

I have received an array of objects from an API response and I need to create a function that manipulates the data by enabling or disabling a flag based on certain conditions. API Response const data = [ { "subfamily": "Hair ...

The Joomla jCE popup feature is not functioning properly when used with AJAX content

Currently, I am using Joomla for my project. One of the features I have implemented is Ajax to display a specific section on a page. Within this Ajax-loaded section, there is a JCE popup link included in the code: <a href="some link" class="jcepopup no ...

Dealing with Axios in Express: "Error - Request unsuccessful with error code 404"

As a novice developer, I'm currently delving into the world of routers and controllers using Express, Express Router, and Axios. In my server file (app.js): var createError = require('http-errors'); var express = require('express' ...

What methods with JavaScript, Ajax, or jQuery can I apply to populate the student details?

For completing the StudentID section, please fill out the form data.cfm with the first name, last name, and Middle Name. <script language="Javascript"> $(function() { $( '#effective_date' ).datepicker(); jQuery.validator.addMetho ...

Error: Attempted to save data with mongoose but encountered an Uncaught ReferenceError; `amadeus` is not defined at line 16,

When attempting to store data in mongoDB using mongoose, an error was encountered. The code snippet from index.js is as follows: const mongoose = require('mongoose') mongoose.connect('mongodb://127.0.0.1:27017/myapp') .then(() => ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Is there a way to associate a click event with an angular2 template interpolation?

Can a click event be bound to an interpolation? Whenever I try to run the code below, I encounter the following ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at col ...

Retrieve object containing all identical fields except for one specific field

Looking for help with filtering a JavaScript object [ { "comparing_result": "d_sens", "event": "Require", "master_field": "type_de_donnees", "master_field_ ...

Cover the whole page in darkness and emphasize the division element

I attempted to implement a solution I found on stackoverflow without success. The issue is that the blackout feature does not seem to activate - nothing happens. Within my JavaScript code (all enclosed in the $(document).ready(function () tag), it appears ...

Managing an array based on its individual elements

const grid = { squares: Array(20).fill(null) } Within my grid object, I have an array called squares which fills with values when a square is clicked. I am trying to check if all elements in the array are not null. const squaresCopy = grid.square ...

Anchor tags are not visible to Jquery

My issue is with integrating JQUERY and PHP. In my external PHP file, I have the following echo statement - `echo ("<a href='#' id='bb'>hello</a>"); Similarly, in my external js file, I have this JQUERY code - $(' ...

Is Ajax capable of producing multiple outputs at once?

I am looking to retrieve data from a product.json file that contains two objects: (1) object for CCTV camera products (2) object for Laptop products. When a specific button is clicked, I want to access the data for LAPTOP products and the same for CCTV. ...