Functions
What is a function?
Section titled “What is a function?”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 declaration
Section titled “Function declaration”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.
Function expressions
Section titled “Function expressions”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
Arrow functions
Section titled “Arrow functions”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 and default values
Section titled “Parameters and default values”Parameters can have a default value if no argument is provided.
function multiply(a, b = 2) { return a * b;}
console.log(multiply(5)); // 10console.log(multiply(5, 3)); // 15
Returning a value
Section titled “Returning a value”A function can return a result with return
.
function add(x, y) { return x + y;}
let result = add(4, 6);console.log(result); // 10
Syntax comparison
Section titled “Syntax comparison”Syntax | Example | Particularity |
---|---|---|
Declaration | function name() {} | Hoisting (can be called before definition) |
Expression | const f = function() {} | No hoisting |
Arrow (ES6) | const f = () => {} | Short syntax, lexical this |
If your wiki still renders double backticks incorrectly, you can escape braces with {
and }
to force their display.