A function is a block of reusable code that performs a specific task.
Instead of repeating the same code, we write it once inside a function and call it when needed.
function greet() {
console.log("Hello, world!");
}
greet(); // Call the functionYou can pass values to a function using parameters (placeholders).
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice"); // Output: Hello, Alice
greet("Bob"); // Output: Hello, BobUse return to send a value back from the function.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8Once a return is hit, the function exits.
Functions can also be assigned to variables.
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 5)); // Output: 20A shorter way to write function expressions.
const square = (n) => {
return n * n;
};
console.log(square(6)); // Output: 36const square = n => n * n;You can set default values for parameters.
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Guest
greet("John"); // Output: Hello, JohnVariables defined inside a function are not accessible outside.
function sayHi() {
let message = "Hi!";
console.log(message); // OK
}
sayHi();
// console.log(message); // ❌ Error: message is not definedFunctions can be defined inside other functions.
function outer() {
function inner() {
console.log("Hello from inner");
}
inner();
}
outer(); // Output: Hello from innerA function without a name — used often in event handlers or callbacks.
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);A callback is a function passed as an argument to another function, to be executed later.
function greetUser(name, callback) {
console.log("Hi " + name);
callback();
}
function showMessage() {
console.log("Welcome to our site!");
}
greetUser("Alice", showMessage);A function that runs immediately after it's defined.
(function() {
console.log("IIFE runs instantly!");
})();Useful for:
| Feature | Statement | Notes |
|---|---|---|
| Function Declaration | function add() {} | Hoisted (can be used before defined) |
| Function Expression | const add = function() {} | Not hoisted |
| Arrow Function | const add = (a, b) => a + b | Short, modern syntax |
| Default Parameters | function(a = 1) {} | Sets fallback value |
| Return Value | return x * y | Sends result back |
| Callback Function | func(callback) | Used for async/events |
| IIFE | (function() {})(); | Runs immediately |
isEven(number) that returns true if the number is even, else false.greetUser(name, time) that returns "Good Morning/Evening, [name]" based on the time (AM/PM).