IIFE Flashcards
What is an IIFE?
AnIIFEorimmediately invoked function expressionis a function that you define and invoke simultaneously. In JavaScript, we use a special syntax to create and execute an IIFE:
(function() {
console.log(‘hello’);
})(); // => hello
What do the parentheses do in an IIFE?
With IIFEs, the parentheses around the function definition tell JavaScript that we first want to evaluate the function as an expression. We then take the return value of the expression and use function call parentheses to invoke the function. A function declaration must be converted to a function expression before you can invoke it with immediate invocation syntax.
What does an IIFE look like with an arrow function?
((first, second) => first * second)(5, 6); // => 30
How can we use IIFE to create private scope?
// thousands of lines of messy JavaScript code!
console.log((function(array) {
let largest = -Infinity;
for (let index = 0; index < array.length; index += 1) {
if ((array[index] % 2) === 0 && (array[index] > largest)) {
largest = array[index];
}
}
return largest;
})([5, 10, 12, 7, 9, 6, 24, -10, -200, 37])); // 24
// more messy JavaScript code
Why is using IIFEs to create private scope useful?
This allows us to create a private scope where we don’t need to worry about our variable names overlapping with any variable names from the surrounding program. Since the function is also anonymous it has no chance of having the same name as other functions in the program. This helps prevent any unwanted behavior in the code.
how can we use IIFEs to simplify the creation of higher order functions?
function makeUniqueIdGenerator() {
let count = 0;
return function() {
count += 1;
return count;
}
};
let makeUniqueId = makeUniqueIdGenerator();
makeUniqueId(); // => 1
makeUniqueId(); // => 2
makeUniqueId(); // => 3
—————————————————
const makeUniqueId = (function() {
let count = 0;
return function() {
++count;
return count;
};
})();
makeUniqueId(); // => 1
makeUniqueId(); // => 2
makeUniqueId(); // => 3
can you create private scopes with blocks?
In ES6 JavaScript and later, you can use blocks to create private scopes. For instance:
// thousands of lines of messy JavaScript code!
{
let array = [5, 10, 12, 7, 9, 6, 24, -10, -200, 37];
let largest = -Infinity;
for (let index = 0; index < array.length; index += 1) {
if ((array[index] % 2) === 0 && (array[index] > largest)) {
largest = array[index];
}
}
console.log(largest); // 24
}
// more messy JavaScript code
what’s the difference between private scopes and private data?
As similar as those two questions sound, they refer to different concepts. When we talk about private scope, we’re talking about how you can use scope to prevent some code from making accidental changes to variables in its outer scope. When we discuss private data, we’re talking about encapsulation: making local data inaccessible from the code’s outer scope.