JavaScript From Zero · 16 min · 120 XP

Functions and return values

Functions package a job so you can run it whenever you need it.

A function is a named recipe. You hand it ingredients (arguments), it does its work, and it hands something back (the return value). If a function does not return anything, calling it gives you undefined, one of the most common sources of the dreaded "why is my value empty?" bug.

A function with an explicit return
function total(price, quantity) {
  return price * quantity;
}

console.log(total(12, 3)); // 36

Arrow functions are a shorter way to write the same thing, and you'll see them everywhere: const total = (price, quantity) => price * quantity;. With a single expression after the arrow and no braces, its value is returned automatically. Add braces and you need return again. Default parameters fill in a missing argument: function greet(name = "there").

Rule of thumb: if you ever write const x = someFunction() and x is undefined, check whether the function actually returns.

Loading your workspace…