Ruben Reyes
Ruben Reyes

Reputation: 773

Javascript: how can I preserve reference to object breaks after reassignment?

I struggled with the title to use for this post. So let's dive into code:

var arr = [1,2,3];
var obj = {a: 1, b: 2, c:3};

function func(val) {
  setInterval(function(){
    console.log(val);
  }, 3000);
}

func(arr);
func(obj);

setTimeout(()=>{
    arr[0] = 9;
  obj.a = 9;
}, 3000);

setTimeout(()=>{
    arr = [9,8,7];
  obj = {a: 9, b: 8, c:7};
}, 3000);

JSFiddle: https://jsfiddle.net/lyquix/obxLa3pe/

The reference to arr and obj from the setInterval is preserved while I make changes to the elements/properties, but it "breaks" when I assign a new array/object to arr and obj.

My question is: how can I make an assignment like this, essentially replacing all the data of an object, without breaking the reference? Is there a standard function or notation? Or do I need to "wipe out" the array/object first and then repopulate elements/properties?

Something like:

while(arr.length) {arr.pop();}
for(let key in obj){delete obj[key];}

and then repopulate...

Upvotes: 0

Views: 794

Answers (2)

Kit Isaev
Kit Isaev

Reputation: 700

You can use the box pattern to achieve this.

var box = {
  arr: [1,2,3];
  obj: { a: 1, b: 2, c:3 };
};

function log(thing) {
  setInterval(() => {
    console.log(thing.obj);
  }, 3000);
}

log(box);

box.obj = { a: 9, b: 8, c: 7 };

Will log { a: 9, b: 8, c: 7 } in 3s.

Upvotes: 2

bryan60
bryan60

Reputation: 29335

for the object you can use assign:

Object.assign(obj, {a: 9, b: 8, c:7});

this will overwrite the properties in the existing object. but if obj had some property d, that would remain untouched.

for the array, you can use splice:

arr.splice(0, arr.length, ...[9,8,7])

Upvotes: 0

Related Questions