JavaScript Default Parameters
Default parameters in JavaScript allow you to assign default values to function parameters if no value or undefined is passed. Introduced in ES6, this feature makes your code cleaner and helps prevent errors.
1. What Are Default Parameters?
When calling a function without an argument, the default value is used.
Example:
function greet(name = "Guest") {
console.log("Hello," + name);
}
greet(); // Hello, Guest
greet("Ava"); // Hello, Ava
2. Default Parameters with Multiple Arguments
You can use default values for one or more parameters.
Example:
function register(username = "Anonymous", role = "User") {
console.log(`${username} registered as ${role}`);
}
register(); // Anonymous registered as User
register("Zara"); // Zara registered as User
register("Max"
,
"Admin"); // Max registered as Admin
3. Expressions as Default Values
You can even use expressions or function calls as default values.
Example:
function getTime() {
return new Date().toLocaleTimeString();
}
function logTime(time = getTime()) {
console.log("Logged at:"
, time);
}
logTime(); // Logged at: current time
logTime("10:00 AM"); // Logged at: 10:00 AM
4. Undefined vs Null in Default Parameters
Only undefined triggers the default value — null does not.
Example:
function sayHi(name =
"Stranger") {
console.log("Hi"
, name);
}
sayHi(undefined); // Hi Stranger
sayHi(null); // Hi null
undefined triggers the default value
null is considered a value, so the default is ignored
5. Using Default Parameters in Arrow Functions
Works the same as with regular functions.
Example:
const multiply = (a, b = 1) => a * b;
console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10
6. Real-World Use Case – API Call Wrapper
Example:
function fetchData(endpoint = "/api/default"
"/api/default", method = "Get") {
console.log(`Fetching ${endpoint} with ${method} method`);
}
fetchData(); // Fetching /api/default with
GET method
fetchData("/api/user"
,
"POST"); // Fetching /api/user with POST
method
Benefits of Default Parameters
- Avoid undefined errors
- Write cleaner and shorter function logic
- Simplify optional arguments
- Enhance function flexibility