Functions & Timers
A function is a reusable block of code with a name. Call it with parentheses and arguments.
Function Declaration
A function is a reusable block of code with a name. Call it with parentheses and arguments.
Real-life example: A function is a recipe card — write once, cook many times.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Asha")); // "Hello, Asha!"Function Expression
Store a function in a variable. Often used when passing functions as values.
Real-life example: Same recipe card, but kept inside a folder labeled "myRecipe" instead of pinned on the wall.
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3)); // 5Arrow Functions
Short syntax: (params) => expression or => { statements }. Great for small callbacks.
Real-life example: A quick sticky note instead of a full recipe card — same job, less writing.
const double = (n) => n * 2;
const sum = (a, b) => {
return a + b;
};
console.log(double(5)); // 10Parameters, Return & Default Parameters
Parameters are inputs. return sends a value back. Default parameters fill in when an argument is missing.
Real-life example: A chai order — size defaults to "regular" if you say nothing.
function makeChai(cups = 1, sugar = true) {
return `${cups} cup(s), sugar: ${sugar}`;
}
console.log(makeChai()); // 1 cup(s), sugar: true
console.log(makeChai(2, false));setTimeout and setInterval
setTimeout runs code once after a delay (milliseconds). setInterval repeats on a timer.
Real-life example: setTimeout — oven timer rings once. setInterval — a clock ticking every second.
// Run once after 2 seconds
const onceId = setTimeout(() => {
console.log("2 seconds passed");
}, 2000);
// Run every 1 second
const repeatId = setInterval(() => {
console.log("tick");
}, 1000);clearTimeout and clearInterval
Save the timer id and pass it to clearTimeout or clearInterval to stop future runs.
Real-life example: Cancel the oven alarm before it rings if you already removed the cake.
const id = setInterval(() => console.log("hi"), 500);
clearInterval(id); // stops the repeating timer