Passing data by value
When you pass data to a function by value, this means that you are passing whatever the variable is holding, not the variable itself. Therefore, the function creates a copy and subsequently changing the copy or the original to not affect the other.
Numbers and Boolean values (true and false) are copied, passed, and compared by value. When you pass a parameter to a function by value, you are making a separate copy of that parameter, a copy that exists only inside the function.
// Global variable
num = 10;
function incrementor(num)
{
// Change the local num
num++;
return(num);
}
document.write(incrementor(num));
document.write(num); |
To run the code, paste it into JavaScript Editor, and click the Execute button. Since passing-by-value is used, changing the local variable does not affect the global one.
Passing data by reference
Passing by reference means that the alias representing the variable itself is received, not the copy. Since the alias (reference) represents the variable itself, changing it changes the original.
Arrays, functions and objects are typically are copied, passed, and compared by reference. When you pass a parameter by reference, and the function changes the value of that parameter, it is changed everywhere in the script.
// Define an array
days = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
function MyFunction(arr)
{
arr[6]="Sunday";
}
MyFunction(days);
for (key in days)
document.write("Element value is " + days[key]); |
To run the code, paste it into JavaScript Editor, and click the Execute button. Do you expect the days variable to include "Sunday" after a call to MyFunction or not?
Next
|