Parameters and Arguments
Learn about parameters and arguments in functions.
We'll cover the following...
Understanding parameters and arguments
Parameters and arguments are terms that are often used interchangeably to represent values that are provided for the function as an input. There’s a subtle difference though: the parameters of a function are set when the function is defined, whereas the arguments of a function are provided when it is called.
To see an example of a function that uses parameters, let’s create a function that squares numbers. In the example that follows, the square
function accepts a single parameter, n
, which is the number to be squared. In the body of the function, the name of the parameter acts just like a variable. We multiply this value by itself and return the result:
function square(n) {return n * n;}
When we call this function, we need to provide an argument, which takes the place of the parameter in the definition and is the number to be squared:
console.log(square(4.5));
When defining arrow functions with a single parameter, the parameters come before the arrow and the main body of the function comes after. For example, the square
function can be written like so:
const square = n => n * n;
Notice that arrow functions don’t need parentheses around the parameter, making them even more succinct.
We can use as many parameters as we like when defining functions. For example, the following function finds the mean of any three numbers by adding them together and dividing the result by three:
function mean(a, b, c) {return (a + b + c) / 3;}
Let’s run that in the console:
console.log(mean(8, 3, 4));
When using more than one parameter with arrow functions, we need to place them in parentheses, so the mean
function would be written in arrow notation like this:
mean = (a, b, c) => (a + b + c) / 3;
If a parameter isn’t provided as an argument when the function is called, the function will still be called, but the missing argument will be given a value of undefined
. For example, if we tried to call the mean
function with only two
arguments, it would return NaN
, which is the result of trying ...