CodingNic

Functions

Parameters and Return Values

Functions 15 min read

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 return statement 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.

javascript
function greet(name) {
  console.log("Hello, " + name);
}

greet("Priya");
// Hello, Priya

A function can take several parameters, separated by commas:

javascript
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).

javascript
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.)

javascript
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.

javascript
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:

javascript
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:

javascript
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

  1. Write a function multiply(a, b) that returns the product of its two arguments. Call multiply(6, 7) and log the result.
  2. Write a function power(base, exponent = 2) that returns base to the power of exponent using a loop (multiply base by itself exponent times). Call it once with just power(5) and once with power(2, 3), logging both results.
  3. 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.
  4. Write a function logOnly(text) that logs text but has no return statement. Store the result of calling it in a variable and log that variable to confirm it’s undefined.

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 return statement, or with a bare return, evaluates to undefined.

Next lesson: closures, one of the trickiest but most useful ideas in JavaScript, a function that remembers variables from where it was created.