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.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);
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);
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.
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();
- Declaration:
function greet(){ } - Invocation:
greet(); - Use meaningful camelCase names such as
calculateSum().
Parameters vs Arguments
| Parameter | Argument |
|---|---|
| Placeholder variable in the function definition. | Actual value supplied during the function call. |
function greetPerson(name) {
console.log("Hello, " + name + "!");
}
greetPerson("CSMC");
greetPerson("Monkeys");
Default parameters
function multiply(a, b = 1) {
console.log(a * b);
}
multiply(5);
multiply(5, 3);
multiply(5) uses the default b = 1 since no second argument was passed.
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));
return can be omitted โ cube above uses this implicit return.Spread (...) vs Rest (...)
| Spread Operator | Rest 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);
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);
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);
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
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();
Global scope
let globalVar = "I am global";
function showGlobal() {
console.log(globalVar);
}
showGlobal();
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.
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");
})();
() calls it right away โ nothing else in the file can reference this function by name.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);
Here n <= 0 is the base case. Without it, countdown would call itself forever and crash with a stack overflow.
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();
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();
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);
Async callback with setTimeout
setTimeout(function () {
console.log("This runs after 1000 ms");
}, 1000);
setTimeout doesn't pause the program; it schedules the callback and lets the rest of the code keep running in the meantime.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.