Is this the correct way?
Regarding object creation you're doing fine.
testvalue = new Object();
testvalue["name"] = "abc";
testvalue["size"] = 2048;
But you can use {}
to create an object. Read more about the differences here.
testvalue = {
name: "abc",
size: 2048
};
If find the last one more easily read.
Does using new every time overwrite the existing memory or does it
allocates new memory and dereferences the older one?
Well, that's a more tricky one. I would say what you're really asking is: Does it allow the reference to be garbage collected? And then I would say probably not, but it may depend on the garbage collector.
According to MDN regarding Reference-counting garbage collection (the naive one).
An object is considered garbage collectable if there is zero reference
pointing at this object.
Then I would say that it wouldn't be garbage collected since there's still a reference to the first object. See this snippet below. There are two objects in the array, and therefore they cannot be garbage collected yet.
var testvalues = [];
var testvalue ;
testvalue = new Object();
testvalue["name"] = "xyz";
testvalue["size"] = 1024;
testvalues.push(testvalue);
testvalue = new Object();
testvalue["name"] = "abc";
testvalue["size"] = 2048;
testvalues.push(testvalue);
console.log(testvalues.length); // Will print "2".
So when you really need to free up some memory you should null
the array and the object. However, in real life, this is rarely needed unless you got a really big array.
$scope.testvalues = null;
testvalue = null;