Babel makes modern JavaScript viable for a wide audience, which has freed developers to adopt newer language features aggressively. But the code users actually download doesn't always reflect the compactness of what's in the editor. Several commonplace transformations expand dramatically once preprocessed, and in many of those cases a simpler, older construct does the same job without the weight. The point isn't old versus new — it's picking the implementation that meets the goal without importing the side effects of the build pipeline. Babel's online REPL makes these expansions easy to inspect; the examples below target browsers without ES2015+ support.

Loops: for..of and iterables

A for..of loop written against an array looks like it should compile down to something close to a traditional for. It doesn't. The 98-byte input:

function getList() {
  return [1, 2, 3];
}

for (let value of getList()) {
  console.log(value);
}

becomes 1.8kb of output — a 1736% increase:


"use strict";

function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function getList() {
  return [1, 2, 3];
}

var _iterator = _createForOfIteratorHelper(getList()),
    _step;

try {
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
    var value = _step.value;
    console.log(value);
  }
} catch (err) {
  _iterator.e(err);
} finally {
  _iterator.f();
}

The reason is that Babel can't know the value being iterated is an array. All it sees is a function that might return any iterable — array, string, object, NodeList — and per the ECMAScript specification for for..of it must handle every possibility. Explicitly passing an array would shrink the output drastically, but that's rarely practical in a real codebase. When break and continue statements are needed and bundle size matters, the plain for loop is the safer bet.

function getList() {
  return [1, 2, 3];
}


for (var i = 0; i < getList().length; i++) {
  console.log(getList()[i]);
}

Dave Rupert documented this same problem and settled on forEach, even polyfilled, as his solution.

Spreading arrays

The spread operator works across more than one kind of object, so when Babel can't determine the type it takes defensive measures — and those measures cost bytes. An 81-byte input:

function getList () {
  return [4, 5, 6];
}


console.log([1, 2, 3, ...getList()]);

compiles to 1.3kb:

"use strict";

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function getList() {
  return [4, 5, 6];
}

console.log([1, 2, 3].concat(_toConsumableArray(getList())));

concat() reaches the same result directly. The amount of code to write is barely different, behavior is exactly as intended, and the bloat disappears.

function getList () {
  return [4, 5, 6];
}


console.log([1, 2, 3].concat(getList()));

The NodeList case

Spreading a queried NodeList into an array so forEach can be used on it is a familiar pattern:

[...document.querySelectorAll('.my-class')].forEach(function (node) {
  // do something
});

It also produces the heavy output described above. Running the NodeList through an Array prototype method such as slice gives the same result with far less baggage.

[].slice.call(document.querySelectorAll('.my-class')).forEach(function(node) {
  // do something
});

What loose mode trades away

Some of the array-related bloat can be avoided with @babel/preset-env's loose mode, which gives up strict fidelity to modern ECMAScript semantics in exchange for slimmer output. It may work fine in many situations, but it asks Babel to make bold assumptions about how your code is used, and that risk can surface later. Being deliberate about which features you reach for is often a better investment than tuning the build and then dealing with unseen consequences.

Default parameters

Default parameter values from ES2015 tidy up signatures for optional arguments, and their transformation is predictable. But used repeatedly across a codebase, the extra bytes accumulate. A 75-byte input:

function getName(name = "my friend") {
  return `Hello, ${name}!`;
}

yields 169 bytes:

"use strict";


function getName() {
  var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "my friend";
  return "Hello, ".concat(name, "!");
}

An alternative skips the arguments object entirely and checks whether the parameter is undefined. That loses the self-documenting quality of default parameters, but when bytes are tight it can be worth it. Depending on the use case, a falsey check may slim things further still.

function getName(name) {
  name = name || "my friend";
  return `Hello, ${name}!`;
}

async/await

async/await is syntactic sugar over the Promise API, but out of the box Babel doesn't compile it to promises. It emits generators backed by the regenerator-runtime library instead. A 157-byte input:

async function fetchSomething(url) {
  const response = await fetch(url);
  return await response.json();
}

fetchSomething("https://google.com");

compiles to 1.5kb:

"use strict";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function fetchSomething(_x) {
  return _fetchSomething.apply(this, arguments);
}

function _fetchSomething() {
  _fetchSomething = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) {
    var response;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return fetch(url);

          case 2:
            response = _context.sent;
            _context.next = 5;
            return response.json();

          case 5:
            return _context.abrupt("return", _context.sent);

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _fetchSomething.apply(this, arguments);
}

fetchSomething("https://google.com");

A plugin like babel-plugin-transform-async-to-promises routes the transformation through promises instead, cutting the output to 638 bytes:

"use strict";


function _await(value, then, direct) {
  if (direct) {
    return then ? then(value) : value;
  }


  if (!value || !value.then) {
    value = Promise.resolve(value);
  }


  return then ? value.then(then) : value;
}


var fetchSomething = _async(function (url) {
  return _await(fetch(url), function (response) {
    return _await(response.json());
  });
});


function _async(f) {
  return function () {
    for (var args = [], i = 0; i < arguments.length; i++) {
      args[i] = arguments[i];
    }


    try {
      return Promise.resolve(f.apply(this, args));
    } catch (e) {
      return Promise.reject(e);
    }
  };
}

That plugin, however, affects transformations across the entire project and adds another build dependency. Simply writing against the Promise API directly avoids both problems.

function fetchSomething(url) {
  return fetch(url).then(function (response) {
    return response.json();
  }).then(function (data) {
    return resolve(data);
  });
}

Classes

ES2015 class syntax streamlines JavaScript's prototypical inheritance, but transpiling it for older browsers produces nothing streamlined. Input of 120 bytes:

class Robot {
  constructor(name) {
    this.name = name;
  }


  speak() {
     console.log(`I'm ${this.name}!`);
  }
}

becomes 989 bytes:

"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var Robot = /*#__PURE__*/function () {
  function Robot(name) {
    _classCallCheck(this, Robot);

    this.name = name;
  }

  _createClass(Robot, [{
    key: "speak",
    value: function speak() {
      console.log("I'm ".concat(this.name, "!"));
    }
  }]);

  return Robot;
}();

Unless the inheritance is fairly involved, the pseudoclassical approach is straightforward enough: it takes slightly less code to write, and the interface it produces is virtually identical to a class.

function Robot(name) {
  this.name = name;


  this.speak = function() {
    console.log(`I'm ${this.name}!`);
  }
}


const rob = new Robot("Bob");
rob.speak(); // "Bob"

Choosing a strategy

What counts as a reasonable bundle-size strategy depends on the audience. A team that has already dropped support for Internet Explorer and other legacy browsers — increasingly common, given how widely ES2015+ is supported — might get more value from auditing the browser list its build targets and confirming it isn't shipping unnecessary polyfills. Teams still obliged to support older browsers can ship the heavy, preprocessed bundles only to the users who need them, for example through differential serving. Which combination a team prioritizes matters less than making the decision deliberately, with the build output in view.

Inspect what you ship

Modern features make applications easier to write, maintain, scale and read. As long as writing JavaScript means preprocessing JavaScript, though, it's worth checking periodically what those features cost the people downloading them. Sometimes that inspection reveals the chance to dodge a hefty transformation with a classic alternative. At worst, it deepens your appreciation of what Babel is doing on your behalf.