Javascript Concepts

Google Maps API Tutorial

avascript Concepts: Pass by Value

I was recently asked whether Javascript function parameters are passed by Reference or by Value. The really quick answer is that they are passed by Value. The full answer is actually quite complicated, and I won’t be going into all the details.

What’s it all about

Some computer languages allow function parameters to be passed either by Reference or by Value.

When a parameter is passed by Reference, then any changes made to it inside the function also change the copy of the variable that’s held outside the function. The variable used inside the function is a pointer to the external copy of the variable

When a parameter is passed by Value, then the function has its own local copy of the variable. Changes to the local copy don’t affect anything outside the function. The variable used inside the function is a local variable that (initially) has the same value as the external variable.

Created by Reference

However, Javascript differs from some other languages in that complex variables are created by Reference.

When you create a numeric or Boolean variable in Javascript, then that variable contains the numeric value you specify.

When you create any other type of variable, such as a string or an Object(), then the variable contains a Reference to the chunk of memory where the data is located. In some computer languages you might say that Object() variables are pointers.

For rather technical reasons, you don’t need to worry about strings. They end up behaving just as if they were passed by Value.

The fact that Object() variables are references does affect what happens when a function modifies a property of a passed Object(). Changing or adding a property of an Object() does affect the property of the external copy of the Object().

For example:

 function tweakIcon(a) { a.image="mymarker.png"; a = some_other_icon; } var icon = new GIcon(); tweakIcon(icon); alert(icon.image);

The “icon.image” property has been changed to “mymarker.png”, but “icon” isn’t affected by the “a = some_other_icon;” statement.

Assignment by Reference

Javascript assignment statements for complex variables are by Reference.

For example:

 var marker1 = new GMarker(point); var marker2 = marker1;

creates a second variable that points to the same chunk of memory where the marker data is located. The two variables are references to the same Object()

Whereas this:

 var marker1 = new GMarker(point); var marker2 = marker1.copy();

creates a second marker that has the same properties.

Comparison by Reference

Javascript comparison operations are by Reference.

if (marker1 == marker2) is true if the variables reference the same marker Object(), but false if marker2 is a .copy() of marker1.

Advertisements