Functions are reusable blocks of code that perform a specific task. They help in breaking programs into smaller, manageable chunks and improve code reusability.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Amina"); // Output: Hello, Amina!
A function can also be stored in a variable.
const greet = function(name) {
return `Hi, ${name}`;
};
console.log(greet("Ali")); // Hi, Ali
Introduced in ES6, arrow functions are a shorter syntax for writing functions.
const square = num => num * num;
console.log(square(4)); // 16
function add(x, y) { // x and y are parameters
return x + y;
}
add(5, 3); // 5 and 3 are arguments
The return statement ends function execution and returns a
value.
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5); // 20
ES6 allows you to assign default values to parameters.
function greet(name = "Guest") {
console.log("Welcome, " + name);
}
greet(); // Welcome, Guest
Allows you to handle an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num);
}
console.log(sum(1, 2, 3, 4)); // 10
A callback is a function passed as an argument to another function.
function processUser(name, callback) {
callback(name);
}
function sayHello(user) {
console.log("Hello " + user);
}
processUser("Zahra", sayHello); // Hello Zahra
Functions without a name. Often used in expressions or callbacks.
setTimeout(function() {
console.log("Hello after 1 second");
}, 1000);
Runs immediately after being defined.
(function() {
console.log("This runs instantly!");
})();
Function declarations are hoisted to the top of their scope.
greet();
function greet() {
console.log("Hi!");
} // This works!
function outer() {
let outerVar = "I'm outside!";
function inner() {
console.log(outerVar); // Accesses outer scope
}
return inner;
}
const closureFunc = outer();
closureFunc(); // I'm outside!
This is a closure — inner function remembers variables from its parent scope.
function validateEmail(email) {
return email.includes("@");
}
function calculateDiscount(price, percent) {
return price - (price * percent / 100);
}
const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // [2, 4, 6]