0

Here is my following code block. I am passing my val object from function test1 to test2 and modify its value in test2 and send it back.

var Promise = require("bluebird");
var list = [1,2,3];

var test1 = function(test) {
    return new Promise(function(resolve,reject) {
        var val = {"name" : "my_name","age" : 25};
        for (var item in list) {
            (function (item) {
                console.log("val",val);
                test2(val)
                    .then(function(test2Response) {
                        console.log("test2Response",test2Response)
                    });
            })(item)
        }
    });
};


var test2 = function(val1) {
    return new Promise(function(resolve,reject) {
        console.log("val1",val1)
        val1.name = val1.name + "_1"
        resolve(val1)
    })
}


test1()

And here is my value of my variables valand val1 at various stages.

val { name: 'my_name', age: 25 }
val1 { name: 'my_name', age: 25 }


val { name: 'my_name_1', age: 25 }
val1 { name: 'my_name_1', age: 25 }


val { name: 'my_name_1_1', age: 25 }
val1 { name: 'my_name_1_1', age: 25 }


test2Response { name: 'my_name_1_1_1', age: 25 }
test2Response { name: 'my_name_1_1_1', age: 25 }
test2Response { name: 'my_name_1_1_1', age: 25 }

I couldnt understand why the value of val changes for every iteration even though I update only val1 not val. How can I maintain the val intact and modify only 'val1`?

Vivek Srinivasan
  • 2,687
  • 3
  • 17
  • 17

1 Answers1

0

When you pass val to test2 as val1 it is still the same reference in memory. You would need to clone the value before passing to test2 which can easily be done by doing like this before calling test2:

var copyOfVal = Object.assign({}, val) // this just creates a new object using the same contents of val but different references in memory. 

then pass copyOfVal into test2 and you will get separate results.

YakovL
  • 7,557
  • 12
  • 62
  • 102
finalfreq
  • 6,830
  • 2
  • 27
  • 28
  • woa! btw this is ES6 – Plato Sep 08 '16 at 16:14
  • PS [this answer](http://stackoverflow.com/a/34283281/1380669) mentions that this approach does not "deep clone", although i don't know exactly what that means :) – Plato Sep 08 '16 at 16:22
  • 1
    `_.clone` is also only shallow clone, all that means is if you have an object with nested objects, the nested objects wont be cloned and actually have the same reference as the initial object. Meaning if you change one of the nested properties it will change on both the original and the copy. Lodash does have a `_.cloneDeep(obj)` that does recursively clone if you an object that fits that pattern. – finalfreq Sep 08 '16 at 18:13