Functions
Master JavaScript functions and their different forms
Functions
Functions are reusable blocks of code that perform specific tasks.
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
Function Expression
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // 8
Arrow Functions (ES6)
// Basic arrow function
const multiply = (a, b) => {
return a * b;
};
// Shorthand for single expression
const square = x => x * x;
// No parameters
const sayHello = () => "Hello!";
// Single parameter (parentheses optional)
const double = x => x * 2;
Parameters and Arguments
// Default parameters
function greetWithDefault(name = "World") {
return `Hello, ${name}!`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Destructuring parameters
function createUser({name, age, email}) {
return {
id: Date.now(),
name,
age,
email
};
}
Higher-Order Functions
// Function that returns a function
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
console.log(double(5)); // 10
// Function that takes a function as parameter
function processArray(arr, callback) {
return arr.map(callback);
}
const numbers = [1, 2, 3, 4];
const doubled = processArray(numbers, x => x * 2);
Scope and Closures
function outerFunction(x) {
// Outer scope
function innerFunction(y) {
// Inner scope - has access to outer scope
return x + y;
}
return innerFunction;
}
const addFive = outerFunction(5);
console.log(addFive(3)); // 8
Functions are the building blocks of JavaScript applications!