0

I'm a newbie to js. Let me illustrate my question with a few examples.

Code 1

var temp = { key: "value" };
var data = ["v1", "v2"];
var result = [];
for (var i in data) {
    var newdata = temp; /** Note here! **/
    newdata.key = data[i];
    result.push(newdata);
}
console.log(result);
// [ { key: 'v2' }, { key: 'v2' } ]

The result here is unexpected.

Code 2

var temp = { key: "value" };
var data = ["v1", "v2"];
var result = [];
for (var i in data) {
    var newdata = { key: "value" }; /* Note here! */
    newdata.key = data[i];
    result.push(newdata);
}
console.log(result);
// [ { key: 'v1' }, { key: 'v2' } ]

Now the result is what I want.

It looks like the name binding operation in Python. But I googled a lot and could not get a satisfied answer. So I have to turn to stackoverflow for help.

My question:

Does JS have a name binding operation similar with Python? If not, why do these two piece of codes get different results?

[Edit]

I know about reference in C++, and name binding in Python. And I'm also aware of the differences between these two.

The only thing I was confused with was: In JS, is it reference or name binding? Or something else?

Thanks to all the comments, I totally understand it's similar with name binding rather than reference. (As I can't find any button to closed this question, I add the answer here.)

Community
  • 1
  • 1
JavaNoScript
  • 2,345
  • 21
  • 27
  • 4
    Objects are passed by reference. That is all. – Niet the Dark Absol Dec 06 '16 at 17:50
  • 2
    FWIW: JavaScript and Python variables work *identically* in this regard: an assignment does *not* create/copy/clone a new object. (Assignment can create a 'new' immutable value [eg. number, bool, string {not: String}], this case is are generally not relevant to talk about as the immutable nature prevents the same state-modification observations.) – user2864740 Dec 06 '16 at 17:50
  • 1
    @NiettheDarkAbsol That is misleading in the larger context of languages (eg. compare C++) and also in context of "passing" (eg. to a function). JavaScript, like Python, is Call By [Object] Sharing which is a form of Call By Value. There is no need for the term "reference" (although it is often confused with the colloquial ".. refers to ..") and in fact, the specification does not use the term for this behavior. Instead of "the variable x references object y", I opt for "the variable x names object y" to avoid the terminology entirely and this is similar to Python's "name binding" terminology. – user2864740 Dec 06 '16 at 17:56
  • 1
    Objects are passed/assigned by value, and that value is a reference. – Oriol Dec 06 '16 at 17:57

0 Answers0