cft

Polyfills in javascript

What are polyfills? Why use them? How to write polyfills?


user

Udit

a year ago | 1 min read

There are several browsers on which our js code runs. There are several versions and implementations of these browsers. There might be a situation where there is some functionality missing in one browser while present in another. We write code to fill those functionalities so that our code or web app stays consistent with users viewing it on any screen.

In web development, a polyfill is a code that implements a feature on web browsers that do not support the feature. Most often, it refers to a JavaScript library that implements an HTML5 web standard.So in short - polyfill is code that allow us programmers to use new API in older browsers. Usually we use some library that add missing functionality or we can implementmissing methods by ourselves.

They let you provide deeper backwards compatibility and browser support without having to use a clunky preprocessor or command line tool.

It doesn’t work for everything. You can polyfill new Object types and methods, but you can’t polyfill expressions and operators.

For example:

  • The Array.prototype.map() the method can be polyfilled
  • Arrow functions, the spread operator, and template literals cannot

Let’s look at how to write polyfills.

Checking for the native method first #

Let’s look at the String.countAll(ch) method.

Before poly filling it, the first thing I want to do is make sure a native version of it doesn’t exist. We only want to run our polyfill if there’s not a native version available.

In this case, the countAll() method is on the String.prototype object, so we check for that.

// Make sure there's no native method available first

if (!String.prototype.

countAll

) {

// Add some polyfill code...

}

Next, we need to create a function for the method we’re poly filling , and set up some arguments.

In this case, the countAll() method accepts one argument: the substring to count its occurrences.

if (!String.prototype.

countAll

) {

String.prototype.

countAll

= function (ch){

// Recreate the native method here...

};}

Recreating the native function #

Now, we’re ready to actually recreate the native method.

To do this, you need to think about what native, better supported methods and approaches already exist that you can use to accomplish the same task.

Error handling #

Depending on how your polyfill is set up, it may be a good idea to check that all required variables are provided and are of the correct type.

Upvote


user
Created by

Udit

Full stack developer


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles