Explain JavaScript Default Parameters
In JavaScript, default parameters allow you to initialize function parameters with default values if no value or undefined
is passed. This feature helps to avoid undefined
values and makes the code more concise and readable.
Here's a simple example to illustrate default parameters in JavaScript:
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Alice'); // Output: Hello, Alice!
In this example, the greet
function has one parameter name
with a default value of 'Guest'
. If the function is called without an argument or with undefined
, the default value 'Guest'
is used.
Let's see a more complex example with multiple parameters:
function createUser(username = 'Anonymous', role = 'User') {
console.log(`Username: ${username}, Role: ${role}`);
}
createUser(); // Output: Username: Anonymous, Role: User
createUser('John'); // Output: Username: John, Role: User
createUser('Jane', 'Admin'); // Output: Username: Jane, Role: Admin
createUser(undefined, 'Moderator'); // Output: Username: Anonymous, Role: Moderator
In this example, the createUser
function has two parameters username
and role
, each with their own default values. When calling the function:
- With no arguments, both default values are used.
- With one argument, only the first parameter is overridden.
- With two arguments, both parameters are overridden.
- By passing
undefined
for a parameter, the default value for that parameter is used.
Example with Default Parameters and Functions
Default parameters can also be functions or expressions:
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // Output: 5
console.log(multiply(5, 2)); // Output: 10
function sum(a = 1, b = 2, c = 3) {
return a + b + c;
}
console.log(sum()); // Output: 6
console.log(sum(4)); // Output: 9
console.log(sum(4, 5)); // Output: 12
console.log(sum(4, 5, 6)); // Output: 15
In these examples:
- The
multiply
function has a default parameterb
set to1
. Ifb
is not provided, it defaults to1
. - The
sum
function has three parameters, each with their own default values. If not provided, the defaults are used.
Default parameters provide a powerful way to handle optional function arguments and make your code more flexible and robust.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.