Functions
📖 Concept
Functions are reusable blocks of code that perform a specific task. They are the backbone of JavaScript.
Function Declaration — Hoisted, can be called before definition. Uses the function keyword.
Function Expression — Stored in a variable. NOT hoisted.
Arrow Functions — Concise syntax (=>). No own this, arguments, or super. Cannot be used as constructors.
Functions are first-class citizens in JS — they can be assigned to variables, passed as arguments, and returned from other functions.
Parameters vs Arguments: Parameters are in the definition, arguments are what you pass in.
🏠 Real-world analogy: A function is like a vending machine — you put in inputs (coins), it does its job internally, and gives you an output (snack). You don't need to know the internal mechanics.
💻 Code Example
1// Function Declaration (hoisted)2console.log(greet("Alice")); // Works! Declarations are hoisted3function greet(name) {4 return `Hello, ${name}!`;5}67// Function Expression (NOT hoisted)8// console.log(add(2, 3)); // ❌ ReferenceError9const add = function(a, b) {10 return a + b;11};1213// Arrow Functions14const multiply = (a, b) => a * b; // Implicit return15const square = x => x * x; // Single param, no parens needed16const getUser = () => ({ name: "Alice" }); // Return object: wrap in ()1718// Default parameters19function createUser(name, role = "user", active = true) {20 return { name, role, active };21}22console.log(createUser("Bob")); // { name: "Bob", role: "user", active: true }2324// Rest parameters25function sum(...numbers) {26 return numbers.reduce((total, n) => total + n, 0);27}28console.log(sum(1, 2, 3, 4)); // 102930// Functions as first-class citizens31const operations = { add, multiply, square };32const apply = (fn, ...args) => fn(...args);33console.log(apply(add, 5, 3)); // 83435// IIFE (Immediately Invoked Function Expression)36(function() {37 const secret = "hidden";38 console.log(secret); // "hidden"39})();40// console.log(secret); // ❌ ReferenceError
🏋️ Practice Exercise
Mini Exercise:
- Write a function that takes any number of arguments and returns the largest
- Convert a regular function to an arrow function and vice versa
- Write a function
composethat takes two functions and returns their composition - Write a function that returns a function (closure preview!)
⚠️ Common Mistakes
Forgetting that arrow functions don't have their own
this— they inherit from the enclosing scopeTrying to return an object from an arrow function without wrapping in parentheses:
() => { name: 'a' }returnsundefined!Using
argumentsobject in arrow functions — it doesn't exist; use rest parameters insteadNot understanding that function expressions are NOT hoisted, while declarations ARE
Overusing arrow functions — don't use them for object methods or when you need
this
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Functions. Login to unlock this feature.