What is polyfilling in JavaScript and How does callbacks works
4/30 of LeetCode’s 30 days of JavaScript Solution and Explanation
The problem today needs a little introduction around how callbacks work and how using that you can code some of the Modern Methods like map
So lets first jump into the very first question
What is Polyfilling?
It's a very basic but Important topic to understand as this will help your code reach towards a wider set of people and can impact the product reputation.
As the JavaScript community grows and new and new features and versions keep on coming a lot of Old age browsers or machines running Older version of a browser client won't be able to support but and some or many of your clients still belong to
that category so how you make sure the code you write will be supported in older browsers or versions of it?
You create polyfill which is the implementation of the Modern Method into a trivial function which uses the most basic components of JS which will be supported by almost all browsers and versions and the solution of today's problem is one such example.
Now Coming to the next Question
What are Callbacks and how do they work?
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
as we saw in our code here
const map = function(arr, fn)
and also in-fact here
mappedArr.push(fn(arr[i],parseInt(i)))
so if you guys remember the Call Stack In similar way JavaScript also uses one more data structure called Callback Queue
the diagram here depicts how call stack and callback queues are used together in an Event Loop
Code
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
const map = function(arr, fn) {
const mappedArr=[]
for(const i in arr){
mappedArr.push(fn(arr[i],parseInt(i)))
}
return mappedArr
};
Conclusion
JavaScript ecosystem grows fast and sometimes some of the other applications might not be caught up so In order for us to support our product we need to make our application backwards compatible and here Polyfills play an important role along with that passing a function inside of other function allows us to control the execution and result of the other function which allows us to decouple the code better using callbacks.
Previous Article — https://medium.com/@varnitsharma-102/arrow-functions-and-a-better-way-of-functional-object-oriented-programming-in-js-5e1542cd02fe
Problem — https://leetcode.com/problems/apply-transform-over-each-element-in-array/description/