Function Parameters Are Passed as Local Copies

This section provides a quick description of how primitive parameters and object parameters are all passed as local copies of whatever original variables store.

As shown in a previous section, JavaScript function call follows two rules: primitive parameters are passed by value and object parameters are passed by reference.

But actually, both rules are derived from a single rule: parameters are passed as local copies of whatever original variable store:

Notice that the above explanation uses these assumptions:

Saying that parameters are passed as local copies is actually more accurate, because passing parameters by reference is a very different programming feature.

Taking VBScript as an example, it supports the "ByRef" keyword to allow you to pass a function parameter as true reference for any data types, including primitive types. A VBScript function will not create a local copy of a "ByRef" parameter. It will use the "ByRef" parameter as an alias of the original variable.

The following VBScript code will swap the original variables by using "ByRef" parameters:

vFirst = "Dog"
vSecond = "Cat"
Call SwapByRef(vFirst, vSecond)
document.writeln(" After Sub: " & vFirst & " | " & vSecond)

Sub SwapByRef(ByRef vLeft, ByRef vRight)
vTemp = vLeft
vLeft = vRight
vRight = vTemp
End Sub

If you try to write a JavaScript function to swap two objects, you will definitely fail. See the next section for my examples.

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

Defining and Calling Functions

 Defining Your Own Functions

 Defining Your Own Functions - Example

 Calling Your Own Functions - Example

 Passing Parameters by Value or by Reference

Function Parameters Are Passed as Local Copies

 Function Parameters Are Passed as Local Copies - Example

 Global and Local Variables - Scope Rules

 Global Variables - Examples

 Local Variables - Examples

 Collision of Global and Local Variables - Examples

 "return" Statement and Return Value

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications


 PDF Printing Version