JavaScriptEasy
What are default parameters?
Default parameters let you give a function parameter a fallback value that is used when the argument is missing or explicitly undefined.
How they behave
- Defaults apply only for
undefined. Passingnull,0,falseor""keeps that value. - Defaults are evaluated at call time, every time.
function f(list = [])gets a new array on each call, which avoids the shared-default bug some other languages have. - A default can use earlier parameters:
function range(start, end = start + 10). - A default can call a function:
function save(id = crypto.randomUUID()). - Parameters with defaults (and everything after them) are not counted in
fn.length.
Combine with destructuring
function connect({ host = "localhost", port = 5432 } = {}) gives each option a default and makes the whole options object optional.
Required parameters
A neat trick: function f(id = required("id")) where required throws. The error only happens when the argument is missing.
Before ES2015
Code used x = x || defaultValue, which wrongly replaced 0, "" and false. Default parameters (or ??) fix that.
Code example
js
1function greet(name = "friend", greeting = `Hello`) {2 return `${greeting}, ${name}!`;3}4console.log(greet()); // Hello, friend!5console.log(greet("Ada")); // Hello, Ada!6console.log(greet(undefined, "Hi")); // Hi, friend!7console.log(greet(null)); // Hello, null! <- null is a real value89// Evaluated on every call: no shared array between calls10function addItem(item, list = []) {11 list.push(item);12 return list;13}14console.log(addItem("a"), addItem("b")); // ["a"] ["b"]1516// Defaults can use earlier parameters17const range = (start, end = start + 3) => Array.from({ length: end - start }, (_, i) => start + i);18console.log(range(5)); // [5, 6, 7]1920// Required parameter pattern21const required = (name) => {22 throw new Error(`${name} is required`);23};24function fetchUser(id = required("id")) {25 return { id };26}27try {28 fetchUser();29} catch (e) {30 console.log(e.message); // id is required31}3233console.log(greet.length); // 0 (params with defaults are not counted)
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.