A polyfill is a piece of code that implements a functionality that is not natively supported by a browser. Old browsers might not have a native functionality provided by newer browser versions. To make it work on older browsers we generally write or use polyfills.

Such Javascript interview questions come in one of the below variations:

  • Implement a polyfill for bind
  • Suppose the browser does not provide a bind functionality, how would you implement it?
  • Implement bind using apply or call

For such questions, you are expected to implement the functionality from scratch.

How to approach ‘polyfill type’ problems in Javascript Interview?

  1. Write down the usage scenarios for the functionality. How is it used? What syntax it follows? If you don’t remember the exact syntax, it’s ok to ask the interviewer in most of the cases. They should be happy to help.

  2. Create test cases. It will make it easier to come up with an implementation that handles edge cases.

  3. Implement - Write the code.

  4. Do a dry run with the test cases created in the step 2.

Solution

We’ll use the approach discussed above to implement a polyfill for .bind() function in javascript.

You can skip this section and jump directly to test cases or implementation if you know the in and out of .bind()

#functions #closures #javascript

Implement a .bind() polyfill in Javascript
16.45 GEEK