Kousha
Kousha

Reputation: 36249

Javascript pass by reference to be overwritten in another file at a later date

Here is a dummy example:

const obj = {foo: '123'};

function logObj(obj) {
    setInterval(function() {
        console.log(obj);
    }, 100)
}

function overWrite(obj) {
    setTimeout(function(){
        console.log('overwriting')
        obj = {foo: 'bar'}
    }, 1000);
}

logObj(obj)
overWrite(obj)

I'm expecting to see { foo: '123' } every 100ms until overwriting is called and then to see { foo: 'bar' }. However the object is never over-written and I always see 123.

EDIT

I do not want to change just one of the keys; I do in fact want to replace the entire object, so doing obj.foo = 'bar' is not a solution

Upvotes: 0

Views: 171

Answers (3)

3limin4t0r
3limin4t0r

Reputation: 21130

To get a better understanding of what's happening let's rename the variables.

const a = { foo: '123' };

function logObj(b) {
  setInterval(function () {
    console.log(b);
  }, 1000);
}

function overWrite(c) {
  setTimeout(function () {
    console.log('overwriting');
    c = { foo: 'bar' };
  }, 5000);
}

logObj(a);
overWrite(a);

Variables passed to a function are copies of the primary value.

First you call logObj with a copy of the value of a (a reference to object { foo: '123' }). This reference will be available as b in the function.

Then you call overWrite with a copy of the value of a (a reference to object { foo: '123' }). This reference will be available as c in the function. In the callback you replace the contents of c with a new reference. However this does not effect the contents of a or b and is only available during the function body.

Here is an simplified example:

variable diagram

Upvotes: 2

Kodiak
Kodiak

Reputation: 542

The solution is simple, change your const obj to var obj = {...}.

As you can see in this article there's a difference when declaring variables with var, const or let.

const cannot be updated or re-declared

Upvotes: -1

brk
brk

Reputation: 50326

Instead of obj = {foo: 'bar'} do obj.foo= 'bar'

const obj = {
  foo: '123'
};

function logObj(obj) {
  setInterval(function() {
    console.log(obj);
  }, 100)
}

function overWrite(obj) {
  setTimeout(function() {
    console.log('overwriting')
    obj.foo = 'bar'
  }, 1000);
}

logObj(obj)
overWrite(obj)

Upvotes: 2

Related Questions