DevPath · Learn to code ESPTEN

Functions

Function declaration vs expression

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?

⚠️ 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
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Arrow functions →