JavaScript Default Parameters
Table of Contents + −
In the previous lesson, we learned how to build strings cleanly with template literals. Now let’s look at default parameters, which let a function fill in a value when no argument is passed.
🎯 What are Default Parameters?
A default parameter is a fallback value that a function uses when you call it without that argument. You set it right in the function’s parameter list with an equals sign.
function greet(name = "Guest") { console.log(`Hello, ${name}!`);}
greet("Alex"); // Hello, Alex!greet(); // Hello, Guest!Let’s walk through what this code does:
name = "Guest"sets"Guest"as the fallback for thenameparameter, used only when no argument is passed.greet("Alex")passes a value, sonameis"Alex"and we printHello, Alex!.greet()passes nothing, sonamefalls back to"Guest"and we printHello, Guest!.
🕰️ The Old Way vs the Modern Way
Before default parameters existed, you had to check for a missing value inside the function and set the fallback yourself. This worked but added an extra line of clutter.
// ❌ The old way: checking inside the functionfunction greet(name) { name = name || "Guest"; console.log(`Hello, ${name}!`);}Here is what each line does in the old approach:
function greet(name)takesnamewith no fallback built in.name = name || "Guest"reassignsnameto"Guest"whenever the passed value is falsy.console.log(...)then prints the greeting using whatevernameended up as.
Default parameters move that fallback into the parameter list, so the function body stays focused on its real job.
// ✅ The modern way: a default parameterfunction greet(name = "Guest") { console.log(`Hello, ${name}!`);}The modern version folds the fallback into the signature:
name = "Guest"handles the missing value right where the parameter is declared.- The body now only prints the greeting, with no extra check cluttering it.
🚫 Defaults Only Apply for undefined
A default value kicks in only when the argument is undefined, which happens when you pass nothing at all. It does not apply for null, 0, "", or any other falsy value.
function greet(name = "Guest") { console.log(`Hello, ${name}!`);}
greet(); // Hello, Guest! (undefined → default used)greet(undefined); // Hello, Guest! (undefined → default used)greet(null); // Hello, null! (null is NOT undefined)greet(""); // Hello, ! (empty string is a real value)Let’s compare each call:
greet()passes nothing, sonameisundefinedand the default"Guest"is used.greet(undefined)passesundefinedexplicitly, which also triggers the default.greet(null)passesnull, a real value, so the default is skipped and we printnull.greet("")passes an empty string, also a real value, so the default is skipped.
null is not undefined
Default parameters trigger only on undefined. If you pass null or 0, the
function treats it as a real value and skips the default.
🔗 Defaults Can Reference Earlier Parameters
A default value can use the values of parameters that come before it. This lets a later parameter build on an earlier one.
function createUser(name, role = "member", label = `${name} (${role})`) { console.log(label);}
createUser("Alex"); // Alex (member)createUser("Sam", "admin"); // Sam (admin)Here is how the defaults chain together:
role = "member"givesrolea fallback when no second argument is passed.label = `${name} (${role})`builds its default from the earliernameandroleparameters.createUser("Alex")fills onlyname, soroledefaults to"member"andlabelbecomesAlex (member).createUser("Sam", "admin")fillsnameandrole, solabelbecomesSam (admin).
Here label defaults to a string built from name and role. Note that the order matters: a parameter can only reference ones defined to its left.
🛠️ A Practical Example
Default parameters shine when a function has an optional setting. Imagine a function that formats a price and lets the caller choose a currency symbol, but uses a sensible default.
function formatPrice(amount, symbol = "$") { return `${symbol}${amount.toFixed(2)}`;}
console.log(formatPrice(19.5)); // $19.50console.log(formatPrice(19.5, "€")); // €19.50Let’s break down this example:
symbol = "$"makes the currency symbol optional, defaulting to a dollar sign.amount.toFixed(2)formats the number with exactly two decimal places.formatPrice(19.5)passes only the amount, sosymbolstays"$"and we get$19.50.formatPrice(19.5, "€")passes a euro symbol, overriding the default to get€19.50.
Most callers just want dollars, so they pass only the amount. The few who need another currency pass the second argument.
⚠️ Common Mistakes to Avoid
| Mistake | Problem | Solution |
Expecting the default to apply for null | greet(null) prints null, not the default | Remember defaults trigger only for undefined |
| Putting a required parameter after a defaulted one | You must pass undefined to reach the later argument | List required parameters first, optional ones last |
| Referencing a parameter defined later | A default can only use parameters to its left | Order parameters so each default sees what it needs |
Required first, optional last
Keep required parameters at the start of the list. If a defaulted parameter
comes before a required one, callers have to pass undefined just to reach
the later value.
🔧 Try It Yourself!
- Write a
greetfunction with anameparameter that defaults to"Guest", then call it with and without an argument. - Call your function with
nulland confirm the default does not apply. - Write a
formatPricefunction with asymbolparameter that defaults to"$". - Add a default parameter that references an earlier parameter and print the result.
🧩 What You’ve Learned
- ✅ A default parameter gives a function argument a fallback value
- ✅ Defaults apply only when the argument is
undefined, not fornullor other falsy values - ✅ Default parameters replace the old habit of checking for missing values inside the function
- ✅ A default can reference parameters defined before it
- ✅ Required parameters should come before optional, defaulted ones
🚀 What’s Next?
Now that your functions can fill in missing values, we will learn how to split code across files and share it. Let’s continue to Modules.