Lesson 6
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.
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.
function add(a, b) {
return a + b;
}
const result = add(4, 7);
console.log(result); // 11function 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.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.
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 itIn JavaScript, a function is a value like any other: you can store it in a variable. This is called afunction expression.
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(3, 4)); // 12Since ES6, JavaScript offers a more concise syntax for writing functions: arrow functions. They are very widely used today, notably in frameworks such as React.
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)); // 16These 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:
// 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;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.
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 (...):
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)); // 100If you call a function with fewer arguments than parameters, the missing parameters are undefined. If there are more, the extra arguments are simply ignored:
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)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.
function sayHello() {
console.log("Hello!"); // displays a message, but returns nothing
}
const result = sayHello();
console.log(result); // undefinedDon'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.
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"A function can only return one value. To return several, you group them in an array or, more readably, in an object:
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); // 15Debugging 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.
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.
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.
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.
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 herecalculateTotal, validateForm, isAdult.is or has: isEven, hasAccess.sayHello launches nothing, you must write sayHello().return and getting undefined instead of the expected result.return: it will never be executed.divide(2, 10) does not give the same result as divide(10, 2).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:
isAdult(age) that returns true if the age is greater than or equal to 18, otherwise false.calculateAverage(...grades) that accepts a variable number of grades and returns their average.console.log().Exercise 2: default values and callbacks
In a new JavaScript file:
introduce(firstName, city = "Antananarivo") that displays a complete introduction sentence.isEven(n) that returns a boolean.map and your isEven function, transform the array [1, 2, 3, 4] into an array of booleans.return.return, a function returns undefined.