Arrow Functions, Higher-Order Functions, Immediately Invoked Function Expressions
What Are Arrow Functions? How Are They Different from Regular Functions?
- Arrow functions have a different syntax and are more concise. They omit the
functionkeyword. If there is only one parameter, the parentheses can be omitted; if there is only one line of code that simply returns a variable or a simple expression, the braces and thereturnkeyword can also be omitted. - Arrow functions do not have their own
this, and they cannot directly change the binding ofthis. - Arrow functions do not have their own
arguments; instead, they access theargumentsobject of the closest non-arrow function. - Arrow functions cannot be used as constructors. In other words, they cannot be called with the
newkeyword, otherwise an error will occur.
What Is a JavaScript IIFE (Immediately Invoked Function Expression)? What Are Its Pros and Cons?
- An anonymous function that is executed immediately at the moment it is defined. It is commonly used to create a local scope and avoid polluting the global scope. The parentheses for the function definition and the function call are combined, ensuring that the function is executed only once rather than being callable multiple times after definition.
(function () {
// Code to be executed
})();
- Common example questions
for (var i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 0);
}
// Immediately prints five 6's
6;
6;
6;
6;
6;
for (const i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 0);
}
// Immediately prints 1 to 5
1;
2;
3;
4;
5;
- Explanation:
varshares the same variable reference, so the closure sees the “last written” value.letcreates a new variable for each loop iteration, so the closure sees the “value bound for that iteration.” A closure captures the “variable binding” (environment binding), not a “snapshot of the value.”
What Is a Higher-Order Function? What Are the Benefits of Using Higher-Order Functions?
- A higher-order function is a function that can accept another function as an argument, or return a function as its result.
- The principle behind
map
function map(arr,callback) {
const result = [];
for(let i=0;i<arr.length;i++){
const item=arr.i;
result.push(callback(item));
}
return result;
}