Skip to content

Instantly share code, notes, and snippets.

Last active July 5, 2018 19:10
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
1 - Axel Rauschmeyer:
2 -
const arr = [ 'a', 'b', 'c']
const it = arr[Symbol.iterator]()
// { value: "a", done: false }
// { value: "b", done: false }
// { value: "c", done: false }
// { value: undefined, done: true }
Copy link

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