JavaScript Functions
A function is a block of code designed to perform a particular task. Functions are reusable.
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("World")); // "Hello, World!"
Function Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
Arrow Functions (ES6+)
// Regular arrow function
const greet = (name) => {
return `Hello, ${name}!`;
};
// Concise (implicit return)
const greet = name => `Hello, ${name}!`;
// No parameters
const sayHi = () => "Hi!";
// Multiple params
const add = (a, b) => a + b;
Default Parameters
function greet(name = "World", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
greet(); // "Hello, World!"
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hey"); // "Hey, Bob!"
Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4, 5); // 15
Higher-Order Functions
Functions that take other functions as arguments or return functions:
// Map, Filter, Reduce
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]
const total = numbers.reduce((sum, n) => sum + n, 0);
// 15
// Sort with callback
const words = ["banana", "apple", "cherry"];
words.sort((a, b) => a.localeCompare(b));
// ["apple", "banana", "cherry"]
Closures
function makeCounter(initial = 0) {
let count = initial;
return {
increment: () => ++count,
decrement: () => --count,
value: () => count,
};
}
const counter = makeCounter(10);
counter.increment(); // 11
counter.increment(); // 12
counter.decrement(); // 11
counter.value(); // 11
Async Functions
// Async/Await
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
} catch (error) {
console.error("Failed to fetch user:", error);
throw error;
}
}
// Usage
const user = await fetchUser(42);