Skip to content

Functions

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).

// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const greet2 = function(name) {
return `Hello, ${name}!`;
};
// Arrow function
const greet3 = (name) => `Hello, ${name}!`;
// Multiple parameters
const add = (a, b) => a + b;
// Default parameters
const greet4 = (name = "Guest") => `Hello, ${name}!`;
// Rest parameters
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3, 4)); // 10

Forgetting that arrow functions don’t have their own this:

// BAD - arrow function in method
const obj = {
name: "Alice",
greet: () => {
console.log(`Hello, ${this.name}`); // this is undefined!
}
};
// GOOD - regular function in method
const obj2 = {
name: "Alice",
greet() {
console.log(`Hello, ${this.name}`); // Works!
}
};

Fix: Use regular functions for object methods; use arrow functions for callbacks.

  1. Convert this to an arrow function: function double(x) { return x * 2; }

    Answer`const double = (x) => x * 2;` or `const double = x => x * 2;`
  2. What’s the output? ((x) => x * 2)(5)

    Answer`10` - this is an immediately invoked function expression (IIFE)
  3. How do you create a function that accepts any number of arguments?

    AnswerUse rest parameters: `const fn = (...args) => { ... }`