Js interviews are pretty much tricky in nature. Since js realm consist of myriad libraries and frameworks it demands a huge time for brief preperation itself. But many companies focus only on your core domain and technical understanding, here comes the importance of fundamentals.
Two importance areas companies evaluate are design patterns and your ability to write robust and reusable code.
That is the primary reason most of the interviewer 've this question in their bag. Here i try to explain two commonly asked polyfill questions.One is bind and another one is reduce
Let's start with bind. Bind method enable us to call a function with different context.Bind primarily return a new function which has context provided as first argument and parameters as second.
Function.prototype.customBind=function(...args){
let params = args.slice(1);
let tempObj= {
fn:this,
...args[0]
}
return ()=>tempObj.fn(...params);
}
The catch here is the this
value of our customBind , since it is getting called on another function we 'll receive a function as this
.
const obj={
name:"Adam"
}
function show(age){
console.log(this.name,age)
}
let outFn = show.customBind(obj,29);
Considering above code snippet , we 'll receive function show as this
value inside cutomBind.
Reduce is another one ,find my custom reduce function here
Array.prototype.customReduce = function(fn,acc){
let contextArr = this;
for(let i=0;i<contextArr.length;i++){
acc = acc!==undefined?fn(acc,contextArr[i]):contextArr[0];
}
return acc
}
Here reduce method has two parameters 1. function 2. accumulator later one is optional. In this case we need to add this function to Array prototype since it is an array function , thus value of this
become the provided array upon which we called the reduce method. we can then iterate over the array and make an accumulated value by running the function provided.
Top comments (0)