Polyfilling and Transpiling in JavaScript

JavaScript | Polyfilling and Transpiling: In this tutorial, we are going to learn about the Polyfilling and Transpiling in JavaScript with examples.
Submitted by Siddhant Verma, on November 24, 2019

JavaScript is rapidly advancing. Today it's the most popular programming/scripting language that devs use to code logic and applications and is used in umpteen number of places. The community behind its development hasn't stopped creating and adding new features to JavaScript to make it more lively, easy and even more powerful. However, the drawback which tags along whenever a language or framework rapidly advances with new changes coming in all the time is their support on the browsers. We know that JavaScript compiles on the browser and it is important for the browser to understand what JavaScript you are writing. Newser features take time to be interpreted by the browsers and sometimes some versions of certain browsers purposely restrain support for new features because of stability. But as a dev, we can't use this as an excuse to not learn what's new for us. So how do we ensure that modern JS runs perfectly on older versions of our browsers?

1) Polyfilling

A polyfill is a piece of code or a plugin that enables modern JavaScript features to run on older versions of the browser. It's just a trick or workaround where modern features are coded in and out using older features so the browser can understand.

For example, ES15 allows us to check is a value is a number or not using the isNaN() method.

isNaN(44);
isNaN('hello');

Output

false
true

IsNaN() checks for values that do not a number. It returns true if the value passed in as a parameter is not a number and false if it is a number. Being a new feature, some browsers may not support it. So we can implement our own NaN as a polyfill and replicate its behavior that the browser can understand.

Number.isNaN = function isNaN(n) {
    return n !== n;
};

We can also check if the method is not already available for the browser first and then define it.

if (!Number.isNan) {
    Number.isNaN = function isNaN(n) {
        return n !== n;
    };
}

The downside of polyfills is that all features can't be coded as polyfills however, it's still very commonly used by developers for features that can be easily coded.

2) Transpiling

The newer syntax cannot be replicated using Polyfills. No matter whatever we do, we will get an undefined syntax error and this is where transpiling comes to the rescue. You can break down transpiling as a combination of two words- transforming and compiling. Now you can easily understand that transpiling is a tool that transforms newer syntax into the older one, that the browser can understand. The most commonly used transpiler is babel which does all the work for us. To demonstrate, let's code some newer syntax see how they are transpiled by babel.

Go to https://babeljs.io/repl and on the left editor, we'll write some newser JS syntax which babel will transpile to older syntax on the right editor.

const add = (a, b) => {
    console.log(`${a} + ${b} = ${a+b}`);
}

Output

"use strict";

var add = function add(a, b) {
  console.log("".concat(a, " + ").concat(b, " = ").concat(a + b));
};

As you can see we have used three modern features, the const keyword, array function and template strings and all of them are converted to older syntax.

const multiply = (a = 5, b = 3) => {
    console.log(a * b);

};

Output

"use strict";

var multiply = function multiply() {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 5;
  var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
  console.log(a * b);
};

Using default value parameter is also a fairly newer feature and babel compiles it into a code understandable in terms of older syntax of JS. Let's look at a last example,

class Student {
    constructor(name, rollNo) {
        this.name = name;
        this.rollNo = rollNo;
        this.attendance = 0;
    }
    isPresent() {
        this.attendance++;
    }
}

A little object oriented JS to create a small class for Students. And we look at the right...

Output

"use strict";

function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }

function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, 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 Student =
/*#__PURE__*/
function () {
  function Student(name, rollNo) {
    _classCallCheck(this, Student);

    this.name = name;
    this.rollNo = rollNo;
    this.attendance = 0;
  }

  _createClass(Student, [{
    key: "isPresent",
    value: function isPresent() {
      this.attendance++;
    }
  }]);

  return Student;
}();

Oh now, what sorcery is this? A few lines of code transpiled into a monstrous amount of code! Imagine how many lines of code and complexity you save by using newer features. If you had to use the older syntax you'd actually have to write that much! Insanely amazing.

JavaScript Tutorial »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.