function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Benjamin BogartBenjamin Bogart 

why: var newExpense = JSON.parse(JSON.stringify(expense)); ?

In the Lightning Components Basics -> Input Data Using Forms module the controller that looks like this:
({
    createExpense: function(component, expense) {
        var theExpenses = component.get("v.expenses");
 
        // Copy the expense to a new object
        // THIS IS A DISGUSTING, TEMPORARY HACK
        var newExpense = JSON.parse(JSON.stringify(expense));
 
        theExpenses.push(newExpense);
        component.set("v.expenses", theExpenses);
    }
})

And this comment later on in the text:
The “disgusting hack” works around a similar issue with references. To see the issue, change the line to remove the two JSON calls, and test the app. You’ll see what the problem is quickly enough. We’ll remove it in the next unit, and so won’t explain further.

It seems to me the purpose of this is to create a copy of the expense object, rather than treating it as a reference.  Am I right? Also, why?  The text says I'll see the problem quicky enough but I don't.  I removed the stringafy and parse and the code still seems to work just fine.

Just trying to understand.  Thanks.
Benjamin DoctorsBenjamin Doctors
5 years later I have the same question...