Austen
Austen

Reputation: 1970

Referencing javascript objects

This has always been a bit confusing to me and my programming jargon isn't adequate to google it. Not even sure if the title makes sense. For example, if I have an array of objects like so...

var someObjects = [{type: 'apple'}, {type: 'orange'}, {type: 'banana'}];

...and I say that...

var theBestFruit = someObjects[2];

but then we add another object to the beginning, shifting all the elements...

someObjects.unshift({type: 'pear'});

Will theBestFruit still reference the banana object? Or will it now be the orange? Some explanation would be much appreciated.

Upvotes: 1

Views: 124

Answers (3)

Dan D.
Dan D.

Reputation: 74655

> var someObjects = [{type: 'apple'}, {type: 'orange'}, {type: 'banana'}];
undefined
> var theBestFruit = someObjects[2];
undefined
> someObjects.unshift({type: 'pear'});
4
> someObjects
[ { type: 'pear' },
  { type: 'apple' },
  { type: 'orange' },
  { type: 'banana' } ]
> theBestFruit
{ type: 'banana' }
> 

Upvotes: 1

user166390
user166390

Reputation:

Well .. try it?

Hint:

The someObject[2] expression is eagerly evaluated to a value (read: object) which is then bound (read: assigned to) the variable theBestFruit. Unless theBestFruit is re-assigned (read: bound to something else) it will always evaluate to the same object (read: value).

It doesn't matter if someObjects[2] evaluates to something else later - it doesn't affect the binding of theBestFruit which was determined at the time of = (read: assignment).

Upvotes: 3

Amadan
Amadan

Reputation: 198324

theBestFruit = someObjects[2] will look up what is at the second (or third, if you count as a non-programmer :p ) position of someObject, (which is the object {type: 'banana'}, and assign a direct reference to this object to theBestFruit. The reference is not to the second object of someObjects. Thus, if someObjects change, theBestFruit will still be {type: 'banana'}.

The best way to test it would be to... test it.

Upvotes: 2

Related Questions