JavaScript Functions

Same Function Different Variables

When we call the same function from multiple places in our code using the function name followed by parentheses, it will run the same statements using the same variables each time. It would be more useful if we could get it to use different variables each time that we run it.

All three ways to define a function provides a way to specify a number of "arguments" that act as placeholders for the variables that the function is to use. Most of your functions will be defined using the third method we considered so we will look primarily at how to add arguments (and other features) to functions defined that way.

function myfunction(y, z) {
  a += y;
  b -= z;

The arguments are listed between the parentheses. These arguments can then be used anywhere inside the function as if they were variables. When the function is run the values from the variables are loaded into these arguments.

To link the variables that we want to use to these placeholder arguments we need to pass the variable names as parameters in the call to run the function. We do this by placing the variables themselves inside the parentheses when we run the function. We can also place numerical constants or text strings in the parameters if we want to pass values not held in variables.

var a = 0;
var b = 10;
var c = 3;
var d = 4;
var e = 2;
1 myfunction(c, d);
2 myfunction(d, e);
3 myfunction(9, 2);
4 myfunction(b, a);

The code above starts by assigning values to the a and b variables that will be updated by our function from earlier. We also define a few additional variables that we will pass as parameters into the function calls.

Note that it is the value that a has at the time that it is passed into the function that gets substituted into the argument and not the value that the original variable has at that point in the processing. It is the values in the parameters that the function uses and not the variables. This is called pass by value. In those languages where you can pass the actual variable into the function instead of just passing its value the method used to do so is called pass by reference. Had we been able to pass the variables into the function by reference rather than by value then the final value in b would have been -16 instead of -14.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow