AI Hints
JavaScript · Lesson 32 of 138

Parameters and Return

Inputs and outputs.

⏱ 2 min read▶ Video at 38:44🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A function becomes much more useful when you can give it information, and get a result back. The information going in is called a parameter. The result coming out is the return value.

Parameters and Return
From the video: Parameters and Return
  • Give it information
  • Get a result back
  • Parameters and return

In and out

Name, inside the brackets, is a parameter. When we call greet with Ana, name holds Ana. Area takes two parameters, and return sends the answer back to whoever called it. We can store that answer, or use it straight away. Run it.

app.jsjavascript
function greet(name) {
  console.log(`Hello, ${name}!`);
}

function area(width, height) {
  return width * height;
}

greet("Ana");
const room = area(4, 5);
console.log("Room:", room, "square metres");
console.log("Garden:", area(10, 3));
Output
Hello, Ana!
Room: 20 square metres
Garden: 30

Return ends the function

As soon as return runs, the function stops, and hands back its value. Any code after it is skipped. A function with no return gives back undefined. Printing inside a function, and returning a value, are different things. Return is how one function passes results to another.

keyvalue
Parameteran input name
Argumentthe value you pass
returnsends a result back
No returngives undefined

Returning early

A function can have more than one return. Here, the first return handles bad input, and leaves straight away. That's called an early return, or a guard. The main calculation only runs when the input is good, and it isn't buried inside an if. Run it.

app.jsjavascript
function average(numbers) {
  if (numbers.length === 0) {
    return 0;
  }
  let total = 0;
  for (const n of numbers) total += n;
  return total / numbers.length;
}

console.log(average([4, 8, 6]));
console.log(average([]));
Output
6
0

Summary

Parameters bring values into a function, and return sends a result out. Next, default values for parameters.

Key takeaways
  • function f(a, b)
  • return a result
  • Store or use it
Next up: Default Parameters — fallback values