1

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, what if it were an object?
A reference to the object would be passed.
1

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].

Comments

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.