Create reusable blocks of code with function, pass them parameters and get their results back with return.
Open this lesson in KodokonA 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.
function sayHello() {
console.log("Hello!");
}
sayHello(); // Prints: Hello!
sayHello(); // Prints: Hello!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.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Léa"); // Prints: Hello, Léa!
greet("Marc"); // Prints: Hello, Marc!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.
function add(a, b) {
return a + b;
}
const result = add(2, 3);
console.log(result); // Prints: 5
console.log(add(10, 4)); // Prints: 14function add(a, b) { return a + b; }, what is the value of add(2, 3)?