Harry
Harry

Reputation: 54939

javascript what happens on array push?

so I have:

var something = function () { return 6}

var foo = new something();

var arr = []
var arr2 = []

I do arr2.push(foo) and arr.push(foo)

What happens in the background? Is foo duplicated and put in 2 places? Is foo just foo and what's inside the arrays a reference to foo?

Thanks.

Upvotes: 1

Views: 144

Answers (2)

meder omuraliev
meder omuraliev

Reputation: 186562

EDIT: I misread. Because you are invoking the function with new you create a new object. Any object is passed by reference.

var something = function () { return 6}

var foo = new something();

typeof foo is an object so in this case it is passed by reference.

Pretty sure that foo is duplicated since it's a primitive and not an object.

Upvotes: 7

6502
6502

Reputation: 114461

What's inside the arrays are references to the same instance of something. This can be checked easily using for example chrome javascript console...

enter image description here

As you can see adding a new member x to arr1[0] got it appearing on arr2[0].

Upvotes: 1

Related Questions