Parameters, Arguments and Abstraction
Parameters and arguments
Parameters are the input variables of a function. Arguments are the values supplied for those parameters when the function is called.The parameters are the names inside the parentheses on the function line. The arguments are the values inside the parentheses at the call.
| Where you see it | What it is called |
|---|---|
| Inside the parentheses on the function line | A parameter |
| Inside the parentheses at the call | An argument |
Arguments are matched to parameters by position. The first argument fills the first parameter, the second fills the second, and so on. Whatever names the caller uses for its own variables make no difference at all. Only the order counts.
The wrong number of arguments
JavaScript never checks that a call supplies exactly one argument for each parameter. It matches whatever it can, by position, and carries on running. Both of the mistakes below are silent: nothing stops, and no message appears.The function below has two parameters,
goal and walked, and the call sends it two arguments, target and today. Run it, then change it and run it again:• Swap the two arguments, so that the call reads
stepsLeft(today, target).• Press Reset, then add a third argument, so that the call reads
stepsLeft(target, today, 500).• Press Reset, then delete the second argument, so that the call reads
stepsLeft(target).function stepsLeft(goal, walked) {
return goal - walked;
}
let target = 10000;
let today = 6200;
console.log("Steps left:", stepsLeft(target, today));
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.
Abstraction
Abstraction means removing unnecessary detail. You can ride an elevator by pressing one button, without knowing anything about the motor, the cables or the counterweight that move you.One common kind of abstraction is procedural abstraction. It gives a name to a process, and lets that process be used knowing only what it does, not how it does it.
Why procedural abstraction is worth it
Procedural abstraction:• makes code readable, because a well-named call says what is happening
• gives a block of code a name that describes its purpose
• allows reuse, so the same work is written once instead of copied
Speed is not on that list. Wrapping work in a function does not make the work itself any faster.