What causes the object to be updated with new values when I update reference variables in JavaScript?

Imagine having an object named x with values x = { a: 'abc', b: 'jkl' },

Next, I am assigning this object x to a new local variable y using var y = x.

Now, when the value of var y changes as y.a = 'pqr', y.b = 'xyz', the object var x is automatically updated with the new values { a: 'pqr', b: 'xyz' } from var y.

While this behavior is often desirable, there are cases where it needs to be prevented. How can this be achieved?

You can access the Plunker code for this here

Answer №1

To prevent the issue, you have two options:

Option 1 - Using Object.assign:

var x = { a: 'abc', b: 'jkl' }
var y = Object.assign({}, x);
y.a = 'modified';
console.log('x: ', x);
console.log('y: ', y);

Option 2 - Using the Spread operator:

var x = { a: 'abc', b: 'jkl' }
var y = { ...x };
y.a = 'modified';
console.log('x: ', x);
console.log('y: ', y);

Answer №2

In this particular situation, a new object is assigned to y while x remains unchanged.

If you were to modify some properties of either x or y, both references would point to the same updated object.

var x = { a: 'abc', b: 'jkl' };
    y = x;

y = { a: 'pqr', b: 'xyz' };

console.log(x);
console.log(y);

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

The promise of a MongoDB connection with Node.js returns as 'awaiting fulfillment'

Greetings to all! A few weeks ago, I embarked on the journey of learning javascript, node.js and mongo. As a beginner, I have an interesting task at hand today. My goal is to add a simple document to the mongoDB and perform a conditional check. So here&apo ...

An issue arises when ng-pattern fails to recognize a regular expression

My form includes inline validation for a specific input field. <form name="coForm" novalidate> <div> <label>Transaction: </label> <input type="text" name="transaction" class="form-control" placeholder="<Dir ...

Switch between playing and pausing the mp3 audio in the Next application by using the toggle

I am currently working on my website and I have been trying to add a button to the bottom of the page that can play or pause a song using useSound library. The song starts playing when I click it for the first time, however, I am facing difficulty in stopp ...

Is it necessary to compile Jade templates only once?

I'm new to exploring jade in conjunction with express.js and I'm on a quest to fully understand jade. Here's my query: Express mentions caching jade in production - but how exactly does this process unfold? Given that the output is continge ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Verify if function is returning sessionStorage using jest

Recently, I've been working on creating a jest test for the function below that sets a sessionStorage entry: /** * @desc create authenticated user session * @param {String} [email=''] * @param {Date} [expires=Date.now()] * @param {St ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

Different ways to split up information on the client side into separate "pages"

Looking for a way to split a lengthy HTML text-only article into multiple divs for easier page navigation on mobile devices? Perhaps dividing it into separate pages that users can swipe through on their iPad or iPhone? I've experimented with JavaScri ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

Each time my classes are initialized, their components undergo reinitialization

Apologies if the question is not well-formed, I am completely new to working with React. I have been attempting to create a dashboard but encountering issues with my states getting reinitialized. Below is the content of my app.js file. import './inde ...

Is there a way to make Express.js pass parameters with special characters exactly as they are?

I am currently working on a project within the freeCodeCamp "API and Microservices" curriculum that involves using Express.js to handle routes. The project itself is relatively straightforward, with some pre-defined routes and others that need to be creat ...

Error: The build process for Next.js using the command `npm run build`

Currently attempting to construct my application with target: 'serverless' set in the next.config.js file (in order to deploy on AWS Lambda). Upon running npm run build, I am encountering the following output: Warning: Built-in CSS support is bei ...

Encountering net::ERR_CONNECTION_RESET and experiencing issues with fetching data when attempting to send a post request

I am facing a React.js task that involves sending a POST request to the server. I need to trigger this POST request when a user clicks on the submit button. However, I keep encountering two specific errors: App.js:19 POST http://localhost:3001/ net::ERR_CO ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

A collection of items that mysteriously affix themselves to the top of the page as

Unique Context In my webpage, I have a specific div element with the CSS property of overflow: auto. Within this scrolling div, there is structured content like this: <h3>Group A</h3> <ul> <li>Item 1</li> <li>I ...

Locating the Active Object's Coordinates in fabric.js

When using fabric js, I have successfully drawn various shapes like circles and rectangles. However, I encountered an issue while trying to obtain the coordinates of the rectangle using the fabric.rect() method. canvas.getActiveObject().get('points& ...

Transforming a React Class Component into a React Functional Component

After struggling for a day with multiple failed attempts, I have been unsuccessful in converting a React Class Component. The original class component code is as follows: class NeonCursor extends React.Component { constructor(props) { super(props); ...

What steps should I take to display a Material UI grid in React without triggering the warning about the missing unique key

In my current project, I am utilizing React and Material UI to display a grid. The grid's rows are populated from an array of data, with each row containing specific information in columns structured like this: <Grid container> {myData.map((re ...