0

Why does the code below print "Tree", "Tree", and not "Bear", "Tree"?

var file_array = new Array(100);
var fileobject = {name: null , folder: null , url: null , modified: null};

fileobject.name = "Bear";
file_array[0] = fileobject;
fileobject.name = "Tree";
file_array[1] = fileobject;

console.log(file_array[0].name);
console.log(file_array[1].name); 

1 Answer 1

2

There's only one object involved. Assigning an object value with = assigns a reference to the object, not a copy.

It's possible to copy objects, but in the general case it can grow to a very hard problem (due to things like reference cycles). If you need lots of those objects, a better solution would be to write a function that returns a fresh object when you call it:

function makeFileObject(name) {
  return {name: name , folder: null , url: null , modified: null};
}

file_array[0] = makeFileObject("Bear");
file_array[1] = makeFileObject("Tree");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, been pulling my hair out over this one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.