Function Parameters Are Passed as Local Copies - Example

This section provides a tutorial example on swapping original primitive and object variables in a function.

To prove that JavaScript function always create local copies for object parameters, I wrote the following tutorial example to try to swap two objects:

<!-- Swap_Function.html
   Copyright (c) 2013 by Dr. Herong Yang,
<head><title>Swap Function</title></head>
<script type="text/javascript">
// Defining a swap function
function swap(left, right) {
   var temp = left;
   left = right;
   right = temp;
   document.write("   Inside swap(): "+left+" | "+right+"\n");
   document.write("   Type of argument: "+(typeof left)+"\n"); 

   var first = "Dog";
   var second = "Cat";
   document.write("\nTest 1: Swapping two string variables\n");
   document.write("   Before call: "+first+" | "+second+"\n");
   document.write("   After call: "+first+" | "+second+"\n");

   var one = new String("White");
   var two = new String("Black");
   document.write("\nTest 2: Swapping two string objects\n");
   document.write("   Before call: "+one+" | "+two+"\n");
   document.write("   After call: "+one+" | "+two+"\n");

The output shows that function parameters are always passed as local copies of original variables:

Test 1: Swapping two string variables
   Before call: Dog | Cat
   Inside swap(): Cat | Dog
   Type of argument: string
   After call: Dog | Cat

Test 2: Swapping two string objects
   Before call: White | Black
   Inside swap(): Black | White
   Type of argument: object
   After call: White | Black

There is no way to swap two original variables in a function, no matter if they are primitive variables or object variables.

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