Home > Web Front-end > JS Tutorial > Clean Code with ES6 Default Parameters & Property Shorthands

Clean Code with ES6 Default Parameters & Property Shorthands

William Shakespeare
Release: 2025-02-15 10:19:13
Original
425 people have browsed it

Clean Code with ES6 Default Parameters & Property Shorthands

Core points

  • ES6 default parameters allow the default value to be initialized for functions, and are used when the parameters are omitted or undefined. This feature simplifies the code and makes it more concise and easy to read because it reduces the need for if statements and other checks.
  • ES6 property abbreviation provides a way to make the code more concise and easy to read, especially when dealing with large configuration objects. Without writing a complete attribute assignment, you can assign values ​​to attributes with the same name as their variable using abbreviation.
  • The default parameters and attribute abbreviations in ES6 can make the method more orderly and in some cases, shorter. They can help developers focus more on the practical uses of the method without being distracted by a lot of default preparations.
  • Although attribute abbreviations are more of an appearance feature, they can increase productivity by reducing the time spent writing variables, configuring objects, and function keywords. They can also be applied to usage method definitions within objects to obtain cleaner code.

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]
Copy after login
Copy after login

A practical example

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>
Copy after login
Copy after login

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;
}
Copy after login
Copy after login

So far, everything went well. What's going on here? We are doing the following:

  1. Set default values ​​for our parameters tag and config in case they are not passed ( Note that some code inspectors don't like parameter reassignment )
  2. Create constants using actual content (and default values)
  3. Check if classNames is defined, and if not, assign the default array
  4. Create and modify elements before returning them

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]
Copy after login
Copy after login

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>
Copy after login
Copy after login

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 is

Syntax 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;
}
Copy after login
Copy after login
Simplify your API

Okay, let's go back to another more common example. The following function takes some data, modify it and calls another method:

// 默认所有内容
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;
}
Copy after login
We often name variable and object attribute names the same. Using attribute abbreviation combined with deconstruction, we can actually shorten the code a lot:

// 这里到底发生了什么?
function createElement({
  content = 'Very default',
  classNames = ['module-text', 'special']
} = {}) {
  // 函数体
}
Copy after login
Again, this may take a while to get used to. Ultimately, it's one of the new features in JavaScript that helps me write code faster and use a cleaner body of function. But wait, there are more! The attribute abbreviation can also be applied to the usage definition within the object:

const a = 'foo', b = 42, c = function() {};

// 以前我们会像这样使用这些常量。
const alphabet = {
  a: a,
  b: b,
  c: c
};

// 但是使用新的简写,我们现在实际上可以这样做,
// 这与上面相同。
const alphabet = {a, b, c};
Copy after login

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?

ES6 default parameters provide multiple advantages. First, they help make your code more concise and easy to read. Without checking if the parameters are undefined and then assigning the default values, you can do everything in one line. This reduces the amount of code you have to write and makes it easier for others to understand your code. Second, they help prevent errors. If a function expects a certain parameter but is not provided, it may result in unexpected results or errors. By setting default parameters, you can make sure your function has all the parameters it needs to work properly.

Can I use the ES6 default parameters with deconstructed assignments?

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.

How is the default parameters of ES6 different from the arguments object in JavaScript?

The

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.

Can I use the ES6 default parameters in the constructor?

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.

Will there any performance impact on using ES6 default parameters?

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.

Can I use the ES6 default parameters with the arrow function?

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.

How does the null value be handled by the default parameter function of ES6?

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.

Can I use the ES6 default parameters in recursive functions?

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.

Can I use the ES6 default parameters with the remaining parameters?

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.

Can I use the ES6 default parameters with the extension operator?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template