08

Functions

Chapter 8 • Intermediate

40 min

Functions

Functions are reusable blocks of code that perform a specific task. They are fundamental to JavaScript and help organize code into logical, reusable pieces.

Function Declaration

The most common way to define a function:

javascript.js
function greet(name) {
    return 'Hello, ' + name + '!';
}

Function Expression

Assigning a function to a variable:

javascript.js
let greet = function(name) {
    return 'Hello, ' + name + '!';
};

Arrow Functions (ES6)

A more concise syntax for function expressions:

javascript.js
let greet = (name) => {
    return 'Hello, ' + name + '!';
};

// Even more concise for single expressions
let greet = name => 'Hello, ' + name + '!';

Function Parameters

Default Parameters

javascript.js
function greet(name = 'World') {
    return 'Hello, ' + name + '!';
}

Rest Parameters

javascript.js
function sum(...numbers) {
    return numbers.reduce((acc, num) => acc + num, 0);
}

Function Scope

Functions create their own scope. Variables declared inside a function are not accessible outside:

javascript.js
function example() {
    let localVar = 'I am local';
    console.log(localVar); // Works
}

console.log(localVar); // Error: localVar is not defined

Higher-Order Functions

Functions that take other functions as arguments or return functions:

javascript.js
function createMultiplier(factor) {
    return function(number) {
        return number * factor;
    };
}

let double = createMultiplier(2);
let triple = createMultiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

Immediately Invoked Function Expressions (IIFE)

Functions that execute immediately after being defined:

javascript.js
(function() {
    console.log('This runs immediately!');
})();

Hands-on Examples

Function Basics

// Function declaration
function calculateArea(length, width) {
    return length * width;
}

// Function expression
let calculatePerimeter = function(length, width) {
    return 2 * (length + width);
};

// Arrow function
let calculateVolume = (length, width, height) => {
    return length * width * height;
};

console.log('Area:', calculateArea(5, 3));
console.log('Perimeter:', calculatePerimeter(5, 3));
console.log('Volume:', calculateVolume(5, 3, 2));

Functions can be declared in different ways. All three approaches create reusable code blocks.