Assign value not reference in javascript

35,106

You can use Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);
Share:
35,106
Mubashar Abbas
Author by

Mubashar Abbas

I have over 5 years of experience in building web applications. I have completed multiple projects successfully, of various sizes, while working in teams and some while working individually. I have worked mostly in PHP, and more specifically the Laravel framework. I am also fluent with building mobile applications in Ionic framework. I have also had to build some components of an application in Java Spring framework. I also keep on learning new skills, I subscribe to Laracasts, and have taken courses from some well known authors about new trends and make a habit of spending some time to learn something new every day. I have gotten pretty good at Ruby on Rails framework, JAVA Spring framework, TDD, Ionic and frontend frameworks React, AngularJS, VueJS by sticking to this habit.

Updated on July 09, 2022

Comments

  • Mubashar Abbas
    Mubashar Abbas almost 2 years

    I am having a little problem assigning objects in javascript.

    take a look at this sample code that reproduces my problem.

    var fruit = {
       name: "Apple"
    };
    
    var vegetable = fruit;
    vegetable.name = "potatoe";
    console.log(fruit);
    

    it logs

    Object {name: "potatoe"}
    

    How can I assign the value not the reference of an object to another object?

  • Liam
    Liam over 7 years
    Note, this doesn't assign the value (as the OP wants) but copies it into a new object. Subtle but sometimes important distinction
  • Mubashar Abbas
    Mubashar Abbas over 7 years
    can you please explain a little this assign call? what is that empty object in the first argument?
  • Liam
    Liam over 7 years
    @MubasharAbbas See here
  • Rafael Andrs Cspedes Basterio
    Rafael Andrs Cspedes Basterio over 6 years
    Object.assign({}, obj); you can see more in: developer.mozilla.org/es/docs/Web/JavaScript/Referencia/…