Skip to content

Instantly share code, notes, and snippets.

@abstractmachines
Last active July 5, 2018 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abstractmachines/1c72a2bb4dee5b09abebee76fa77c0e0 to your computer and use it in GitHub Desktop.
Save abstractmachines/1c72a2bb4dee5b09abebee76fa77c0e0 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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