Posts

Showing posts with the label iteration

ES6 generators in depth

Image
This blog post is outdated. Please read chapter “ Generators ” in “Exploring ES6”. This blog post is part of a series on iteration in ES6: Iterables and iterators in ECMAScript 6 ES6 generators in depth Generators, a new feature of ECMAScript 6 [4] , are functions that can be paused and resumed. This helps with many applications: iterators, asynchronous programming, etc. This blog post explains how generators work and gives an overview of their applications. The following GitHub repository contains the example code: generator-examples Overview Two important applications of generators are: Implementing iterables Blocking on asynchronous function calls The following subsections give brief overviews of these applications, more thorough explanations are provided later (plus discussions of other topics). Implementing iterables via generators The following function returns an iterable over the properties of an object, one [key,value] pair per property: // The asterisk after `function` ...

Iterables and iterators in ECMAScript 6

Image
This blog post is outdated. Please read chapter “ Iterables and iterators ” in “Exploring ES6”. This blog post is part of a series on iteration in ES6: Iterables and iterators in ECMAScript 6 ES6 generators in depth ECMAScript 6 introduces a new interface for iteration, Iterable . This blog post explains how it works, which language constructs consume data via it (e.g., the new for-of loop) and which sources provide data via it (e.g., arrays). Iterability The idea of iterability is as follows. Data consumers: JavaScript has language constructs that consume data. For example, for-of loops over values and the spread operator ( ... ) inserts values into arrays or function calls. Data sources: The data consumers could get their values from a variety of sources. For example, you may want to iterate over the elements of an array, the key-value entries in a map or the characters of a string. It’s not practical for every consumer to support all sources, especially because it should be pos...