0
0
Javascriptprogramming~10 mins

Practical closure use cases in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A-=
B+=
C*=
D/=
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using '-' instead of '+' causes the count to decrease.
Using '*' or '/' changes the count incorrectly.
2fill in blank
medium

Complete 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'
Athis.name
Bgreet
Cname
Dperson
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.
3fill in blank
hard

Fix 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'
A0
B1
Cundefined
D3
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.
4fill in blank
hard

Fill 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'
Alet
Bvar
Ci
D0
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.
5fill in blank
hard

Fill 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'
A+=
B0
Ccount
D-=
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using '-=' instead of '+=' for increment.
Resetting count to wrong value.
Returning wrong variable in getCount.