Complete the code to create a closure that returns a function adding a fixed number.
function makeAdder(x) {
return function(y) {
return x [1] y;
};
}
const add5 = makeAdder(5);
console.log(add5(3));The closure captures x and adds it to y using the + operator.
Complete the code to create a counter using closure that increments by 1 each call.
function createCounter() {
let count = 0;
return function() {
count [1] 1;
return count;
};
}
const counter = createCounter();
console.log(counter());The closure updates count by adding 1 each time the returned function is called using +=.
Complete the code to demonstrate how closures capture the loop variable correctly with `let`, returning i + 1 for each function.
function createFunctions() {
let funcs = [];
for (let i = 0; i < 3; i++) {
funcs.push(function() {
return i [1] 1;
});
}
return funcs;
}
const functions = createFunctions();
console.log(functions[0]());The closure captures i correctly due to block scoping with let and adds 1 to it using the + operator.
Complete the code to create a closure that filters numbers greater than 5.
function filterGreaterThanFive(arr) {
return arr.filter(function(num) {
return num [1] 5;
});
}
const result = filterGreaterThanFive([3, 7, 2, 9]);
console.log(result);The function filters numbers greater than 5 using the > operator.
Fill all three blanks to create a closure that maps words to their lengths if length is greater than 3.
function mapLongWords(words) {
return Object.fromEntries(
words.filter(function([1]) {
return [1].[2] > 3;
})
.map(function([3]) {
return [[3], [3].[2]];
})
);
}
const result = mapLongWords(['cat', 'elephant', 'dog', 'giraffe']);
console.log(result);The code uses filter and map with closures to create an object mapping each word to its length if the length is greater than 3, then Object.fromEntries converts the array of entries to an object.