How to make code leaner in JavaScript

Continue to create, accelerate growth! This is the first day of my participation in the "Nuggets Daily New Plan · June Update Challenge", click to view the details of the event

The answer is to save code using JavaScript object destructuring, which is a common skill in project development.

Let's first look at an articleobject with two properties titleand description.

const article = {
    title: "JavaScript对象解构赋值",
    description:
        "解构是一个概念,分解其中一种数据类型并将其单独的属性分配给变量",
};
复制代码

Before ES6, when you needed to assign a property of an object to a variable, it was usually done like this:

const title = article.title;
const description = article.description
复制代码

But ES6 introduced object destructuring syntax, which provides another way to assign object properties to variables:

const { title, description: desc } = article;

console.log(title); // JavaScript对象解构赋值
console.log(desc); //  解构是一个概念,分解其中一种数据类型并将其单独的属性分配给变量
复制代码

The above code assigns the properties titleand descriptionproperties to the variables titleand desc.

Syntax description: The identifier before the colon ( :) is the property of the object, and the identifier after the colon is the newly defined variable.

Object destructuring example{}

Destructuring empty objects

Use the ORoperator ||to define a default value nullfor an empty object, and a default value if the object is an empty object {}.

function getArticle() {
    return null;
}
const { title, description } = getArticle() || {};

// 错误的情况
const { title, description } = getArticle() ;
复制代码

Nested object destructuring

Just look at the code below:

const article = {
    id: 1001,
    detail: {
        title: "JavaScript对象解构赋值",
        description:
            "解构是一个概念,分解其中一种数据类型并将其单独的属性分配给变量",
    },
};
const {
    detail: { title, description },
    detail,
} = article;
console.log(title); // JavaScript对象解构赋值
console.log(description); // 解构是一个概念,分解其中一种数据类型并将其单独的属性分配给变量
console.log(detail); // { title: 'JavaScript对象解构赋值', description: '解构是一个概念,分解其中一种数据类型并将其单独的属性分配给变量' }
复制代码

Note: Object destructuring by default assigns an object's properties to a variable with the same name.

Guess you like

Origin juejin.im/post/7103540921609748510
Recommended