Functions
Functions
Section titled βFunctionsβWhat it means
Section titled βWhat it meansβFunctions are reusable blocks of code. JavaScript supports function declarations, function expressions, and arrow functions. Functions can be assigned to variables, passed as arguments, and returned from other functions (first-class functions).
Examples
Section titled βExamplesβ// Function declarationfunction greet(name) { return `Hello, ${name}!`;}
// Function expressionconst greet2 = function(name) { return `Hello, ${name}!`;};
// Arrow functionconst greet3 = (name) => `Hello, ${name}!`;
// Multiple parametersconst add = (a, b) => a + b;
// Default parametersconst greet4 = (name = "Guest") => `Hello, ${name}!`;
// Rest parametersconst sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3, 4)); // 10Common mistake
Section titled βCommon mistakeβForgetting that arrow functions donβt have their own this:
// BAD - arrow function in methodconst obj = { name: "Alice", greet: () => { console.log(`Hello, ${this.name}`); // this is undefined! }};
// GOOD - regular function in methodconst obj2 = { name: "Alice", greet() { console.log(`Hello, ${this.name}`); // Works! }};Fix: Use regular functions for object methods; use arrow functions for callbacks.
Quick practice
Section titled βQuick practiceβ-
Convert this to an arrow function:
function double(x) { return x * 2; }Answer
`const double = (x) => x * 2;` or `const double = x => x * 2;` -
Whatβs the output?
((x) => x * 2)(5)Answer
`10` - this is an immediately invoked function expression (IIFE) -
How do you create a function that accepts any number of arguments?
Answer
Use rest parameters: `const fn = (...args) => { ... }`