In-depth Understanding of ES6 005 [Study Notes]

Destructuring: Making data access more convenient. If you declare variables using `var`, `let`, or `const` with destructuring, you must provide an initializer (i.e., the value on the right side of the equals sign). The following will cause an error:
// Syntax error `var {tyep,name}`
// Syntax error `let {type,name}`
// Syntax error `const {type,name}`
To assign values to already declared variables using destructuring, consider the following:
`let node = { type:&qu...`

Destructuring: Making Data Access More Convenient

If you declare variables using `var`, `let`, or `const` with destructuring, you must provide an initializer (i.e., the value on the right side of the equals sign). The following will cause an error:

// 语法错误
var {tyep,name}

// 语法错误
let {type,name}

// 语法错误
const {type,name}

To assign values to already declared variables using destructuring, see below:

let node = {
  type:"Identifier",
  name:"foo"
},
type = "Literal",
name = 5;

// 使用解构语法为多个变量赋值 ,请注意一定要使用小括号包裹解构赋值的方法(js引擎将一对开放的花括号视为一个代码块,而语法规定,代码块语句不允许出现在赋值语句侧,添加小括号后可以将语句转化为一个表达式
({type,name}=node)
console.log(type) // Identifier
console.log(name) // foo

The value of a destructuring assignment expression is equal to the value on the right side of the expression (i.e., the right side of `=`). This means you can use a destructuring assignment expression anywhere a value is expected, as follows:

let node = {
  type:"Identifier",
  name:"foo"
},
type = "Literal",
name = 5;

function outputinfo(value){
  console.log(value===node); // true
}

outputinfo({type,name} = node);

console.log(type) // "Identifier"
console.log(name) // "foo"
// The value of the expression is the value on the right side. This syntax means `value` is passed `node`, and `type` and `name` are assigned.
// When calling the `outputInfo()` function, a destructuring expression is passed. Since the value of a JavaScript expression is the value on its right side, the parameter passed here is equivalent to `node`, and the variables `type` and `name` are reassigned. Finally, `node` is passed to the `outputInfo()` function.

If a destructuring assignment expression (i.e., the expression on the right side of `=`) is `null` or `undefined`, it will cause the program to throw an error. Any attempt to read properties of `null` or `undefined` will trigger a runtime error.

Default Values

When using a destructuring assignment expression, if the specified local variable name does not exist in the object, that local variable will be assigned `undefined`.

let node = {
  type:"Identifier",
  name:"foo"
}
let {type,name,value} = node;
console.log(type) //Identifier
console.log(name) // foo
console.log(value) // undefined

// Default values: When a specified property does not exist, you can define a default value by adding an equals sign (=) and the corresponding default value after the property name.

let node = {
  type:"Identifier",
  name:"foo"
}
let {type,name,value=true} = node; // This value only takes effect if the property does not exist on `node` or its value is `undefined`.
console.log(type) //Identifier
console.log(name) // foo
console.log(value) // true

Assigning to Local Variables with Different Names

Destructuring assignments typically use local variables with the same names as the object properties. For example, the value of `node.type` is stored in the `type` variable. However, if you want to use differently named local variables to store object property values,

let node = {
  type:"Identifier",
  name:"foo"
}
let {type:localType,name:localName="bar"} = node;
console.log(type) //Identifier
console.log(name) // foo

// Differently named local variables, with default values
let node = {
  type:"Identifier"
}
let {type:localType,name:localName="bar"} = node;
console.log(type) //Identifier
console.log(name) // bar

Nested Object Destructuring

Destructuring nested objects is still similar to object literal syntax; you can deconstruct objects to get the information you want.

let node = {
  type:"Identifier",
  name:"foo",
  loc:{
    start:{
      line:1,
      column:1
    },
    end:{
      line:1,
      column:4
    }
  }
}
let {loc:{start}} = node;
console.log(start.line); // 1
console.log(start.column); // 1

// Using differently named local variables
let node = {
  type:"Identifier",
  name:"foo",
  loc:{
    start:{
      line:1,
      column:1
    },
    end:{
      line:1,
      column:4
    }
  }
}
let {loc:{start:localStart}} = node;
console.log(localStart.line); // 1
console.log(localStart.column); // 1

In the following statement, because there is only a pair of curly braces on the right side, it will not declare any bindings. `loc` is not a binding to be created; it represents the position where properties are retrieved within the object.

// 未声明任何变量!
let {loc:{}} = node

Array Destructuring

Compared to object destructuring syntax, array destructuring is much simpler. It uses array literals, and all destructuring operations are performed within the array, rather than using objects like object literal syntax.

let colors = ["red","green","blue"]
let [firstColor,secondColor]=colors
console.log(firstColor) //red
console.log(firstColor) // green
// Provide variables only for elements of interest. Remember, the array itself does not change during this process.
let [,,thirdColor] = colors;
console.log(thirdColor) // blue

Array Destructuring Assignment

In the context of array destructuring assignment, there is no need to wrap the expression in parentheses.

These syntaxes for array destructuring assignment are sufficient. Array destructuring syntax also has a unique use case: variable swapping.

If the right-hand side of an array destructuring assignment expression is `null` or `undefined`, it will cause the program to throw an error. This characteristic is very similar to object destructuring values.

let a = 1, b = 2;
[a,b] = [b,a];
console.log(a)  // 2
console.log(b)  // 1

Nested Array Destructuring

let colors = ["red",["green","lightgreen"],"blue"];
// 
let [firstColor,[secondColor]] = colors;
console.log(firstColor); // red
console.log(secondColor); // green

Rest Elements

You can assign the remaining elements in an array to a specific variable using the `...` syntax.

let colors = ["red","green","blue"]
let [firstColor,...restColors] = colors;
console.log(firstColor) // "red"
console.log(restColors[0]); // green
console.log(restColors[1]); // blue

ES5 often uses the `concat()` method to clone arrays; if called without arguments, it returns a copy of the current array. ES6 can achieve the same goal through the rest elements syntax.

// es5
var colors = ["red","green","blue"];
var clonedColors = colors.concat();
console.log(clonedColors) // [red,green,blue]
// es6
let colors = ["red","green","blue"];
let [...clonedColors] = colors;
console.log(clonedColors); // [red,green,blue]

In a destructured array, the rest element must be the last item; adding more commas after it will cause a syntax error. You can use object destructuring to create more complex expressions, allowing you to extract desired information from any data structure that mixes objects and arrays.

let node = {
  type: "Identifier",
  name: "foo",
  loc: {
    start: {
      line: 1,
      column: 4
    },
    end: {
      line: 1,
      column: 4
    }
  },
  range: [0,3]
}

let {
  loc:{start},
  range:[startIndex]
}
console.log(start.line); // 1
console.log(start.column); // 1
console.log(startIndex); 0

Destructuring Parameters

When defining a JavaScript function that accepts many optional parameters, we typically create an options object and define the extra parameters as properties of this object.

  • Destructuring parameters that must be passed
  • Default values for destructuring parameters
function setCookie(name,value,{
  source = false,
  path = '/',
  domain = 'example.com',
  expires = new Date(Date.now()+360000*1000)
}){
  // 设置cookie的代码
}

setCookie("type","js",{secure:true,expires:60000})
// There's a peculiar aspect to destructuring parameters: by default, if you call a function without providing the destructured parameter, it will throw an error. For example, if the third parameter is not passed, an error will occur.
// 程序报错!
setCookie("type","js");
// The third parameter is missing, and its value is `undefined`. Destructuring parameters are just a shorthand for applying destructuring declarations to function parameters. That is, if the right-hand side of a destructuring assignment expression is `null` or `undefined`, the program will throw an error. Similarly, if the `setCookie()` function is called without passing the third parameter, it will also cause the program to throw an error.
// A good practice is to provide the same default values for it.
const setCookieDefaults = {
  secure:false,
  path: "/",
  domain: "example.com",
  expires: new Date(Date.now()+360000000)
}
function setCookie(name,value,{
   secure:false,
  path: "/",
  domain: "example.com",
  expires: new Date(Date.now()+360000000)
}=setCookieDefaults) {
  // ....
}

In both object and array destructuring, you can set default values for object properties or array elements whose values are `undefined`. The right-hand side of the assignment expression cannot be `null` or `undefined`, otherwise the program will throw an error. You can use `var`, `let`, or `const` to declare variables with destructuring, but according to syntax rules, an initializer must be specified.

主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/4331

(0)
Walker的头像Walker
上一篇 Nov 25, 2025 12:00
下一篇 Nov 25, 2025 10:00

Related Posts

  • In-depth Understanding of ES6 009 [Learning Notes]

    Classes in JavaScript function PersonType(name){ this.name = name; } PersonType.prototype.sayName = function(){ console.log(this.name) } var person = new PersonType("Nicholas") p…

    Personal Mar 8, 2025
    1.3K00
  • Node: In-depth Yet Easy to Understand (Shengsi Garden Education) 003 [Study Notes]

    WebSocket and SSE Overview WebSocket Basics Definition: WebSocket is a full-duplex connection upgraded after an HTTP handshake, allowing clients and servers to push data bidirectionally over the same TCP channel, eliminating the need for repeated polling. Handshake Process: The client initiates an HTTP request with the Upgrade: websocket header; The server responds with 101 Switching Protocols, and both parties agree...

    Personal Nov 24, 2025
    44800
  • Nuxt3: Beginner's Guide and Principles Introduction [Learning Notes]

    Nuxt 3: Getting Started and Principles 💡 What is Nuxt 3? Nuxt 3 is a full-stack frontend framework built on Vue 3 and Vite, supporting: Server-Side Rendering (SSR) Static Site Generation (SSG) Single-Page Applications (SPA) Building full-stack applications (with API support) Nuxt 3 is an "enhanced version" of Vue, helping you simplify project structure and development workflow. 🔧 Core Principles Feature How Nuxt Handles It ✅ Page Routing Automatic root...

    Personal Apr 6, 2025
    2.2K00
  • In-depth Understanding of ES6 011 [Learning Notes]

    Promises and Asynchronous Programming

    Because the execution engine is single-threaded, it needs to track the code that is about to run. This code is placed in a task queue. Whenever a piece of code is ready to execute, it is added to the task queue, and whenever a piece of code in the engine finishes execution, the event loop executes the next task in the queue. A Promise acts as a placeholder for the result of an asynchronous operation. It doesn't subscribe to an event or pass a callback function to the target function. Instead, it allows the function to return a Promise, like this...

    Personal Mar 8, 2025
    1.2K00
  • Go Engineer's Comprehensive Course 017: Learning Notes

    Introduction to Rate Limiting, Circuit Breaking, and Degradation (with Sentinel Practical Application)
    Based on the key video points from Chapter 3 (3-1 to 3-9) of the courseware, this guide compiles a service protection introduction for beginners, helping them understand "why rate limiting, circuit breaking, and degradation are needed," and how to quickly get started with Sentinel.
    Learning Path at a Glance
    3-1 Understanding Service Avalanche and the Background of Rate Limiting, Circuit Breaking, and Degradation
    3-2 Comparing Sentinel and Hystrix to clarify technology selection
    3-3 Sen...

    Personal Nov 25, 2025
    28100
EN
简体中文 繁體中文 English