Functions and return

A function is a named recipe: a block of code you write once and run whenever you want. You have already used one, console.log. Now you make your own:

function greet(name) {
  return "Hi, " + name;
}

const message = greet("Ada");
  • name is a parameter: a placeholder for whatever value gets passed in.
  • greet("Ada") calls the function, and "Ada" is the argument that fills the placeholder.
  • return hands a value back to whoever called the function. The function stops right there.

return is not console.log

This trips up almost everyone. console.log shows a value on the screen and then throws it away. return gives the value back so the rest of your program can use it: store it, add to it, pass it on. A function with no return gives back undefined. If your code says console.log(double(4)) and prints undefined, you forgot a return.

Arrow functions

Modern JavaScript has a shorter way to write functions, using =>:

const double = (n) => n * 2;

With no curly brackets, the value after the arrow is returned automatically. With curly brackets, you are back to needing a return:

const double = (n) => {
  return n * 2;
};

Both styles are everywhere in real code, so learn to read both. A good rule: use the short version for one-liners, the full version when the function does several things.

Variables made inside a function with let or const only exist inside that function. That keeps functions tidy: what happens in the function stays in the function.

Try it yourself

Edit it. Break it. Run it again.
function greet(name) {
  return "Hi, " + name + "!";
}
console.log(greet("Ada"));

const double = (n) => n * 2;
console.log(double(21));

function noReturn(n) {
  n * 2;
}
console.log(noReturn(5));

const area = (w, h) => {
  const result = w * h;
  return result;
};
console.log(area(3, 4));
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Return, do not print

double prints the answer instead of giving it back. Change it so double(n) returns n * 2.

function double(n) {
  console.log(n * 2);
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2The arrow brace trap

This arrow function returns undefined. Fix it so greet("Ada") returns "Hi, Ada!".

const greet = (name) => {
  "Hi, " + name + "!";
};
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.