DEV Community

Hemendra Khatik
Hemendra Khatik

Posted on • Updated on • Originally published at blog.aamchora.space

Polyfills and Transpilers in JavaScript.

Have you ever been in a situation where your code runs in one browser and fails in another?

And you would be wondering what the hell is happening??

What the hell is happening

Even after checking your code thoroughly, over and over again, you find it 100% correct.

Then where the hell actual problem lies in?

where is the problem

Let's understand this weird behaviour of JavaScript.

As we all know, JavaScript keeps on evolving over time. The browsers need to be updated with the time too.

If we don't update our browser, Modern JavaScript code will fail on the older versions of the browsers.

So basically It's not your fault It's the browser's fault.

Pro Tip: Don't forget to update your browser.

But wait...

We don't want to give users a bad user experience.

Is there any way we can fix this issue..?

is there any way?

And the answer is ...

Yes! we're magicians.

We gotta learn new magic mantras for this.

And those are:

  • Polyfill's Mantra
  • Transpiler's Mantra

Polyfill's Mantra

A polyfill is a piece of code used to provide modern functionality on older browsers that do not natively support it.

EG:

let str = 'hello world';

console.log(str.includes('hello')); // true
console.log(str.includes('bye')); //false
Enter fullscreen mode Exit fullscreen mode

If you run the above code in updated versions of Chrome, firebox, safari, etc. It will work fine.

But if you run it in Internet Explorer 11 you will face an error as below.

IE 11

To make our code run in older engines we need to write a polyfill for includes function.


// Checking if includes method exist or not
if (!String.prototype.includes) {
    // polyfill method
    String.prototype.includes = function (searchString) {
    let isFound = false;

    // here <this> refers to the string it self
    if (this.indexOf(searchString) !== -1) {
      isFound = true;
    }
    return isFound;
  }
} 

// Now it will work in IE 11 too.

let str = 'hello world';

console.log(str.includes('hello')); // true
console.log(str.includes('bye')); //false

Enter fullscreen mode Exit fullscreen mode

Transpiler's Mantra

A transpiler is a piece of software that translates one source code to another source code. It can parse modern code and rewrite it using the older syntax of that language so that it will also work in outdated engines.

Transpiler

Babel is one of the most used transpilers out there.

Usually, developer runs the transpiler on their own computer or in the cloud and then deploys the transpiled code to the server.

Tip: Remember these two mantras, and your code will never fail.

Powers


Do let me know if this blog was helpful

follow me for more such blog posts.

Twitter || Linkedin

Top comments (0)