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:
<html>
<!-- Swap_Funtion.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Swap Function</title></head>
<body>
<pre>
<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");
swap(first,second);
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");
swap(one,two);
document.write(" After call: "+one+" | "+two+"\n");
</script>
</pre>
</body>
</html>
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.