@babel/plugin-transform-for-of

Example

In

  1. for (var i of foo) {}

Out

  1. var _iteratorNormalCompletion = true;
  2. var _didIteratorError = false;
  3. var _iteratorError = undefined;
  4. try {
  5. for (var _iterator = foo[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  6. var i = _step.value;
  7. }
  8. } catch (err) {
  9. _didIteratorError = true;
  10. _iteratorError = err;
  11. } finally {
  12. try {
  13. if (!_iteratorNormalCompletion && _iterator.return != null) {
  14. _iterator.return();
  15. }
  16. } finally {
  17. if (_didIteratorError) {
  18. throw _iteratorError;
  19. }
  20. }
  21. }

Installation

  1. npm install --save-dev @babel/plugin-transform-for-of

Usage

.babelrc

Without options:

  1. {
  2. "plugins": ["@babel/plugin-transform-for-of"]
  3. }

With options:

  1. {
  2. "plugins": [
  3. ["@babel/plugin-transform-for-of", {
  4. "loose": true, // defaults to false
  5. "assumeArray": true // defaults to false
  6. }]
  7. ]
  8. }

Via CLI

  1. babel --plugins @babel/plugin-transform-for-of script.js

Via Node API

  1. require("@babel/core").transform("code", {
  2. plugins: ["@babel/plugin-transform-for-of"]
  3. });

Options

loose

boolean, defaults to false

In loose mode, arrays are put in a fast path, thus heavily increasing performance.All other iterables will continue to work fine.

Example

In

  1. for (var i of foo) {}

Out

  1. for (var _iterator = foo, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  2. var _ref;
  3. if (_isArray) {
  4. if (_i >= _iterator.length) break;
  5. _ref = _iterator[_i++];
  6. } else {
  7. _i = _iterator.next();
  8. if (_i.done) break;
  9. _ref = _i.value;
  10. }
  11. var i = _ref;
  12. }

Abrupt completions

In loose mode an iterator's return method will not be called on abrupt completions caused by thrown errors.

Please see google/traceur-compiler#1773 andbabel/babel#838 for more information.

assumeArray

boolean, defaults to false

This will apply the optimization shown below to all for-of loops by assuming that all loops are arrays.

Can be useful when you just want a for-of loop to represent a basic for loop over an array.

Optimization

If a basic array is used, Babel will compile the for-of loop down to a regular for loop.

In

  1. for (let a of [1,2,3]) {}

Out

  1. var _arr = [1, 2, 3];
  2. for (var _i = 0; _i < _arr.length; _i++) {
  3. var a = _arr[_i];
  4. }

You can read more about configuring plugin options here