Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Iterators : Arrays
/* JavaScript Iterators
An Iterator Object is a data structure that has a .next() method that can be called repeatedly.
Iterators use the Well Known Symbol called Symbol.iterator.
(The Iterable Object has an Iterator pointer for indexing.)
The Iterator object has two properties, value and done (boolean). Iteration will continue so
long as done is falsey. Once done is truthy, iteration stops.
Just like C++ iterators for C++ data structures, JavaScript iterators iterate through an entire
collection, and if incremented once more, will go "one value beyond" the collection to return
null pointer (or, in JS, undefined). The way this is done in JS is to call the .next() function
once more.
Sources:
1 - Axel Rauschmeyer: http://exploringjs.com/es6/ch_iteration.html
2 - http://www.zsoltnagy.eu/es6-iterators-and-generators-in-practice/
*/
const arr = [ 'a', 'b', 'c']
const it = arr[Symbol.iterator]()
console.log(it.next())
// { value: "a", done: false }
console.log(it.next())
// { value: "b", done: false }
console.log(it.next())
// { value: "c", done: false }
console.log(it.next())
// { value: undefined, done: true }
@abstractmachines

This comment has been minimized.

Owner

abstractmachines commented Nov 2, 2017

Arrays are just built-in iterables in JS

  • Arrays are built-in iterables just like Sets, Maps, etc, and work well with the for-of loop.

Converting other things to arrays

  • Array.from()

  • Spread operator can convert Sets to Arrays

  • The spread operator inserts the values of an iterable into an Array (from Dr Axel):

const arr = ['b', 'c'];
const arr2 = ['a', ...arr, 'd']

// arr2 is now:
> ['a', 'b', 'c', 'd']

JS Array Methods are awesome

Don't forget to use JS array methods like .includes(), .some(), .every(), and more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment