theJava
theJava

Reputation: 15034

Difference betwen these two ways of creating objects of arrays

var obj = {};
obj.arr1 = [];
obj.arr2 = [];

// Does the above one create a new object each time.

var obj = {
  obj.arr1 = [],
  obj.arr2 = []
};

Upvotes: 0

Views: 93

Answers (3)

krishna
krishna

Reputation: 950

I imagine in the first way the array is created and in the later step it adds the element by creating memory location ...where as in second methodology the array is created and the elements of it also created then and there itself. (I imagine diff is the time of creation of memory locations for the array elements may vary)

Upvotes: 0

xdazz
xdazz

Reputation: 160833

// Does the above one create a new object each time.

No. And the too ways is almost the same.

And second way is not right, should be

var obj = {
  arr1: [],
  arr2: []
};

How can i create a new object each time

If you mean the array object [], yes they are already different objects. obj.arr1 and obj.arr2 is not same object. obj.arr1 === obj.arr2 will return false

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129782

Except for the syntax error, the two means of creating the object will give you the exact same result. In your second example, what you're thinking of is probably this:

var obj = {
  arr1: [],
  arr2: []
};

I'm not sure what you mean with regards to creating a new object each time. In both examples of the code, the value variable obj will be set to a new object with two empty arrays. If there was already an obj object in that context, with one or more arrays, they would be overwritten.

Upvotes: 3

Related Questions