Functions
A reusable, named block of code that performs a specific task.
What is it?
As programs grow, you need the same task in several places: calculate a total, check an email, format a date. Instead of repeating that logic, wrap it in a function: a named block of code you can "call" whenever you need it.
A function can take inputs (parameters) and send back a result (with return).
Explain like I'm 10
A function is like a recipe. You give it ingredients (parameters), it follows the steps, and it hands back a finished dish (the return value). You can reuse it as often as you like.
Examples
Declaring and calling a function
function add(a, b) {
return a + b;
}
const result = add(2, 3);
console.log(result); // 5add takes two parameters, a and b, and returns their sum. Calling add(2, 3) runs that code with a = 2 and b = 3.
Arrow function shorthand
const add = (a, b) => a + b;Arrow functions are a shorter way to write simple functions, common in modern JavaScript.
How it works
When you call a function, JavaScript pauses the current line, runs the function's code with the arguments you passed, and, if there's a return, sends a value back to where it was called. Execution then continues from there.
Why does it exist?
Functions let you name a piece of logic once and reuse it anywhere. Code stays shorter, easier to test and easier to change: you fix a bug in one place instead of every copy.
When to use it
Write a function when you're about to repeat the same few lines, or when a chunk of code does one clear, nameable thing: checking an email, calculating a total, formatting a date.
When not to use it
Don't wrap a one-off single line in a function just because you can; it adds indirection with no benefit. And a function doing five unrelated things should usually be split into smaller, focused ones.
Common mistakes
Forgetting to
returna value and expecting the function to give one back automatically.Confusing a function's parameters (the placeholders) with arguments (the actual values passed in).
Writing functions that try to do too many unrelated things at once.
Practice exercises
- Easy:
Write a function
square(n)that returnsn * n. - Medium:
Write a function
isEven(n)that returnstrueorfalse. - Hard:
Write a function
average(numbers)that takes an array and returns the average value.
Interview questions
What's the difference between a parameter and an argument?
A parameter is the placeholder name in the function's definition (function add(a, b): a and b). An argument is the actual value passed at the call (add(2, 3): 2 and 3).
What happens if a function has no `return` statement?
It returns undefined when it reaches the end. Calling it doesn't throw, but any code using its "result" gets undefined.
What's the difference between a function declaration and an arrow function?
Besides shorter syntax, arrow functions have no own this, arguments or super, and can't be used with new. They take this from the surrounding scope. Regular functions get their own this (set by how they're called) and their own arguments object.
What's the difference between a function declaration and a function expression?
A declaration (function foo() {}) is hoisted with its full body, so you can call it before the line it's on. An expression (const foo = function () {}) is part of an assignment; the variable follows normal let/const/var hoisting, so the function isn't callable until that line runs.
Can a function have more than one `return` statement?
Yes, often one per if/else branch. The first one that runs ends the function; code after it doesn't run.
What happens if you call a function with fewer arguments than it has parameters?
The missing parameters are undefined (or their default value, if set). JavaScript doesn't complain about the count, unlike many statically typed languages.
What happens if you call a function with more arguments than it has declared parameters?
The extras are accepted without error but aren't bound to a named parameter. You can still reach them through the arguments object (in a regular function) or with a rest parameter (...args).
What is a default parameter, and when does its default value actually kick in?
A value set in the signature (function greet(name = "Guest")), used only when the argument is undefined, whether omitted or passed as undefined. Other falsy values like null or 0 don't trigger it.
What is a rest parameter, and how does it differ from the old `arguments` object?
...args as the last parameter collects remaining arguments into a real array (function sum(...nums) { ... }), so .map() and .reduce() work directly. The older arguments object exists automatically in every regular function, but it's only array-like (no array methods) and doesn't exist in arrow functions.
Are function declarations hoisted? What about function expressions?
Declarations are hoisted fully, body included, so they work before their line. Function expressions (and arrow functions) aren't: only their variable is hoisted, by its own rules (undefined for var, TDZ for let/const). Calling one early gives undefined is not a function or a TDZ ReferenceError.
What is a callback function?
A function passed into another function to be called later, often when an operation finishes or an event happens. Examples: the click handler given to addEventListener, or the function given to .map() that runs once per element.
What is a higher-order function?
A function that takes a function as an argument, returns one, or both. .map(), .filter() and .reduce() are higher-order because each takes a callback.
What is a closure, in plain terms?
A function that remembers the variables of the scope it was defined in, even after that scope has finished. A function returned from another function can keep reading and updating variables from a call that already ended.
What is recursion, and what must a recursive function have to avoid infinite recursion?
A function that calls itself on a smaller version of the problem until it reaches a base case it can answer directly. Without a base case, it calls itself until the call stack overflows and throws RangeError: Maximum call stack size exceeded.
What is an IIFE (Immediately Invoked Function Expression), and why would you use one?
A function expression defined and called in one statement, usually (function () { ... })();. It creates a private scope that runs once. Before let/const/modules, it was used to avoid leaking variables into the global scope; today it's rarer, but still used for one-off setup code.
Can a function be assigned to a variable, passed as an argument, or returned from another function? What does that make functions in JavaScript?
Yes to all three. That makes functions "first-class citizens" (first-class values): you can store, pass and return them like any number, string or object. This is what makes callbacks, higher-order functions and closures possible.
What's the practical difference between `function foo() {}` and `const foo = function () {}`?
Both create an equivalent function. The first is a hoisted declaration usable before its line; the second is bound to a const and unusable until that line runs. Also, a declaration always has the name foo in stack traces, while an anonymous expression only gets a name inferred from the variable it's first assigned to.
Why don't arrow functions have their own `this`? Where do they get it from instead?
They were designed without their own this. Instead they look this up like any variable: from the nearest enclosing non-arrow function (or the module/global scope) where the arrow was defined, not where it's called.
Why can't arrow functions be used as constructors with `new`?
new needs the function to create a fresh this bound to the new object. Arrow functions never create their own this, so JavaScript throws TypeError: X is not a constructor.
What is a pure function? Why are pure functions easier to test and reason about?
A function that always returns the same output for the same inputs and has no side effects: no mutating arguments, no global state, no I/O. You can test it in isolation (call it, check the output, no setup) and reason about it from its inputs alone.
What does it mean for JavaScript functions to be 'first-class citizens'?
Functions are regular values, not a special category. You can store them in variables, arrays or object properties, pass them as arguments and return them, just like numbers or strings.
What's the difference between a function's arity and the number of arguments it's actually called with?
Arity is the number of parameters a function declares (function add(a, b) {} has arity 2). The number of arguments is set per call and can be more, fewer or equal; JavaScript doesn't enforce a match.
Are extra arguments passed beyond a function's declared parameters lost?
No. They're not assigned to a named parameter, but you can reach them through the arguments object in a regular function, or capture them with a rest parameter (...rest).
What is currying, and how does it relate to closures?
Turning a multi-argument function into a chain of one-argument functions, e.g. add(a)(b)(c) instead of add(a, b, c). It relies on closures: each returned function keeps access to the arguments already given to the outer ones.
Why can't arrow functions have their own `arguments` object?
Same design as this: arrow functions don't bind their own arguments, so using it inside one looks it up from the nearest enclosing regular function. With no enclosing regular function, it throws a ReferenceError.
Output-prediction: what does `function outer() { let count = 0; return function () { count++; return count; }; } const counter = outer(); console.log(counter()); console.log(counter());` log?
It logs 1 then 2. outer() runs once and returns the inner function, which keeps a closure over that call's count. Each counter() call updates the same count instead of starting fresh.
Output-prediction: what does `sayHi(); function sayHi() { console.log("hi"); }` do?
It logs "hi". Function declarations are hoisted with their whole body, so sayHi is callable before its line.
Output-prediction: what does `sayBye(); const sayBye = function () { console.log("bye"); };` do?
It throws ReferenceError: Cannot access 'sayBye' before initialization. sayBye is a const, so it's in the Temporal Dead Zone until its line runs. Assigning a function doesn't change const hoisting.
Output-prediction: given `const obj = { name: "Ana", greet() { console.log(this.name); }, greetArrow: () => console.log(this.name) };`, what does `obj.greet()` log compared to `obj.greetArrow()`?
obj.greet() logs "Ana": a regular method's this comes from the call, and obj.greet() sets this to obj. obj.greetArrow() doesn't log "Ana": an arrow function takes this from the scope around the object literal, never obj, however it's called.
Output-prediction: given `function add(a, b = 10) { return a + b; }`, what do `add(5)`, `add(5, undefined)`, and `add(5, null)` each return?
15, 15, then 5. The default applies only when the argument is undefined, whether omitted or passed explicitly. null is a real value, so b stays null, and 5 + null treats null as 0, giving 5.