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

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

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() 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 JavaScript Scope Gotchas
A Simple Explanation of JavaScript Iterators
Dmitri Pavlutin · 2020-10-06 · via Dmitri Pavlutin Blog

A collection is a data structure that contains elements. For example, a string is a collection of characters and an array is a collection of ordered items:


const message = 'Hi!'; // consists of 'H', 'i' and '!'

const numbers = [1, 3, 4]; // consists of 1, 3 and 4


To easily access elements of collections of different structure, JavaScript implements a special pattern named iterator.

In this post, as a part of the iterator pattern, you'll learn what are iterables and iterators. You'll also learn about iterables consumers: how to iterate over a collection using for...of cycle, transform any iterable to an array using the spread operator [...iterable], and more.

Table of Contents

  • 1. Digging up the iterable
  • 2. Iterable and iterator interfaces
    • 2.1 How array conforms to iterable
  • 3. Consumers of iterables
    • 3.1 for...of cycle
    • 3.2 Spread operator
    • 3.3 Array destructuring
    • 3.4 Array.from()
  • 4. Native iterable types
    • 4.1 Iterable array
    • 4.2 Iterable string
    • 4.3 Iterable Map
    • 4.4 Iterable Set
  • 5. Summary

1. Digging up the iterable

I don't want to jump right into the dry theory of iterators. I know how confusing they are. On the contrary, let's start with a warm-up example to dig up the concept of iterable.

Let's reuse the numbers array from the introduction. Your task is to simply log to console each item of this array:


const numbers = [1, 3, 4];

for (const item of numbers) {

console.log(item);

}

// logs 1, 3, 4


As expected, the for...of loop logs to console each item of numbers array. Good.

Now let's try another experiment. Can for...of enumerate each property of a plain JavaScript object?


const person = { name: 'Eric', address: 'South Park' };

for (const prop of person) {

console.log(prop);

}

// Throws "TypeError: person is not iterable"


Not this time. for...of cycle cannot iterate over the properties of person object. Why does it happen?

You can find the answer in the error message: TypeError: person is not iterable. The for...of cycle requires an iterable collection to iterate over its items.

So, the first rule of thumb whether a data structure is iterable is try to iterate it using for...of.

Having this warm-up experiment, let's state stricter what an iterable is in the next section.

2. Iterable and iterator interfaces

An object is Iterable when it conforms to Iterable interface.

The Iterable interface requires the object to contain a method Symbol.iterator that must return an Iterator object.


interface Iterable {

[Symbol.iterator]() {

//...

return Iterator;

}

}


In simple words, any object is iterable (iter + able meaning able to be iterated) if it contains a method name Symbol.iterator (symbols can also define methods) that returns an Iterator.

Ok. But what's an Iterator? Let's find out:

The Iterator object must conform to Iterator interface.

The Iterator object must have a method next() that returns an object with properties done (a boolean indicating the end of iteration) and value (the item extracted from the collection at the iteration).


interface Iterator {

next() {

//...

return {

value: <value>,

done: <boolean>

};

};

}


I know that these theoretical terms are confusing. But stay with me.

2.1 How array conforms to iterable

You know from the warm-up experiment that the array is iterable. But how does exactly the array conform to the Iterable interface?


const numbers = [1, 3, 4];

numbers[Symbol.iterator](); // => object


Invoking the expression numbers[Symbol.iterator]() shows that the array instance contains the special method Symbol.iterator. This makes the array conform to the Iterable interface.

The numbers[Symbol.iterator]() method must return the iterator object.

The iterator object is the one that performs the iteration over the array items. Just call iterator.next() to access each item of the array!


const numbers = [1, 3, 4];

const iterator = numbers[Symbol.iterator]();

iterator.next(); // => { value: 1, done: false }

iterator.next(); // => { value: 2, done: false }

iterator.next(); // => { value: 3, done: false }

iterator.next(); // => { value: undefined, done: true }


Each invocation of iterator.next() returns an object { value: <item>, done: <boolean> }.

The value property contains the iterated item, while done indicates whether the iteration is complete.

When there are no more items to iterate, iterator.next() returns { value: undefined, done: true }.

3. Consumers of iterables

JavaScript provides a good set of cycles, syntaxes, and functions that consume iterables.

3.1 for...of cycle

As you know already, for...of cycle accepts an iterable object and iterates through its items:


const message = 'Hi!';

for (const char of message) {

console.log(char);

}

// logs 'H', 'i', '!'


In the above example, message is a string type that is an iterable. for...of cycle iterates over the characters in the string.

3.2 Spread operator

Another great consumer of iterables is the spread operator [...iterable]:


const message = 'Hi!';

const chars = [...message];

chars; // => ['H', 'i', '!']


The spread operator [...message] iterates over the characters of the string and creates an array of these characters.

3.3 Array destructuring

The array destructuring syntax can destructure iterables too!


const message = 'Hi!';

const [firstChar, ...restChars] = message;

firstChar; // => 'H'

restChars; // => ['i', '!']


[firstChar, restChars] = message is a destructuring assignment that destructures the iterable string message.

firstChar is assigned with the first character 'H'. The rest of the characters ['i', '!'] are stored into the array restChars.

3.4 Array.from()

Array.from(iterable[, mapFunction]) also accepts an iterable and transforms it into an array.


const message = 'Hi!';

const chars = Array.from(message);

chars; // => ['H', 'i', '!']


4. Native iterable types

Many native data types in JavaScript are iterables. What makes the iterator pattern in JavaScript so flexible and useful is that any iterable can be consumed by any iterable consumer.

Here's a list of popular iterable data types.

4.1 Iterable array

The array is iterable over its items:


const numbers = [1, 3, 4];

for (const item of numbers) {

console.log(item);

}

// logs 1, 3, 4


4.2 Iterable string

The string primitive is iterable over the characters:


const message = 'Hi!';

for (const char of message) {

console.log(char);

}

// logs 'H', 'i', '!'


4.3 Iterable Map

The Map object is iterable over its key and value pairs.


const map = new Map();

map.set('name', 'Eric');

map.set('address', 'South Park');

for (const [key, value] of map) {

console.log(key, value);

}

// logs 'name', 'Eric'

// logs 'address', 'South Park'


4.4 Iterable Set

The Set object is iterable over its items:


const set = new Set(['blue', 'red', 'green']);

for (const item of set) {

console.log(item);

}

// logs 'blue', 'red', 'green'


5. Summary

Iterables are collections that can be iterated. To be an iterable, the object must conform to Iterable interface.

Iterable consumers are language constructs that consume iterables. for...of cycle is an iterable consumer that cycles over each item of the iterable, spread operator [...iterable] create an array from the iterable's items.

What makes the iterator pattern so useful is that any iterable can be used by any iterable consumer. Even more: you can define your own iterable types, and even define your own iterable consumers!

Challenge: how would you implement an iterable that generates n random numbers?