JSJavaScript · Lesson 4 of 14

Functions & Arrow Functions

JavaScript has multiple syntaxes for functions. This is not a bug, it's a feature. The arrow syntax is the most common in modern code.

JavaScript
// Function declaration — hoisted (can be called before it's defined)
function add(a, b) {
  return a + b;
}

// Function expression — not hoisted
const multiply = function(a, b) {
  return a * b;
};

// Arrow function — modern, concise
const subtract = (a, b) => a - b;            // implicit return
const square = x => x * x;                    // single param, no parens needed
const greet = () => "Hello!";                  // no params

// Multi-line arrow function needs explicit return
const divide = (a, b) => {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
};

console.log(add(2, 3));       // 5
console.log(multiply(4, 5));  // 20
console.log(square(7));       // 49

// Default parameters
function greetUser(name = "World") {
  return `Hello, ${name}!`;
}
console.log(greetUser());        // Hello, World!
console.log(greetUser("Alice")); // Hello, Alice!

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5));  // 15

JavaScript functions are first-class values — you can assign them to variables, pass them as arguments, and return them from other functions. This enables powerful patterns like callbacks and higher-order functions.

JavaScript
// Closures — functions that remember their surrounding scope
function makeCounter(start = 0) {
  let count = start;
  return {
    increment: () => ++count,
    decrement: () => --count,
    value: () => count,
  };
}

const counter = makeCounter(10);
counter.increment();
counter.increment();
console.log(counter.value()); // 12

// Destructuring in function parameters
function displayUser({ name, age, city = "Unknown" }) {
  console.log(`${name}, ${age}, ${city}`);
}
displayUser({ name: "Alice", age: 30, city: "Paris" });

// Spread operator
function addThree(a, b, c) {
  return a + b + c;
}
const args = [1, 2, 3];
console.log(addThree(...args));  // 6