Skip to content

Functions

A function is a reusable block of code that performs a specific task.
It is called to avoid repeating code and improve readability.

In plain English:
“Give a name to a set of instructions, and reuse them whenever you want.”


function greet(name) {
return "Hello " + name;
}
console.log(greet("Alice")); // Hello Alice

Here, greet is a declared function.
It can be called before its definition thanks to the hoisting mechanism.


You can also store a function in a variable.
In this case, it cannot be called before its definition.

const greet = function(name) {
return "Hi " + name;
};
console.log(greet("Bob")); // Hi Bob

Introduced with ES6, they offer a shorter syntax.
They automatically inherit the this of their context (lexical this), which makes them convenient in callbacks.

const greet = (name) => "Hello " + name;
console.log(greet("Bob")); // Hello Bob

Important difference:

  • A classic function defines its own this.
  • An arrow function uses the this of the context where it was defined.

Parameters can have a default value if no argument is provided.

function multiply(a, b = 2) {
return a * b;
}
console.log(multiply(5)); // 10
console.log(multiply(5, 3)); // 15

A function can return a result with return.

function add(x, y) {
return x + y;
}
let result = add(4, 6);
console.log(result); // 10

SyntaxExampleParticularity
Declarationfunction name() {}Hoisting (can be called before definition)
Expressionconst f = function() {}No hoisting
Arrow (ES6)const f = () => {}Short syntax, lexical this
Tip

If your wiki still renders double backticks incorrectly, you can escape braces with { and } to force their display.