What is a function?
Imagine having to rewrite the same recipe every single time you wanted dinner. A nightmare, right? Functions are the exact opposite: your first superpower as a programmer. Write the logic once and use it a thousand times.
A function is a named block of code that groups instructions so you can reuse them. Think of it like a cooking recipe: you write it once and "cook it" (call it) as many times as you like, without ever jotting down the steps again.
Function declaration
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Ana")); // "Hello, Ana"
A declaration starts with the keyword function followed by a name. It has a
special property: thanks to hoisting you can call it before you write it
in the code.
Function expression
const greet = function (name) {
return "Hello, " + name;
};
Here the function has no name of its own (it is anonymous) and is stored in a variable. Unlike the declaration, you cannot use it before defining it.
Which one should you use?
- Declaration: ideal for main, reusable functions.
- Expression: useful when you pass a function as data (for example, to another function).
⚠️ Classic trap: mixing up defining a function with calling it. Writing
greet (no parentheses) gives you the whole function; greet("Ana") actually
runs it. They're two different moves, and forgetting the parentheses is one of
the most common slip-ups.
Examples
Declaration called before being defined (hoisting)
console.log(double(5)); // 10, it works even though it's above!
function double(n) {
return n * 2;
}
Function expression stored in a variable
const square = function (n) {
return n * n;
};
console.log(square(4)); // 16