ES6+ Features: Default Parameters
Before ES6, handling optional function parameters often involved manual checks inside the function body. For example, you might use the logical OR operator (||) or an if statement to assign a default value if an argument was undefined.
Default parameters simplify this process by allowing you to define a default value directly in the function's parameter list.
1. Basic Syntax
To set a default parameter, you simply assign a default value to it using the assignment operator (=) in the function's parameter list.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest! (name uses default)
greet('Alice'); // Output: Hello, Alice! (name uses provided argument)
greet(undefined); // Output: Hello, Guest! (explicit undefined uses default)
greet(null); // Output: Hello, null! (null is a value, not undefined, so default is NOT used)
2. When are Default Values Used?
A default value is used only if:
- The argument for that parameter is omitted during the function call.
- The argument for that parameter is explicitly passed as
undefined.
Important: If any other value, including null, 0, false, or an empty string (''), is passed, the default value will not be used. These are considered valid, non-undefined values.
3. Order of Default Parameters
It's generally a good practice to place parameters with default values at the end of your parameter list.
You can mix default and non-default parameters, but if a non-default parameter follows a default parameter, you'll have to explicitly pass undefined for the default parameter to use its default value.
// Good practice: Default parameters at the end
function createUser(name, age = 30, city = 'Unknown') {
console.log(`User: ${name}, Age: ${age}, City: ${city}`);
}
createUser('Bob'); // User: Bob, Age: 30, City: Unknown
createUser('Carol', 25); // User: Carol, Age: 25, City: Unknown
createUser('David', 40, 'London'); // User: David, Age: 40, City: London
// Less common, but possible: Non-default after default
function sendMessage(message = 'No message', recipient) {
// To use default for message, recipient must be provided
console.log(`To: ${recipient}, Message: ${message}`);
}
// sendMessage('Hi'); // Error: recipient is undefined
sendMessage(undefined, 'Eve'); // To: Eve, Message: No message
sendMessage('Hello', 'Frank'); // To: Frank, Message: Hello
4. Using Expressions as Default Values
Default values can be any valid JavaScript expression, including:
- Numbers, strings, booleans
- Variables
- Function calls
- References to other parameters (that appear before them in the list)
The expression is evaluated each time the function is called and the default value is needed.
function getDefaultId() {
console.log('Generating default ID...');
return Math.random().toString(36).substring(7);
}
function createItem(name, id = getDefaultId()) { // Function call as default
console.log(`Item: ${name}, ID: ${id}`);
}
createItem('Laptop'); // Generates new ID
createItem('Mouse'); // Generates another new ID
createItem('Keyboard', 'custom-id-123'); // Uses provided ID
// Using another parameter's value
function createGreeting(name = 'User', message = `Hello, ${name}!`) {
console.log(message);
}
createGreeting('Grace'); // Hello, Grace!
createGreeting(undefined, 'Hi there!'); // Hi there!
5. Comparison to Pre-ES6 Techniques
Let's look at how default parameters simplify common patterns:
Before ES6 (using ||):
function sayHelloOld(name) {
name = name || 'Guest'; // If name is falsy (undefined, null, '', 0, false), use 'Guest'
console.log('Old Way: Hello, ' + name + '!');
}
sayHelloOld(); // Hello, Guest!
sayHelloOld('Alice'); // Hello, Alice!
sayHelloOld(null); // Hello, Guest! (Problem: null is falsy, so it defaults)
sayHelloOld(''); // Hello, Guest! (Problem: empty string is falsy, so it defaults)
sayHelloOld(0); // Hello, Guest! (Problem: 0 is falsy, so it defaults)
This || trick is concise but has a major drawback: it will use the default value for any falsy value (0, '', false, null), not just undefined (or omitted arguments).
Before ES6 (explicit undefined check):
function sayHelloBetterOld(name) {
if (name === undefined) {
name = 'Guest';
}
console.log('Better Old Way: Hello, ' + name + '!');
}
sayHelloBetterOld(); // Hello, Guest!
sayHelloBetterOld('Alice'); // Hello, Alice!
sayHelloBetterOld(null); // Hello, null! (Correctly uses null)
sayHelloBetterOld(''); // Hello, ! (Correctly uses empty string)
sayHelloBetterOld(0); // Hello, 0! (Correctly uses 0)
This is more accurate but verbose. Default parameters offer the best of both worlds: conciseness and correct undefined handling.
Comprehensive Example: User Profile Function
Exercise: Configure a Notification
Instructions:
Create a function named sendNotification that takes a message and optional parameters for configuration.
- Define the
sendNotificationfunction with the following parameters and their default values:message(string, no default, must be provided)type(string, default:'info')duration(number, default:3000milliseconds)isVisible(boolean, default:true)timestamp(number, default:Date.now()- use a function call for the default).
- Inside the function, log all the received parameter values in a formatted way.
- Test your function with various scenarios:
- Call with only the required
message. - Call with
messageandtype. - Call with
message,type, andduration. - Call with
messageand explicitlyundefinedfortypeto ensure default is used. - Call with
messageandnullfortypeto observenullbeing used instead of the default.
- Call with only the required

