Quiz Questions

What are default parameters and how are they used?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Default parameters in JavaScript allow you to set default values for function parameters if no value or undefined is passed. This helps avoid undefined values and makes your code more robust. You can define default parameters by assigning a value to the parameter in the function definition.

function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Alice'); // Output: Hello, Alice!

Default parameters

Default parameters in JavaScript provide a way to set default values for function parameters. This feature was introduced in ECMAScript 2015 (ES6) and helps to make functions more robust and easier to work with by avoiding undefined values when no arguments are passed.

Syntax

You can define default parameters by assigning a value to the parameter in the function definition. If no value or undefined is passed for that parameter, the default value will be used.

function functionName(parameter1 = defaultValue1, parameter2 = defaultValue2) {
// function body
}

Example

Here is a simple example to illustrate how default parameters work:

function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Alice'); // Output: Hello, Alice!

In this example, the greet function has a default parameter name with a default value of 'Guest'. When the function is called without any arguments, it uses the default value. When an argument is provided, it overrides the default value.

Multiple default parameters

You can also define multiple default parameters in a function:

function createUser(username = 'Anonymous', age = 18) {
console.log(`Username: ${username}, Age: ${age}`);
}
createUser(); // Output: Username: Anonymous, Age: 18
createUser('John'); // Output: Username: John, Age: 18
createUser('John', 25); // Output: Username: John, Age: 25

In this example, the createUser function has two default parameters: username and age. If no arguments are passed, both default values are used. If only one argument is passed, the second parameter uses its default value.

Using expressions as default values

You can also use expressions as default values for parameters:

function add(a = 0, b = a + 1) {
return a + b;
}
console.log(add()); // Output: 1
console.log(add(5)); // Output: 11
console.log(add(5, 10)); // Output: 15

In this example, the default value for b is an expression that depends on the value of a. If no arguments are passed, a is 0 and b is 1. If only a is passed, b is a + 1. If both a and b are passed, the provided values are used.

Further reading

Edit on GitHub