JavaScript Fundamentals
JavaScript Functions
JavaScript Functions
Section titled “JavaScript Functions”Functions are reusable blocks of code that perform specific tasks.
Function Declaration
Section titled “Function Declaration”function greet(name) { return `Hello, ${name}!`;}
greet("Alice"); // "Hello, Alice!"Function Expression
Section titled “Function Expression”const greet = function(name) { return `Hello, ${name}!`;};Arrow Functions
Section titled “Arrow Functions”// Full syntaxconst greet = (name) => { return `Hello, ${name}!`;};
// Short syntax (implicit return)const greet = name => `Hello, ${name}!`;
// Multiple parametersconst add = (a, b) => a + b;Parameters
Section titled “Parameters”Default Parameters
Section titled “Default Parameters”function greet(name = "World") { return `Hello, ${name}!`;}
greet(); // "Hello, World!"greet("Alice"); // "Hello, Alice!"Rest Parameters
Section titled “Rest Parameters”function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0);}
sum(1, 2, 3, 4); // 10Closures
Section titled “Closures”function createCounter() { let count = 0; return { increment: () => ++count, decrement: () => --count, getCount: () => count };}
const counter = createCounter();counter.increment(); // 1counter.increment(); // 2counter.getCount(); // 2Higher-Order Functions
Section titled “Higher-Order Functions”// Function that takes a function as argumentfunction repeat(n, action) { for (let i = 0; i < n; i++) { action(i); }}
repeat(3, console.log); // 0, 1, 2
// Function that returns a functionfunction multiplier(factor) { return num => num * factor;}
const double = multiplier(2);double(5); // 10