惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
5 Interesting Uses of JavaScript Destructuring
Dmitri Pavlutin · 2019-08-15 · via Dmitri Pavlutin Blog

Looking at my regular JavaScript code, I see that destructuring assignments are everywhere.

Reading object properties and accessing array items are frequent operations. The destructuring assignments make these operations so much easier and concise.

In this post, I will describe 5 interesting uses of destructuring in JavaScript, beyond the basic usage.

1. Swap variables

The usual way to swap 2 variables requires an additional temporary variable. Let's see a simple scenario:


let a = 1;

let b = 2;

let temp;

temp = a;

a = b;

b = temp;

a; // => 2

b; // => 1


temp is a temporary variable that holds the value of a. Then a is assigned with the value of b, and consequently b is assigned with temp.

The destructuring assignment makes the variables swapping simple, without any need of a temporary variable:


let a = 1;

let b = 2;

[a, b] = [b, a];

a; // => 2

b; // => 1


[a, b] = [b, a] is a destructuring assignment. On the right side, an array is created [b, a], that is [2, 1]. The first item of this array 2 is assigned to a, and the second item 1 is assigned to b.

Although you still create a temporary array, swapping variables using destructuring assignment is more concise.

This is not the limit. You can swap more than 2 variables at the same time. Let's try that:


let zero = 2;

let one = 1;

let two = 0;

[zero, one, two] = [two, one, zero];

zero; // => 0

one; // => 1

two; // => 2


You can swap as many variables as you want! Although, swapping 2 variables is the most common scenario.

2. Access array item

You have an array of items that potentially can be empty. You want to access the first, second, or nth item of the array, but if the item does not exist, get a default value.

Normally you would use the length property of the array:


const colors = [];

let firstColor = 'white';

if (colors.length > 0) {

firstColor = colors[0];

}

firstColor; // => 'white'


Fortunately, array destructuring helps you achieve the same way shorter:


const colors = [];

const [firstColor = 'white'] = colors;

firstColor; // => 'white'


const [firstColor = 'white'] = colors destructuring assigns to firstColor variable the first element of the colors array. If the array doesn't have any element at the index 0, the 'white' default value is assigned.

But there's a lot more flexibility. If you want to access the second element only, that's possible too:


const colors = [];

const [, secondColor = 'black'] = colors;

secondColor; // => 'black'


Note the comma on the left side of the destructuring: it means that the first element is ignored. secondColor is assigned with the element at index 1 from the colors array.

3. Immutable operations

When I started using React, and later Redux, I was forced to write code that respects immutability. While having some difficulties at the start, later I saw its benefits: it's easier to deal with unidirectional data flow.

Immutability forbids mutating objects. Fortunately, destructuring helps you achieve some operations in an immutable manner easily.

The destructuring in combination with ... rest operator removes elements from the beginning of an array:


const numbers = [1, 2, 3];

const [, ...fooNumbers] = numbers;

fooNumbers; // => [2, 3]

numbers; // => [1, 2, 3]


The destructuring [, ...fooNumbers] = numbers creates a new array fooNumbers that contains the items from numbers but the first one.

numbers array is not mutated, keeping the operation immutable.

In the same immutable manner you can delete properties from objects. Let's try to delete foo property from the object big:


const big = {

foo: 'value Foo',

bar: 'value Bar'

};

const { foo, ...small } = big;

small; // => { bar: 'value Bar' }

big; // => { foo: 'value Foo', bar: 'value Bar' }


The destructuring assignment in combination with object rest operator creates a new object small with all properties from big, only without foo.

4. Destructuring iterables

In the previous sections, the destructuring was applied to arrays. But you can destructure any object that implements the iterable protocol.

Many native primitive types and objects are iterable: arrays, strings, typed arrays, sets, and maps.

For example, you can destructure a string to characters:


const str = 'cheese';

const [firstChar = ''] = str;

firstChar; // => 'c'


You're not limited to native types. Destructuring logic can be customized by implementing the iterable protocol.

movies holds a list of movie objects. When destructuring movies, it would be great to get the movie title as a string. Let's implement a custom iterator:


const movies = {

list: [

{ title: 'Heat' },

{ title: 'Interstellar' }

],

[Symbol.iterator]() {

let index = 0;

return {

next: () => {

if (index < this.list.length) {

const value = this.list[index++].title;

return { value, done: false };

}

return { done: true };

}

};

}

};

const [firstMovieTitle] = movies;

console.log(firstMovieTitle); // => 'Heat'


movies object implements the iterable protocol by defining the Symbol.iterator method. The iterator iterates over the titles of movies.

Conforming to an iterable protocol allows the destructuring of movies object into titles, specifically by reading the title of the first movie: const [firstMovieTitle] = movies.

The sky is the limit when using destructuring with iterators.

5. Destructuring dynamic properties

In my experience, the destructuring of an object by properties happens more often than arrays destructuring.

The destructuring of an object looks pretty simple:


const movie = { title: 'Heat' };

const { title } = movie;

title; // => 'Heat'


const { title } = movie creates a variable title and assigns to it the value of property movie.title.

When first reading about objects destructuring, I was a bit surprised that you don't have to know the property name statically. You can destructure an object with a dynamic property name!

To see how dynamic destructuring works, let's write a greeting function:


function greet(obj, nameProp) {

const { [nameProp]: name = 'Unknown' } = obj;

return `Hello, ${name}!`;

}

greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!'

greet({ }, 'name'); // => 'Hello, Unknown!'


greet() function is called with 2 arguments: the object and the property name.

Inside greet(), the destructuring assignment const { [nameProp]: name = 'Unknown' } = obj reads the dynamic property name using square brakets [nameProp]. The name variable receives the dynamic property value.

Even better you can specify a default value 'Unknown' in case if the property does not exist.

6. Conclusion

Destructuring works great if you want to access object properties and array items.

On top of the basic usage, array destructuring is convinient to swap variables, access array items, perform some immutable operations.

JavaScript offers even greater possibilities because you can define custom destructuring logic using iterators.

What interesting applications of destructuring do you know? Write a comment below!