Lesson 6 / 1060%

Lesson 6

Functions

25 min

Declare, call and reuse code blocks with functions.

Definition

A function is a named, reusable block of code that performs a specific task. It can receive input values, calledparameters, and return a result using thereturn keyword. A function is definedonly once, then called as many times as needed by writing its name followed by parentheses.

What is a function in JavaScript?

A function is a reusable block of code designed to perform a specific task. It can receive parameters as input and return a result using thereturn keyword. Functions let you organize your code, avoid repetition, and make it much more readable and easier to maintain.

Without functions, every calculation or treatment would have to be rewritten in full at every place where it is needed. With functions, you write it once and call it as many times as needed.

A function is like a cooking recipe: you write it once, with the list of necessary ingredients (the parameters) and the steps to follow (the body of the function). Every time you want the dish (the call), you provide the ingredients and get the result. You already use some without knowing it:console.log(), prompt() orNumber() are functions written by others.

Declaring a classic function

classic-function.js
function add(a, b) {
  return a + b;
}

const result = add(4, 7);
console.log(result); // 11
  • function introduces the function declaration.
  • add is the name of the function: always choose a name that clearly describes its action.
  • a and b are the parameters: the values the function expects as input.
  • return sends the result back to the code that called the function, and ends its execution.

Defining is not calling

Writing a function does not run it: the code it contains only runs when you call it. Without the parentheses, you refer to the function itself instead of launching it.

define-vs-call.js
function sayHello() {
  console.log("Hello!");
}

// Nothing is displayed until the function is called
sayHello(); // "Hello!"
sayHello(); // "Hello!" (you can call it as many times as you want)

console.log(sayHello); // displays the function itself, without running it

A function stored in a variable

In JavaScript, a function is a value like any other: you can store it in a variable. This is called afunction expression.

function-expression.js
const multiply = function (a, b) {
  return a * b;
};

console.log(multiply(3, 4)); // 12

Arrow functions

Since ES6, JavaScript offers a more concise syntax for writing functions: arrow functions. They are very widely used today, notably in frameworks such as React.

arrow-function.js
const add = (a, b) => {
  return a + b;
};

// If the body of the function only contains a "return",
// you can write it in an even shorter way:
const doubleValue = (n) => n * 2;

// With a single parameter, the parentheses are optional:
const square = n => n * n;

console.log(doubleValue(5)); // 10
console.log(square(4));      // 16

These two syntaxes (classic function and arrow function) are very similar, but they handle the this keyword differently, a subtlety you will mostly encounter when working with objects or classes.

To go from a classic function to an arrow function, just follow three steps: remove the word function, add the arrow=> after the parameters, then, if the body only contains a return, remove the curly braces and the wordreturn:

transformation.js
// 1. Classic function
function triple(n) {
  return n * 3;
}

// 2. Arrow function with curly braces
const triple2 = (n) => {
  return n * 3;
};

// 3. Shortened arrow function (implicit return)
const triple3 = n => n * 3;

Parameters, arguments and default values

We distinguish the parameter (the name defined in the function) from the argument (the value actually provided when calling it). A function can also define adefault value for a parameter, used if no argument is passed for it.

default-value.js
const greet = (name = "Guest") => {
  console.log(`Hello ${name}!`);
};

greet("Léa"); // "Hello Léa!"
greet();      // "Hello Guest!" (default value used)

A function can also accept a variable number of arguments thanks to the "rest" syntax (...):

rest-parameters.js
const addAll = (...numbers) => {
  return numbers.reduce((total, n) => total + n, 0);
};

console.log(addAll(1, 2, 3));         // 6
console.log(addAll(10, 20, 30, 40));  // 100

If you call a function with fewer arguments than parameters, the missing parameters are undefined. If there are more, the extra arguments are simply ignored:

missing-arguments.js
function introduce(firstName, age) {
  console.log(firstName, age);
}

introduce("Aina", 17);       // Aina 17
introduce("Aina");           // Aina undefined
introduce("Aina", 17, 99);   // Aina 17  (the 99 is ignored)

The return value and undefined

A function that contains no return statement automatically returns undefined. This is a frequent source of errors for beginners, especially when trying to use the result of a function that returns nothing.

without-return.js
function sayHello() {
  console.log("Hello!"); // displays a message, but returns nothing
}

const result = sayHello();
console.log(result); // undefined

Don't confuse displaying a value withconsole.log() and returning it withreturn. Only the returned value can be reused in the rest of the program. Moreover, return stops the function immediately: any code placed after it is never executed.

return-stops-the-function.js
function divide(a, b) {
  if (b === 0) {
    return "Division by zero is impossible"; // the function stops here
  }
  return a / b;
}

console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // "Division by zero is impossible"

Returning several values

A function can only return one value. To return several, you group them in an array or, more readably, in an object:

multiple-return.js
function analyze(grades) {
  const total = grades.reduce((sum, n) => sum + n, 0);
  return {
    average: total / grades.length,
    maximum: Math.max(...grades),
  };
}

const summary = analyze([12, 15, 9]);
console.log(summary.average); // 12
console.log(summary.maximum); // 15

Debugging tip

When a function doesn't return what you expect, add aconsole.log() at the start to display its parameters, then another one just before the return. You will see immediately whether the problem comes from the received values or from the calculation.

Functions as values: passing a function as an argument

Since a function is a value, you can pass it to another function. A function passed as an argument is called a callback. You will come across them everywhere in JavaScript, for example with array methods such as forEach ormap.

callback.js
const names = ["aina", "hery", "miora"];

// forEach runs the provided function for each element
names.forEach((name) => {
  console.log("Hello", name);
});

// map returns a new array transformed by the function
const uppercased = names.map((name) => name.toUpperCase());
console.log(uppercased); // ["AINA", "HERY", "MIORA"]

We will come back to these methods in detail in the lesson dedicated to arrays.

Variable scope

A variable declared inside a function is only accessible within that function: this is calledlocal scope. A variable declared outside of any function is accessible everywhere in the file: this is calledglobal scope.

scope.js
const globalMessage = "I am accessible everywhere";

function saySomething() {
  const localMessage = "I am only accessible inside this function";
  console.log(globalMessage); // works
  console.log(localMessage);  // works
}

saySomething();
console.log(localMessage); // error: localMessage does not exist here
  • Always favor local variables over global ones: this avoids name conflicts and makes the code more predictable.
  • A function's parameters are also local variables: they only exist while the function is running.

Best practices for naming and writing functions

  • Give an explicit name, often a verb: calculateTotal, validateForm, isAdult.
  • A function should ideally do only one thing, and do it well.
  • Avoid overly long functions: if a function exceeds a few dozen lines, it can often be split up.
  • For a function that returns a boolean, start its name with is or has: isEven, hasAccess.
  • Avoid modifying global variables from inside a function: prefer receiving parameters and returning a result.

Common mistakes with functions

  • Forgetting the parentheses when calling: sayHello launches nothing, you must write sayHello().
  • Forgetting the return and getting undefined instead of the expected result.
  • Writing code after a return: it will never be executed.
  • Using a local variable outside its function, which causes the "is not defined" error.
  • Mixing up parameter and argument, or passing the arguments in the wrong order: divide(2, 10) does not give the same result as divide(10, 2).
  • Trying to return several values with several return statements: only the first one is executed, you must group the values in an array or an object.

Exercise 1: writing your first functions

In a new JavaScript file:

  1. Write an arrow function isAdult(age) that returns true if the age is greater than or equal to 18, otherwise false.
  2. Write a function calculateAverage(...grades) that accepts a variable number of grades and returns their average.
  3. Test both functions with several different values and display the results with console.log().

Exercise 2: default values and callbacks

In a new JavaScript file:

  1. Write a function introduce(firstName, city = "Antananarivo") that displays a complete introduction sentence.
  2. Write a function isEven(n) that returns a boolean.
  3. Using map and your isEven function, transform the array [1, 2, 3, 4] into an array of booleans.

Key takeaways

  • A function groups reusable code, with parameters as input and a result returned via return.
  • Defining a function does not run it: you must call it with parentheses.
  • Arrow functions offer a shorter syntax, widely used in modern JavaScript.
  • Without return, a function returns undefined.
  • A function is a value: you can store it in a variable or pass it as an argument (callback).
  • Variables declared inside a function have local scope, invisible from the outside.