More on ByVal and ByRef

In my previous entry I discussed VBScript’s various syntaxes for passing values by reference. However it occurs to me that there may be some confusion about what exactly “pass by reference” (byref) and “pass by value” (byval) mean in JavaScript and VBScript. This is frequently a source of confusion, as VBScript has byref behaviour not supported in JavaScript.

The confusion arises because VBScript uses “by reference” to mean two similar-but-different things. VBScript supports reference types and variable references. JavaScript supports the former but not the latter.

The best way to illustrate the difference is with an example. Consider this VBScript class:

Class Foo 
      Public Bar 
End Class

Now we can create an instance of this class:

Dim Blah, Baz 
Set Blah = New Foo 
Set Baz = Blah 
Blah.Bar = 123

Both Blah and Baz are references to the same object. The fourth line changes both Blah.Bar and Baz.Bar because these are different names for the same thing.

That’s the “reference type” feature. We say that VBScript treats objects as reference types.

Now consider this little program:

Sub Change(ByRef XYZ) 
    XYZ = 5 
End Sub 
Dim ABC 
ABC = 123
Change ABC

This passes a reference to variable ABC. The local variable XYZ becomes an alias for ABC, so the assignment XYZ = 5 changes ABC as well.

JavaScript has reference types — all object types are reference types. But JavaScript does not support variable references; you cannot alias one variable with another in JavaScript.

1 thought on “More on ByVal and ByRef

  1. Pingback: Porting old posts, part 1 | Fabulous adventures in coding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s