Kodokon kodokon.com

Functions: declaration, parameters, return

Create reusable blocks of code with function, pass them parameters and get their results back with return.

6 min · 3 questions

Open this lesson in Kodokon

A function is a reusable block of code that you give a name to. It is like a cooking recipe: you write it once, then you can run it as many times as needed. To create a function, you use the function keyword, followed by its name, parentheses () and a block between curly braces { }. To execute it, you call it by writing its name followed by parentheses.

JAVASCRIPT
function sayHello() {
  console.log("Hello!");
}

sayHello(); // Prints: Hello!
sayHello(); // Prints: Hello!
A function declared once, called twice

A function becomes really useful when it accepts information. A parameter is a variable declared between the function's parentheses: it acts as an input box. When you call the function, the concrete value you pass in is called an argument. In the following example, name is the parameter and "Léa" is an argument.

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

greet("Léa");  // Prints: Hello, Léa!
greet("Marc"); // Prints: Hello, Marc!
The name parameter changes with each call

Printing a message is nice; producing a reusable result is better. The return keyword sends a value back to the place where the function was called: the call add(2, 3) is then replaced by its value, 5. You can store this result in a variable or use it directly. Note that return immediately ends the function's execution.

JAVASCRIPT
function add(a, b) {
  return a + b;
}

const result = add(2, 3);
console.log(result);     // Prints: 5
console.log(add(10, 4)); // Prints: 14
return produces a result you can use anywhere

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which keyword lets a function send a result back to where it was called?
    • return
    • function
    • result
    • send
  2. With function add(a, b) { return a + b; }, what is the value of add(2, 3)?
    • 23
    • 5
    • undefined
  3. What do you call the concrete values passed to a function when it is called?
    • Arguments
    • Parameters
    • Indexes