What is the best way to save an object in a temporary variable?

  RPGDATA = {
    turkey: 'Leg',
    chicken: 'Muffin'
}
var tempdata = RPGDATA;

    RPGDATA.turkey = 'NoLeg';

console.log(tempdata); // I'm seeing 'NoLeg' here, but shouldn't it be 'Leg'?

console.log(RPGDATA);

Check out this code on jsfiddle: http://jsfiddle.net/njxd7eLy/1/

Why is tempdata showing the updated object instead of the original data?

Update: Here's an example for clarification: http://jsfiddle.net/zLeufxfm/ The old data is stored in tempdata, but not as a separate object.

Answer №1

In JavaScript, objects are passed by reference, so if you want to modify each object independently, you must clone the object.

One way to accomplish this is by using the JSON object.

Click here to view an example.

var myObj = {
  name: 'bob',
  age: '42'
};

var copy = JSON.parse(JSON.stringify(myObj));

myObj.newProp = 'Hello';

copy.otherProp = 'Yo';

console.log(copy, myObj);

For further reading:

JSON Object documentation

Guide to working with objects in JavaScript

Answer №2

The result will show "NoLeg" as per Oka's explanation that objects in JavaScript are passed by reference.

The provided diagram is simple to comprehend and aids in grasping how values are transmitted in JavaScript:

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

Risks associated with the use of Base64 encoded URLs in relation to security

When accessing my API from a web application, I'm using ajax to send get and post requests. Since I'm new to this, I'm curious about the security implications related to the content type being used. Currently, I know of two content types t ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

Handling multiple post requests for the same route in Node.js

I am in the process of creating a Node JS application utilizing Express JS and MongoDb. Within my index.hjs file (which uses hogan), I have integrated both a login and password recovery feature. Currently, both forms have the action set to "/" and the meth ...

Setting up Supertest and Express together is leading to a timeout error

In my server.test.js file, I have a straightforward setup: import 'regenerator-runtime/runtime'; const request = require('supertest'); const express = require("express") const app = express(); app.get('/user', func ...

Documentation in TypeScript with JSDoc and using the new Rest type syntax

Encountering an issue while integrating TypeScript into a large existing React/Redux application. To test things out, I decided to convert one of my React files to a .ts file. My approach involves using JSDoc to add types to the imported JS files in order ...

Beware, search for DomNode!

I attempted to create a select menu using material-ui and React const SelectLevelButton = forwardRef((props, ref) => { const [stateLevel, setStateLevel] = useState({ level: "Easy" }); const [stateMenu, setStateMenu] = useState({ isOpen ...

Switch from Index.html to Index.html#section1

Currently, I am working on a website and sending someone a draft for review. However, the Home screen is designed as a 'a href' link with "#home". The issue arises when the website opens from my computer; it goes to ...../Index.html instead of .. ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

Terminate the JWT token and automatically log out the user in the event of a banning or modification

Greetings fellow developers, I've been working on enhancing my application's user system to include functionality for administrators to upgrade an account's level (granting admin privileges if it reaches level 10) or ban users from the site ...

Struggling to transfer data into MySQL database with AJAX and PHP

I am attempting to store user-input text from an input field into a MySQL database using Ajax and PHP. The concept is to input the text, click 'display', and then retrieve it from the database to display on the page. Here's a snippet of the ...

Retrieving data from a div container on an active website

Imagine having a website similar to , where you want to automatically retrieve the time value every second and save it in a .txt file. Initially, I considered using OCR (optical character recognition) software for this task, but soon realized that relying ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

AssertionError: 'assertEquals' is not recognized in compiled WebDriverJS

I'm facing an issue with the webDriverJS library. After downloading the project and building the js file "webdriver.js" following instructions from the wiki and this post on Selenium WebDriverJS Using in Browser, I am unable to use the function "asse ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

Make sure to switch up the font color with each new use of the "append" function

Currently, on my page, I am using the append function to add a new line of text (".newText") every 5 seconds. This is my current implementation: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yello ...

Transfer PDF file to user's web browser through XMLHttpRequest, utilizing up-to-date HTML5 techniques, all while maintaining the integrity of the document's encoding

I am trying to achieve a similar result as described in this StackOverflow post about handling file download from ajax post. However, I'm working with a dynamically-generated PDF file created using PHP v5.6.10 (with the PDFLib extension, v9.0.5). Unf ...

What is the best way to incorporate global variables within Vue JS components?

I am currently working on creating a web-app using Vue JS. I have come across the concept of Single File components(.vue files) which seems like a great way to create components. However, I am looking to avoid using any node modules. That's when I dis ...

jQuery enigma - struggling to get slideUp/slideDown to function

My goal is to utilize jQuery and CSS to display the initial paragraph out of a set of four, and insert a link or button at the conclusion of the first paragraph. Upon clicking on the link or button, my aim is to reveal the remaining three paragraphs in a s ...

AngularJS Formly's ui-mask feature: Stripping input mask characters from the model

I recently implemented an input mask on a 10-digit phone number field within my Formly form using AngularJS. The input is masked with dashes (xxx-xxx-xxxx) and displays correctly on the page. However, the issue arises when attempting to ignore these mask c ...

Tips on invoking a JSP and Servlet from JavaScript by passing in a parameter

Check out the code below for calling JavaScript functions: <td><input type="button" name="edit" value="Edit" onclick="editRecord(<%=rs.getString(1)%>);" ></td> <td><input type="button" name="delete" value="Delete" onclic ...