Iterators

Data types

The latest ECMAScript standard defines eight data types:

Symbol

ECMAScript 6 introduces a new primitive type: symbols. They are tokens that serve as unique IDs

const Sym1 = Symbol('Sym');
const Sym2 = Symbol('Sym');
  
console.log(Sym1 === Sym2); // returns "false"

//

const Sym = Symbol('Sym');
console.log(Sym + ''); // TypeError: Cannot convert a Symbol value to a string
console.log(Sym.toString()); // Symbol(Sym), now it works
console.log(Sym.description); // "Sym"

//

const myPrivateMethod = Symbol();
this[myPrivateMethod] = function() {...};

new operator

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

const date = new Date();
const str = new String('str');
const set1 = new Set([1, 2, 3, 4, 5]);
const myMap = new Map();

this

this keyword refers to an object, that object which is executing the current bit of javascript code.

In other words, every javascript function while executing has a reference to its current execution context, called this. Execution context means here is how the function is called.

const obj1 = {
  name: "Pulsar",
  bike: function() {
    console.log(this.name);
  }
};

var name = "Ninja";
const obj2 = { name: "Gixxer", bike: obj1.bike };
const bike = obj1.bike;

bike();           // "Ninja"
obj1.bike();      // "Pulsar"
obj2.bike();      // "Gixxer"

for...of

const iterableArr = [10, 20, 30];
const iterableStr = 'boo';

for (const value of iterableArr) {
  console.log(value);
}
// 10
// 20
// 30

for (const value of iterableStr) {
  console.log(value);
}
// "b"
// "o"
// "o"

Iterators

The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.

Iterators

const range = {
  from: 1,
  to: 5,
  [Symbol.iterator]() {
    return this;
  },
  next() {
    if (this.current === undefined) {
      this.current = this.from;
    }

    if (this.current <= this.to) {
      return {
        done: false,
        value: this.current++
      };
    } else {
      delete this.current;
      return {
        done: true
      };
    }
  }
};

for (const num of range) {
  console.log(num); // 1, 2, 3, 4, 5
}

console.log(Math.max(...range)); // 5

Iterators

const someString = 'hi';
console.log([...str]); // ["h", "i"]
console.log(typeof someString[Symbol.iterator]); // "function"

const iterator = someString[Symbol.iterator]();
console.log(iterator + ''); // "[object String Iterator]"

console.log(iterator.next()); // { value: "h", done: false }
console.log(iterator.next()); // { value: "i", done: false }
console.log(iterator.next()); // { value: undefined, done: true }

Links

Iterators

By Andrew Bogomolov