Without functions, developers repeat the same logic multiple times. Functions allow code reuse by writing the logic once and calling it whenever required.

๐Ÿ’ก Key idea: write the logic once, call it many times.
๐Ÿ”ต 1

Why Functions Exist

Without a function

let width1 = 5, height1 = 10;
let area1 = width1 * height1;
console.log(area1);

let width2 = 7, height2 = 3;
let area2 = width2 * height2;
console.log(area2);
โ€บ50 21

Using a function

function calculateArea(width, height) {
    return width * height;
}

let areaOne = calculateArea(5, 10);
let areaTwo = calculateArea(7, 3);
console.log(areaOne);
console.log(areaTwo);
โ€บ50 21

Same result, but the multiplication logic is written once and reused โ€” if you needed to change how area is calculated, you'd only edit one place.

๐ŸŸฃ 2

Declaring and Calling a Function

A function declaration defines the function. Nothing happens until it is invoked (called).

function greet() {
    console.log("Hello, JavaScript!");
}

greet();
โ€บHello, JavaScript!
  • Declaration: function greet(){ }
  • Invocation: greet();
  • Use meaningful camelCase names such as calculateSum().
๐ŸŸข 3

Parameters vs Arguments

ParameterArgument
Placeholder variable in the function definition.Actual value supplied during the function call.
function greetPerson(name) {
    console.log("Hello, " + name + "!");
}

greetPerson("CSMC");
greetPerson("Monkeys");
โ€บHello, CSMC! Hello, Monkeys!

Default parameters

function multiply(a, b = 1) {
    console.log(a * b);
}

multiply(5);
multiply(5, 3);
โ€บ5 15

multiply(5) uses the default b = 1 since no second argument was passed.

๐ŸŸ  4

Arrow Functions

Arrow functions provide a shorter syntax for writing functions.

const square = (x) => {
    return x * x;
};
console.log(square(4));

const cube = x => x * x * x;
console.log(cube(3));
โ€บ16 27
๐Ÿ’ก If only one expression exists, braces and return can be omitted โ€” cube above uses this implicit return.
๐Ÿฉท 5

Spread (...) vs Rest (...)

Spread OperatorRest Operator
Expands an array into individual arguments.Collects multiple arguments into a single array.

Spread โ€” expanding an array into arguments

function sumThree(a, b, c) {
    console.log(a + b + c);
}

const numbers = [1, 2, 3];
sumThree(...numbers);
โ€บ6

Rest โ€” collecting arguments into an array

function sumAll(...values) {
    let total = 0;
    for (let value of values)
        total += value;
    console.log(total);
}

sumAll(1, 2);
sumAll(5, 10, 15);
โ€บ3 30
๐Ÿ”ท 6

Returning Values

The return statement sends a value back to the caller and immediately stops execution.

function addNumbers(x, y) {
    return x + y;
}

let result = addNumbers(10, 5);
console.log(result);
โ€บ15
โšช 7

Scope โ€” Where Variables Live

Variables declared inside a function are local and cannot be accessed outside the function.

function showLocal() {
    let localVar = "I am local";
    console.log(localVar);
}

showLocal();
// console.log(localVar);   // โŒ ReferenceError โ€” localVar doesn't exist here
โ€บI am local

var (function-scoped) vs let (block-scoped)

function testScope() {
    if (true) {
        var usingVar = "function-scoped";
        let usingLet = "block-scoped";
    }
    console.log(usingVar);
    // console.log(usingLet);   // โŒ ReferenceError โ€” usingLet is block-scoped to the if
}
testScope();
โ€บfunction-scoped

Global scope

let globalVar = "I am global";

function showGlobal() {
    console.log(globalVar);
}
showGlobal();
โ€บI am global

Functions can always read variables declared outside them (global scope) โ€” the restriction only goes one direction: outer code can't reach into a function's local variables.

๐Ÿ”ด 8

IIFE (Immediately Invoked Function Expression)

An IIFE executes immediately after it is defined and helps avoid polluting the global scope.

(function () {
    console.log("This runs immediately");
})();
โ€บThis runs immediately
โ„น๏ธ The wrapping parentheses turn the function into an expression, and the trailing () calls it right away โ€” nothing else in the file can reference this function by name.
๐ŸŸก 9

Recursion

A recursive function calls itself. Every recursive function must contain a base case so it eventually stops.

function countdown(n) {
    if (n <= 0) {
        console.log("Done!");
    } else {
        console.log(n);
        countdown(n - 1);
    }
}

countdown(3);
โ€บ3 2 1 Done!

Here n <= 0 is the base case. Without it, countdown would call itself forever and crash with a stack overflow.

๐ŸŸข 10

Nested Functions

A function declared inside another function can access variables from its outer function.

function outer() {
    let outerVar = "from outer";

    function inner() {
        console.log("Inner sees: " + outerVar);
    }

    inner();
}

outer();
โ€บInner sees: from outer
๐Ÿ”ต 11

Anonymous Functions

An anonymous function has no name and is usually stored in a variable.

const greetAnon = function () {
    console.log("Hello from anonymous function");
};

greetAnon();
โ€บHello from anonymous function
๐Ÿฉท 12

Callback Functions

A callback is a function passed to another function to be executed later.

function doTwice(action) {
    action();
    action();
}

function sayHello() {
    console.log("Hello");
}

doTwice(sayHello);
โ€บHello Hello

Async callback with setTimeout

setTimeout(function () {
    console.log("This runs after 1000 ms");
}, 1000);
โ€บThis runs after 1000 ms
โฑ๏ธ This output appears roughly 1 second later than everything before it โ€” setTimeout doesn't pause the program; it schedules the callback and lets the rest of the code keep running in the meantime.
๐Ÿ“‹ Summary

Chapter Summary

  • Functions improve code reuse and readability.
  • Understand declarations, invocations, parameters, and arguments.
  • Use arrow functions for concise syntax.
  • Know the difference between spread and rest operators.
  • Understand return values and variable scope.
  • Learn advanced concepts: IIFE, recursion, nested functions, anonymous functions, and callbacks.