Skip to main content

4. Functions in JavaScript

Functions are the building blocks of JavaScript. They let you organize code, reuse logic, and create powerful abstractions. Mastering functions unlocks the full power of the language.


4.1 Function Fundamentals

What is a Function?

A function is a reusable block of code that performs a specific task.

function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice'));

Parameters vs Arguments

  • Parameter: Variable in the function definition (name above)
  • Argument: Value passed to the function ('Alice' above)

Hoisting

Function declarations are hoisted (can be called before they appear):

sayHi();
function sayHi() { console.log('Hi!'); }

Function expressions are NOT hoisted:

// greet(); // Error
const greet = function() { ... };

Function Scope

Variables declared inside a function are not accessible outside.


4.2 Parameter Types

  • Required: Must be provided
  • Default: Has a fallback value
  • Rest: Collects extra arguments
  • Destructured: Unpacks from objects/arrays
function show(a, b = 2, ...rest) {
console.log(a, b, rest);
}
show(1); // 1 2 []
show(1, 3, 4, 5); // 1 3 [4, 5]

function printUser({name, age}) {
console.log(name, age);
}
printUser({name: 'Sam', age: 30});

4.3 Argument Types

  • Positional: Order matters
  • Spread: Expand arrays/objects
  • Default: Uses fallback
function add(x, y) { return x + y; }
let nums = [2, 3];
console.log(add(...nums)); // 5

4.4 Function Types

  • Classic Function
    function sum(a, b) { return a + b; }
  • Arrow Function
    const double = x => x * 2;
  • Anonymous Function
    setTimeout(function() { console.log('Hi'); }, 1000);
  • Higher Order Function (takes/returns functions)
    function repeat(fn, n) { for (let i = 0; i < n; i++) fn(); }
  • Callback Function
    [1,2,3].forEach(function(x) { console.log(x); });
  • First Class Function Functions can be assigned, passed, and returned like any value.
  • Pure & Impure Functions Pure: No side effects, same output for same input.

4.5 Advanced Concepts

Nested Functions

Functions inside functions:

function outer() {
function inner() { console.log('Inner!'); }
inner();
}

Scope Chain

Inner functions access variables from outer scopes.

Closures

A closure is a function that remembers its outer variables:

function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
let counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

IIFE (Immediately Invoked Function Expression)

(function() {
console.log('Runs immediately!');
})();

Next: Arrays & Objects