Core points
Creating methods also means writing APIs—whether for yourself, for other developers on your team, or for other developers using your project. Depending on the size, complexity, and purpose of the function, you must consider the default settings and input/output API. The default function parameters and attribute abbreviation are two convenient features of ES6 that can help you write APIs.
ES6 default parameters
Let us quickly review the knowledge and then look at the grammar. The default parameters allow us to initialize the default values for the function. Use the default value when the parameter is omitted or undefined - this means null is a valid value. The default argument can be anything from a number to another function.
// 基本语法 function multiply(a, b = 2) { return a * b; } multiply(5); // 10 // 默认参数也适用于后面的默认参数 function foo(num = 1, multi = multiply(num)) { return [num, multi]; } foo(); // [1, 2] foo(6); // [6, 12]
Let's look at a basic function and demonstrate how default parameters can speed up your development and make your code better organized. Our example method is called createElement(). It accepts some configuration parameters and returns an HTML element. The API looks like this:
// 我们想要一个 <p> 元素,带有一些文本内容和两个附加的类。 // 返回 <p>Such unique text</p> createElement('p', { content: 'Such unique text', classNames: ['very-special-text', 'super-big'] }); // 为了使此方法更有用,它应该在任何参数被省略或根本没有传递参数时始终返回默认元素。 createElement(); // <div>Very default</div>
The implementation of this method won't have much logic, but it may become quite large due to its default coverage.
// 没有默认参数,它看起来相当臃肿且不必要地庞大。 function createElement(tag, config) { tag = tag || 'div'; config = config || {}; const element = document.createElement(tag); const content = config.content || 'Very default'; const text = document.createTextNode(content); let classNames = config.classNames; if (classNames === undefined) { classNames = ['module-text', 'default']; } element.classList.add(...classNames); element.appendChild(text); return element; }
So far, everything went well. What's going on here? We are doing the following:
Let's now use this function and optimize it to make it simpler, faster to write, and to show its purpose more clearly:
// 基本语法 function multiply(a, b = 2) { return a * b; } multiply(5); // 10 // 默认参数也适用于后面的默认参数 function foo(num = 1, multi = multiply(num)) { return [num, multi]; } foo(); // [1, 2] foo(6); // [6, 12]
Instead of touching the logic of the function, we deleted all default processing from the function body. Function signatures now contain all default values. Let me explain part further, which may be a bit confusing:
// 我们想要一个 <p> 元素,带有一些文本内容和两个附加的类。 // 返回 <p>Such unique text</p> createElement('p', { content: 'Such unique text', classNames: ['very-special-text', 'super-big'] }); // 为了使此方法更有用,它应该在任何参数被省略或根本没有传递参数时始终返回默认元素。 createElement(); // <div>Very default</div>
We not only declare a default object parameter, but also declare the default object attribute . This makes the default configuration look clearer, rather than just declaring a default object (e.g. config = {}) and then setting the default properties later. It may take some extra time to get used to it, but ultimately it will improve your workflow. Of course, for larger configurations, we can still argue that it may create more overhead, and it would be easier to just keep the default processing in the body of the function.
ES6 attribute abbreviation
If the method accepts large configuration objects as parameters, your code may become quite large. The usual practice is to prepare some variables and add them to the object. The attribute abbreviation isSyntax Sugar, which can make this step shorter and easier to read:
// 没有默认参数,它看起来相当臃肿且不必要地庞大。 function createElement(tag, config) { tag = tag || 'div'; config = config || {}; const element = document.createElement(tag); const content = config.content || 'Very default'; const text = document.createTextNode(content); let classNames = config.classNames; if (classNames === undefined) { classNames = ['module-text', 'default']; } element.classList.add(...classNames); element.appendChild(text); return element; }
// 默认所有内容 function createElement(tag = 'div', { content = 'Very default', classNames = ['module-text', 'special'] } = {}) { const element = document.createElement(tag); const text = document.createTextNode(content); element.classList.add(...classNames); element.appendChild(text); return element; }
// 这里到底发生了什么? function createElement({ content = 'Very default', classNames = ['module-text', 'special'] } = {}) { // 函数体 }
const a = 'foo', b = 42, c = function() {}; // 以前我们会像这样使用这些常量。 const alphabet = { a: a, b: b, c: c }; // 但是使用新的简写,我们现在实际上可以这样做, // 这与上面相同。 const alphabet = {a, b, c};
Conclusion
Default parameters and attribute abbreviations are a great way to make your method more organized and, in some cases, shorter. Overall, the default function parameters helped me focus more on the practical use of the method without being distracted by a lot of default preparation and if statements. The attribute abbreviation is indeed more of an appearance feature, but I find myself more productive and spend less time writing all variables, configuration objects, and function keywords. Are you already using default parameters and attribute abbreviations?This article was peer-reviewed by Sebastian Seitz. Thanks to all SitePoint peer reviewers for making SitePoint content perfect!
FAQ about ES6 default parameters (FAQ)
What are the advantages of using ES6 default parameters?Yes, you can use the ES6 default parameters with deconstructed assignments. This is a powerful feature of ES6 that allows you to unpack values in arrays or properties in objects into different variables. When used in conjunction with the default parameters, you can extract values from objects or arrays and assign default values when the extracted values are not defined.
arguments object is an array-like object that contains all the parameters passed to the function. However, it does not have all methods of having arrays and is not as flexible as the ES6 default parameters. With default parameters, you can set default values for any undefined parameters, which is not possible in arguments objects.
Yes, you can use the ES6 default parameters in the constructor. This is especially useful when creating new instances of a class. If certain parameters are not provided when creating a new instance, the default parameters are used to ensure that the new object has all the necessary properties.
Generally speaking, the performance impact of using ES6 default parameters is small and should not be a problem. However, like any feature, it should be used with caution. Excessive use of default parameters, especially in performance-critical code, can cause slow execution time. As always, be sure to test your code and monitor its performance.
Yes, you can use the ES6 default parameters with the arrow functions. The arrow functions introduced in ES6 provide a concise syntax to write function expressions. They are especially useful when using higher-order functions that take other functions as arguments.
If the parameter passes a null value, the ES6 default parameter function will not assign the default value. This is because null is considered a value in JavaScript, unlike undefined. If you want to assign a default value when the parameter is null, you need to deal with this case separately in your code.
Yes, you can use the ES6 default parameters in recursive functions. This is especially useful when you want to provide a base case for a recursive function but don't want to ask the caller to always provide it.
Yes, you can use the ES6 default parameters with the remaining parameters. However, remember that the remaining parameters must be the last parameter in the function definition. Additionally, you cannot assign default values to the remaining parameters themselves, but you can assign default values to individual parameters for a portion of the remaining parameters.
Yes, you can use the ES6 default parameters with the extension operator. The extension operator allows you to expand iterable objects such as arrays to individual elements. When used with default parameters, you can pass a set of values to the function and assign a default value to any undefined parameters.
The above is the detailed content of Clean Code with ES6 Default Parameters & Property Shorthands. For more information, please follow other related articles on the PHP Chinese website!