Introduction & Syntax
Functions · Study material
Functions are the building blocks of every JavaScript program – and JavaScript treats them as first-class values: you can store them in variables, pass them to other functions and return them. Interviews test the details: the three ways to define a function and how each is hoisted, when a default parameter applies, rest parameters vs the arguments object, what fn.length counts, why a function without return gives undefined, and whether JavaScript passes objects by reference. This topic answers all of them. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
Three ways to define a function
| Declaration | Expression | Arrow function | |
|---|---|---|---|
| Syntax | function f(x) { … } | const f = function (x) { … }; | const f = (x) => …; |
| Hoisted | yes, with its body | only the variable (var: undefined, const/let: TDZ) | only the variable |
Own this / arguments | yes | yes | no – uses the surrounding ones |
Can be used with new | yes | yes | no |
Every function has a name (inferred from the variable for anonymous expressions and arrows) and a length. The Arrow Functions topic covers this in detail.
console.log(square(4)); // declarations are hoisted with their body
function square(n) { // 1. function declaration
return n * n;
}
const cube = function (n) { return n ** 3; }; // 2. function expression
const double = (n) => n * 2; // 3. arrow function (implicit return)
console.log(cube(2), double(21));
console.log(typeof square, square.name, cube.name, double.name);
16 8 42 function square cube double
Parameters, arguments and defaults
Parameters are the names in the definition; arguments are the values passed in a call. JavaScript never checks the count: missing arguments are undefined and extra ones are ignored (but still visible in arguments). A default parameter is used when the argument is missing or explicitly undefined – null, 0 and "" are real values and keep the default from applying. Defaults are evaluated at every call and may refer to earlier parameters.
// A default is used when the argument is missing or undefined – not when it is null
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet());
console.log(greet("Asha"));
console.log(greet(undefined, "Hi"));
console.log(greet(null));
Hello, Guest! Hello, Asha! Hi, Guest! Hello, null!
Rest parameters and arguments
A rest parameter ...nums collects the remaining arguments into a real array; it must be the last parameter. The older arguments object is array-like (no map or reduce) and does not exist in arrow functions. Spread syntax f(...array) does the opposite of rest: it turns an array into separate arguments.
// Rest parameter: collects the remaining arguments into a real array
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(), sum(1, 2, 3), sum(...[10, 20])); // spread turns an array into arguments
// The older arguments object: array-like, not available in arrow functions
function oldStyle() {
return `${arguments.length} args, first: ${arguments[0]}`;
}
console.log(oldStyle("a", "b"));
// fn.length counts parameters before the first default or rest parameter
console.log(sum.length, ((a, b = 2, ...c) => 0).length);
0 6 30 2 args, first: a 0 1
Return values
return ends the function and sends a value back. A function that ends without return (or with a bare return;) returns undefined. Several return statements – early returns for special cases – keep code flat.
function noReturn() {
const x = 1 + 1; // computed, but never returned
}
function earlyReturn(n) {
if (n < 0) return "negative"; // return ends the function immediately
return n === 0 ? "zero" : "positive";
}
console.log(noReturn());
console.log(earlyReturn(-5), earlyReturn(0), earlyReturn(8));
undefined negative zero positive
First-class and higher-order functions
A higher-order function takes a function as an argument (a callback), returns a function, or both. map, filter, setTimeout and event listeners all take callbacks; factories such as multiplier(3) return new functions that remember their arguments through closures.
// Functions are values: store them, pass them, return them
const apply = (fn, x) => fn(x); // a higher-order function takes a function…
const ops = { half: (n) => n / 2, negate: (n) => -n };
console.log(apply(ops.half, 9), apply(ops.negate, 4));
function multiplier(factor) { // …or returns one
return (n) => n * factor;
}
const triple = multiplier(3);
console.log(triple(7), [1, 2, 3].map(multiplier(10)));
4.5 -4 21 [ 10, 20, 30 ]
IIFE – Immediately Invoked Function Expression
(function () { … })() defines a function and calls it immediately. Before modules and block scope, it was the standard way to create private variables and avoid polluting the global scope; you will still see it in older code and in interview questions.
// IIFE: defined and called at once – its variables stay private
const counter = (function () {
let count = 0;
return () => ++count;
})();
counter();
counter();
console.log(counter());
console.log(typeof count); // count is not visible outside
3 undefined
Pass by value – "pass by sharing"
JavaScript always passes a copy of the value. For primitives that is the value itself; for objects it is a copy of the reference. So a function can mutate the caller's object or array, but reassigning the parameter never affects the caller.
// Arguments are copied. For objects the copy is a reference: mutation is shared, reassignment is not.
function addItem(cart, item) {
cart.push(item); // changes the caller's array
cart = ["replaced"]; // only changes the local parameter
return cart;
}
const myCart = ["pen"];
const returned = addItem(myCart, "book");
console.log(myCart, returned);
[ 'pen', 'book' ] [ 'replaced' ]
Common mistakes
- Forgetting return – the function computes the value and returns undefined.
- Calling a function expression before its line – TypeError (var) or ReferenceError (let/const).
- Using || for defaults – 0 and "" are replaced; use default parameters or ??.
- Returning an object from an arrow with { } – the braces are a block; wrap the object in parentheses.
- Passing fn() instead of fn as a callback – you pass the result, not the function.
- Mutating arguments by accident – sort and splice change the caller's array.
- Recursion without a base case – RangeError: Maximum call stack size exceeded.
Key points to remember
- Declarations are hoisted with their body; expressions and arrows are not.
- Missing arguments are undefined; extra arguments are ignored.
- Defaults apply for undefined only and are evaluated at each call.
- Rest must be last; arguments does not exist in arrow functions.
- No return → undefined.
- Functions are values: callbacks, higher-order functions and factories.
- Objects are passed as copied references: mutation shows, reassignment does not.
Frequently asked questions
Declaration or arrow function – which should I use?
Arrow functions for short callbacks and functions that should use the surrounding this; declarations for named top-level functions (hoisting lets you call them before they are defined) and for methods that need their own this.
Does JavaScript support function overloading?
No. A second declaration with the same name replaces the first. Use default parameters, rest parameters or an options object, and check arguments inside the function.
Is JavaScript pass by reference?
No – it is pass by value, where the value of an object variable is a reference. That is why mutation is visible to the caller but reassignment is not.
Where can I learn more?
Read JavaScript Functions and Higher-Order Functions in the JavaScript tutorial, then practise with the exercises below.