When talking about functions, one of the first things we mentioned was the word parameters. In this reading we will be covering what exactly a parameter is - as well as the differentiation between parameters and arguments.
Let's start off by talking about the difference between arguments and parameters and how to identify which is which.
So by defining parameters when we declare our function we are effectively setting accessible variables within the function:
function add(firstParameter, secondParameter) {
console.log(firstParameter + secondParameter);
}
// the add function declares two parameters
> add(1, 2); //=> 3
In the above example we declared our parameters when we declared our function. Now arguments work slightly differently - when the function is invoked we are passing in arguments. So in the above example when we invoked add(1, 2) the (1,2) were the arguments being passed in. So when a function is invoked the values of the passed in arguments are assigned to the declared parameters.
You can think of parameters and arguments like a recipe. A recipe is a list of ingredients (parameters) and list of steps (the code to be run). When someone cooks the recipe (invokes the function), they add the ingredients they actually have (arguments). The result of cooking the recipe is the delicious return value!
In JavaScript a function will not throw an error if the number of arguments passed during a function invocation is different than the number of parameters listed during function declaration. This is very important to know!
Let's use the above function to demonstrate:
function add(firstParameter, secondParameter) {
console.log(firstParameter + secondParameter);
}
// this will ignore the 17 & 14
// the first two arguments passed in will be assigned to the first two parameters
> add(1, 2, 17, 14); //=> 3
Notice in the above example we passed in 4 arguments (1, 2, 17, 14) to add. Since the function was only looking for two parameters that is all it uses.
Now what happens if we pass in fewer arguments then needed?
function add(firstParameter, secondParameter) {
console.log(firstParameter + secondParameter);
}
> add(5); //=> NaN
Whoa what happened there? Let's do a play-by-play:
firstParameter was set to equal the first passed in argument which in the above case is 5.secondParameter is declared as a variable but is set to the default value of undefined.undefined which is definitely not a number! So we get NaN (which means Not A Number) printed to the console.As you write more functions, you'll grow very comfortable using both arguments and parameters to accomplish your function's goal.