Thursday, June 7, 2018

JavaScript For Of Loop

Though the new JavaScript for/of loop construct is a nice syntactic sugar and similar to the foreach loop find in C#. It is worth noting that the behind the scene the implementation is based on an iterator.

eslint has even a rule to not let you use it.

error iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations  no-restricted-syntax

const list = [1,2,3];

for(let i=0; i < list.length; i++) { // Old syntax
  console.log(list[i]);
}

for(let i of list) { // New syntax
  console.log(i);
}
Transpiled with BabelJS.io  [Link]

"use strict";

var list = [1, 2, 3];
for (var i = 0; i < list.length; i++) {
  console.log(list[i]);
}



var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var _i = _step.value;

    console.log(_i);
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

No comments:

Post a Comment