Lessons / JavaScript / Unit 4

Functions

A function is a named block of code you can run whenever you want. You write it once and use it as many times as you need.

JavaScript · Unit 4 of 5 · about 4 minutes

Making and calling a function

You make a function with the word function, a name, brackets and curly braces. The code inside doesn't run until you call the function by writing its name followed by brackets.

function sayHi() {
  console.log("Hi!");
}

sayHi();
sayHi();
Hi!
Hi!

Parameters

Parameters are names in the brackets that receive values when the function is called. The values you pass in are called arguments.

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

greet("Sam");
greet("Ana");
Hi, Sam
Hi, Ana

Returning a value

return sends a value back to wherever the function was called. You can store it, print it or use it in another calculation.

function double(n) {
  return n * 2;
}

let x = double(4);
console.log(x + 1);
9

Try it

What does this print?

function addOne(n) {
  return n + 1;
}

console.log(addOne(addOne(2)));
The inner call runs first. addOne(2) is 3. Then addOne(3) is 4.

return ends the function

As soon as a function reaches return, it stops. Any lines after it inside the function are skipped.

Try it

What does this print?

function test() {
  return "hi";
  console.log("bye");
}

console.log(test());
return sends back "hi" and ends the function. The console.log("bye") line never runs.

Printing is not returning

This is one of the most common beginner mix-ups. console.log inside a function shows a value on screen, but the function still gives back nothing. In JavaScript, nothing is called undefined.

function add(a, b) {
  console.log(a + b);
}

let result = add(2, 3);
console.log(result);
5
undefined

Try it

How do you fix the add function above so result is 5?

The function needs to return the value. Then result stores 5 instead of undefined.

Arrow functions

You'll often see a shorter way to write small functions, called an arrow function. These two do the same thing.

function square(n) {
  return n * n;
}

const square2 = (n) => n * n;

console.log(square(5), square2(5));
25 25

Common mistakes

Forgetting the brackets when calling

greet on its own does nothing. You need greet() to run it.

Forgetting return

If a function calculates something but never returns it, you get undefined back.

Passing arguments in the wrong order

Arguments match parameters by position. If a function is subtract(a, b), then subtract(2, 10) is -8, not 8.

Recap

  • A function is a named block of code you can run again.
  • Parameters receive the values you pass in.
  • return sends a value back and ends the function.
  • console.log shows a value. It doesn't return it.