Destructuring • JavaScript for impatient programmers (ES2021 edition)
CRANK

(Ad, please don’t block.)37.1 A first taste of destructuringWith normal assignment, you extract one piece of data at a time – for example:const arr = ['a', 'b', 'c']; const x = arr[0]; // extract const y = arr[1]; // extractWith destructuring, you can extract multiple pieces of data at the same time via patterns in locations that receive data. The left-hand side of = in the previous code is one such location. In the following code, the square brackets in line A are a destructuring pattern:const arr = ['a', 'b', 'c']; const [x, y] = arr; // (A) assert.equal(x, 'a'); assert.equal(y, 'b');This code does the same as the previous code.Note that the pattern is “smaller” than the data: we are only extracting what we need.37.2 Constructing vs. extractingIn order to understand what destructuring is, consider that JavaScript has two kinds of operations that are opposites:You can construct compound data, for example, by setting properties and via object literals.You can extract data out of…

exploringjs.com
Related Topics: JavaScript
1 comments