乐闻世界logo
搜索文章和话题

Set a default parameter value for a javascript function

1个答案

1

In JavaScript, default parameter values can be set by providing initial values for parameters within the function definition. If no corresponding parameter is provided when calling the function, the parameter will default to the specified value. This feature was introduced in ES6 (ECMAScript 2015), making it concise and easy to understand.

Here is an example of setting default parameter values:

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

In this example, we define a function named greet that accepts a parameter name. By using the = operator, we assign the default value 'Guest' to name. When calling the greet function with a parameter, such as greet('Alice'), the function uses the provided value. However, if no parameter is provided, such as greet(), the function uses the default value 'Guest'.

Before ES6, we had to check within the function body whether the parameter was provided and not undefined; if so, we manually set the default value. Here is an example of implementing default parameters in older JavaScript versions:

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

In this older example, we check within the function body whether the name parameter is provided and not undefined. If it is undefined, we assign the default value 'Guest' to name. This approach was common before ES6 but is cumbersome and less intuitive. With the introduction of default parameters in ES6, the code becomes clearer and more concise.

2024年6月29日 12:07 回复

你的答案