2
let obj = { apple: 12, mango: 13 };
basket = obj;
basket.apple = 45;
basket.banana = 15;
console.log(obj);

output:

{ apple: 45, mango: 13, banana: 15 }

I am not updating "obj", how's its value get updated?

But in case of numbers and string when we update a variable it will not update another variable which we copies the value from.

var a = 45;
var b = a;
b = 99;

console.log(a,b) //45, 99

  • 1
    You are assigning the reference of `obj` to `basket`. So `basket` and `obj` are pointing to the same object. You can check as `console.log(basket === obj)` which returns `true` – DecPK May 17 '21 at 09:57
  • Does this answer your question? [Duplicate object in javascript](https://stackoverflow.com/questions/13287297/duplicate-object-in-javascript) – evolutionxbox May 17 '21 at 10:00

4 Answers4

1

Problem

value type reference type object in javascript

Solution

You can use Spread ... operator to clone a new object instead of keeping the reference.

let obj = { apple: 12, mango: 13 };

const basket = {...obj}; // Clone new object
basket.apple = 45;
basket.banana = 15;

console.log({obj, basket});
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

Objects hold references to the actual values they represent, or rather, objects points to a memory location where the values they represent are stored. So when you assign an object to another object say basket = obj you simply made basket to point to the same memory location as obj, hence when you change basket, you are changing the value at the location where both basket and obj points to.

Chibuzo
  • 6,112
  • 3
  • 29
  • 51
0

Brother as per rules object store the reference while primitive values doesn't.

let obj = { apple: 12, mango: 13 };
basket = obj;
basket.apple = 45;
basket.banana = 15;
console.log(obj);

so according to above code the basket is getting the reference of obj object so when you will change on basket basket will update referenced value that's why your obj also changes. You can check this code for your solution

const obj = { apple: 12, mango: 13 };
    const basket = {...obj};
    basket.apple = 45;
    basket.banana = 15;
    console.log(obj);
Saleh Majeed
  • 19
  • 1
  • 4
0

you are giving the reference of the obj to basket
so both (obj, basket) pointing to same object location

you can check this by
console.log(obj == basket) // true

In order to clone the object, you can use Object.assign

basket = Object.assign({}, obj);
console.log(obj == basket) // false