Parameters and Return Values
Objectives
By the end of this chapter, you should be able to:
- Pass parameters into a function and use them inside its body
- Give a parameter a default value with default parameters
- Collect any number of arguments with rest parameters (
...args) - Explain what a function returns when it has no
returnstatement at all
💡 Why this matters: Parameters are how you feed information into a function, and return values are how you get information back out. Almost every function you write does both.
Parameters
A parameter is a named placeholder in a function’s definition. When you call the function, you pass in an argument, and it’s matched to the parameter by position.
function greet(name) {
console.log("Hello, " + name);
}
greet("Priya");
// Hello, Priya
A function can take several parameters, separated by commas:
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
// 5
If you call a function with fewer arguments than it has parameters, the missing ones are undefined inside the function body. Calling it with extra arguments just ignores the extras.
Default Parameters
A default parameter gives a parameter a fallback value to use when no argument is passed for it (or when the argument passed is undefined).
function greetDefault(name = "friend") {
console.log("Hello, " + name);
}
greetDefault();
// Hello, friend
greetDefault("Sam");
// Hello, Sam
Default parameters are useful anytime an argument is optional and you want sensible behavior without it.
Rest Parameters
Sometimes you don’t know in advance how many arguments a function will receive. A rest parameter, written ... followed by a name, collects any number of extra arguments into a single list you can loop over. (That list is called an array, you’ll learn much more about arrays next module. For now, just know you can read items out of it by position, starting at 0, and check how many items it holds with .length.)
function sum(...numbers) {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total = total + numbers[i];
}
return total;
}
console.log(sum(1, 2, 3));
// 6
console.log(sum(10, 20, 30, 40));
// 100
sum works no matter how many arguments you pass it, because ...numbers gathers all of them. A rest parameter must be the last parameter in the list, and there can only be one.
Return Values
A return statement ends a function immediately and hands back a value to wherever it was called.
function isEven(n) {
if (n % 2 === 0) {
return true;
}
return false;
}
console.log(isEven(6));
// true
console.log(isEven(7));
// false
As soon as a return runs, the function stops. Code written after it in the same path never executes.
What a Function Returns With No return Statement
If a function never hits a return statement, it doesn’t return “nothing,” it returns the value undefined. This is easy to prove:
function logMessage(text) {
console.log(text);
}
const result = logMessage("hi");
console.log(result);
// hi
// undefined
logMessage only logs its argument, it never returns anything explicitly. Storing the result of calling it and logging that result proves the value is undefined. The same thing happens with a bare return and no value after it:
function doNothing() {
return;
}
console.log(doNothing());
// undefined
Every function in JavaScript returns something. If you don’t write return, that something is undefined.
Try It
- Write a function
multiply(a, b)that returns the product of its two arguments. Callmultiply(6, 7)and log the result. - Write a function
power(base, exponent = 2)that returnsbaseto the power ofexponentusing a loop (multiplybaseby itselfexponenttimes). Call it once with justpower(5)and once withpower(2, 3), logging both results. - Write a function
total(...values)using a rest parameter that adds up any number of arguments. Call it with four numbers and log the result. - Write a function
logOnly(text)that logstextbut has noreturnstatement. Store the result of calling it in a variable and log that variable to confirm it’sundefined.
Recap
- Parameters are placeholders filled in by arguments when a function is called.
- Default parameters supply a fallback value when no argument (or
undefined) is passed. - Rest parameters (
...args) collect any number of arguments into a single list. - A function without a
returnstatement, or with a barereturn, evaluates toundefined.
Next lesson: closures, one of the trickiest but most useful ideas in JavaScript, a function that remembers variables from where it was created.