Functions & Arrow Functions
Three ways to write functions
function add(a, b) { return a + b; } // declaration (hoisted)
const add2 = function (a, b) { return a + b; } // expression
const add3 = (a, b) => a + b; // arrow function
- Arrow functions with one expression return it automatically.
- Returning an object needs brackets:
() => ({ ok: true }).
Parameters
- Defaults:
function greet(name = "friend") { ... } - Rest:
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } - Destructuring:
function show({ name, age }) { ... }
Functions are values
You can store them in variables, pass them to other functions (callbacks) and return them. This is what makes map, filter, event listeners and promises possible.
Scope and closures
Variables live inside their { } block. An inner function remembers variables from where it was created, which is called a closure (used for counters, private data and settings).
Arrow functions and this
Arrow functions don't have their own this; they use the surrounding one. Use regular functions for object methods that need this, and arrows for callbacks.
💡 Keep functions small and name them with verbs: calculateTotal, fetchUsers.
Example
function greet(name = "friend") {
return `Hi, ${name}!`;
}
const square = (n) => n * n;
const sum = (...nums) => nums.reduce((total, n) => total + n, 0);
const describe = ({ name, age }) => `${name} is ${age}`;
console.log(greet(), greet("Ana")); // Hi, friend! Hi, Ana!
console.log(square(7), sum(1, 2, 3, 4)); // 49 10
console.log(describe({ name: "Ben", age: 21 }));
// Closure: a private counter
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
console.log(next(), next(), next()); // 1 2 3