0

I'm not sure of the terminology to search for an answer to this. Given:

this.snake = [{x: 0, y: 0}];
var curhead = this.snake[0];

Does curhead contain a copy of the dictionary(?) at snake[0] or a direct reference to it?

1
  • 1
    curhead will have a reference. Commented May 17, 2016 at 12:29

4 Answers 4

4

JavaScript always copies by value.

Objects in JavaScript, including Arrays, are only ever accessed by reference though. (i.e. foo = [] generates an array and assigns a reference to it to foo).

So you will get a copy of the first value in the array, which is a reference to the object.


This is distinct from being a reference to the first value in the array.

Given:

var array = [ { value: 1 } ];
var reference = array[0];
array.unshift( { value: 2 } );

If reference was a reference to the first value in the array, then by changing the first value it would point to the object with value : 2.

Since it is a copy of the value, it continues to be a reference to the object with value : 1 (which is now the second value in the array).

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

Comments

0

In the example you have given, curhead will contain a reference to the first item in the array snake

1 Comment

me too. Thanks for your help!
0

It is an array of objects with only one element. So

this.snake[0]

Will contain a reference to {x: 0, y: 0}.

Paras

Comments

-1

Now curHead and snake[0] refers to the exact same memory location . Try changing a value in curHead it will change snake[0] as well

curhead.x = 1
console.log(curhead)
//Object {x: 1, y: 0}
console.log(this.snake)
//[{x: 1, y: 0}]

Fun things happen when you try to assign a completely new object to curhead , lets say curhead = 'hi' . Then javaScript will create a new heap space for curhead and this.snake will be unchanged to its value {x: 1, y: 0}

2 Comments

"to the exact same memory location" — That's an implementation detail.
@sam if the answer was helpful please accept it by clicking check mark next to upvote section.

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.