Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES 6: Difference between Symbol.iterator and @@iterator

I was wondering if there was a specific difference in implementing an iterator using the @@iterator function versus the Symbol.iterator one:

On MDN, there is a page on Array.prototype.@@iterator, yet in the examples itself, Symbol.iterator is used as the function name. Is this just the updated version and @@iterator is not valid anymore, or are both of them valid?

like image 615
nils Avatar asked Apr 16 '15 09:04

nils


People also ask

What is a symbol iterator?

Symbol. iterator is the protocol that makes native objects like Array , Set , and Map iterable by providing a hook into language features like for…of loops and the spread operator. The most obvious use case is in creating new, iterable data structures that are not provided by the language, like a Linked List.

What is symbol iterator in TypeScript?

Iterators in JavaScript/TypeScript In JavaScript the implementation is based on a method whose key is Symbol. iterator. Really, Symbol. iterator is a factory of iterators. Iterator is a structure that contains a pointer to the next element in the iteration.

What is es6 iterator?

Iterator is an object which allows us to access a collection of objects one at a time. The following built-in types are by default iterable − String. Array. Map.

What is difference between iterator and generator in JavaScript?

While custom iterators are a useful tool, their creation requires careful programming due to the need to explicitly maintain their internal state. Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous.


2 Answers

The ECMAScript 2015 (ES6) specification uses @@iterator to reference Symbol.iterator. There is no @@iterator, and wherever you see it, read it as Symbol.iterator.

I think (someone more familiar with the ECMAScript spec might be able to back this up) the reason @@iterator is used is because you need to access Symbol properties on an object using square brackets ([]), but most parts of the ES2015 specification (and documentation) used the more familiar dot-notion (e.g. object.property versus object["property"]), and so@@somesymbol` is used to keep things consistent.

See page 38 (marked as page 18): http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

like image 92
Thomas Foster Avatar answered Oct 07 '22 16:10

Thomas Foster


There is no @@iterator function. That token produces a syntax error - it is only used in specification to denote a specific symbol.

If you want to use that symbol in your code, e.g. to access iterators on arrays, you have to use Symbol.iterator. Which is a property of the Symbol class initialised to have the value @@iterator.

like image 28
Bergi Avatar answered Oct 07 '22 17:10

Bergi