Skip to content

re: What is Symbol in JavaScript and the best situation to use it? VIEW POST


Here's a concrete example. In this example, we create an object of type SimpleIterable and iterate over it. What allows us to use the for...of syntax is the use of a computed property that defines a method with the name of Symbol.iterator. I think the idea is that there is no ambiguity here, as there could be if we just used a string instead.

class SimpleIterable {
    constructor() {
        this.index = 0
        this.values = [3,1,4]

    next() {
        const value = this.values[this.index]
        const done = !(this.index in this.values)
        this.index += 1
        return { value, done }

    [Symbol.iterator]() {
        return {
            next: () =>

const iter = new SimpleIterable()
for (const value of iter) {
    console.log('value = ' + value)
code of conduct - report abuse