Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a closure that remembers the initial value.
Javascript
function createCounter() {
let count = 0;
return function() {
count [1] 1;
return count;
};
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '-' instead of '+' causes the count to decrease.
Using '*' or '/' changes the count incorrectly.
β Incorrect
The closure increments the count by 1 each time the inner function is called using '+=' operator.
2fill in blank
mediumComplete the code to create a function that returns a personalized greeting using closure.
Javascript
function greet(name) {
return function() {
return `Hello, [1]!`;
};
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'this.name' does not work because 'this' is not bound here.
Using 'person' or 'greet' are undefined in this scope.
β Incorrect
The inner function uses the 'name' parameter from the outer function to create a personalized greeting.
3fill in blank
hardFix the error in the closure that tries to capture loop variable values.
Javascript
function createFunctions() {
let funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() {
return i;
});
}
return funcs;
}
const functions = createFunctions();
console.log(functions[0]() === [1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Expecting the functions to return 0, 1, 2 instead of 3.
Not understanding how 'var' scope works in loops.
β Incorrect
Using 'var' causes all functions to share the same 'i' which ends at 3 after the loop.
4fill in blank
hardFill both blanks to fix the closure capturing loop variable problem using let.
Javascript
function createFunctions() {
let funcs = [];
for ([1] i = 0; i < 3; i++) {
funcs.push(function() {
return [2];
});
}
return funcs;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'var' causes all functions to share the same variable.
Returning a fixed number instead of the loop variable.
β Incorrect
Using 'let' for 'i' creates a new binding each loop iteration, so each function captures its own 'i'.
5fill in blank
hardFill all three blanks to create a counter with private state and a reset method.
Javascript
function createCounter() {
let count = 0;
return {
increment() {
count [1] 1;
return count;
},
reset() {
count = [2];
},
getCount() {
return [3];
}
};
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '-=' instead of '+=' for increment.
Resetting count to wrong value.
Returning wrong variable in getCount.
β Incorrect
The increment method adds 1 to count, reset sets count to 0, and getCount returns the current count.