weird behaviour of javascript with arrays

arrays, javascript

Solution

The problem with Chrome's console is that it doesn't copy the objects you pass to it.

By the time Chrome builds the console the objects it displays have changed.

If you want to see your "me", try this :

  var arr = [];
  var temp = { "name": "me" };
  arr.push(temp)
  console.log(arr)
  setTimeout(function(){
      temp["name"] = "you";
      arr.push(temp)
      console.log(arr)
  }, 3000);

and look inside the array in less than 3 seconds.

Fiddle : http://jsfiddle.net/TMDq2/

Some may see it as a bug, some as an optimization. It's at least a borderline implementation...

Problem

Let us consider the following JavaScript snippet ``` var arr = []; function pushMe() { var temp = { "name": "me" }; arr.push(temp) console.log(arr) temp["name"] = "you"; arr.push(temp) console.log(arr) } ``` I was astonished to see the output as `[Object { name="you"},Object { name="you"}]` As we are pushing the references, both must refer to same object. But at least after the first push output must be like `Object { name="me"}` Why is this happening?? thanks :)

Original source