RaghavBang
Published in

RaghavBang

Most asked JavaScript Interview Questions: Part 2

  1. When are Arrow function, function declaration, function statement and function expression?
  • Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
  • An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression.
  • https://www.geeksforgeeks.org/what-is-a-typical-use-case-for-anonymous-functions-in-javascript
  • Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
  • A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable
function fakeFetch(msg, shouldReject) { 
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldReject) {
reject(`error from server: ${msg}`)
}
resolve(`from server: ${msg}`)
}, 3000)
})}
fakeFetch("Hi",true) // it will take reject state
fakeFetch("Bye") //it will take resolve state
  • map Polyfill

Array.prototype.myMap = function(callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
/* call the callback function for every value of this array and push the returned value into our resulting array
*/

arr.push(callbackFn(this[i], i, this));
}
return arr;
}
  • filter polyfill
Array.prototype.myFilter = function(callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (callbackFn.call(this, this[i], i, this)) {
arr.push(this[i]);
}
}
return arr;
}
  • reduce polyfill
Array.prototype.myReduce= function(callbackFn, initialValue) {
var accumulator = initialValue;for (var i = 0; i < this.length; i++) {
if (accumulator !== undefined) {
accumulator = callbackFn.call(undefined, accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
}

--

--

Technical blogs, Mini project idea, Coding and updates about new technology

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store