0
0
Javascriptprogramming~10 mins

Closures 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 returns a function adding a fixed number.

Javascript
function makeAdder(x) {
  return function(y) {
    return x [1] y;
  };
}

const add5 = makeAdder(5);
console.log(add5(3));
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
2fill in blank
medium

Complete the code to create a counter using closure that increments by 1 each call.

Javascript
function createCounter() {
  let count = 0;
  return function() {
    count [1] 1;
    return count;
  };
}

const counter = createCounter();
console.log(counter());
Drag options to blanks, or click blank then click option'
A-=
B*=
C+=
D/=
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using subtraction or multiplication instead of addition assignment.
3fill in blank
hard

Complete the code to demonstrate how closures capture the loop variable correctly with `let`, returning i + 1 for each function.

Javascript
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]());
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
4fill in blank
hard

Complete the code to create a closure that filters numbers greater than 5.

Javascript
function filterGreaterThanFive(arr) {
  return arr.filter(function(num) {
    return num [1] 5;
  });
}

const result = filterGreaterThanFive([3, 7, 2, 9]);
console.log(result);
Drag options to blanks, or click blank then click option'
A<
B>
C===
D!==
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using less than or equality operators instead of greater than.
5fill in blank
hard

Fill all three blanks to create a closure that maps words to their lengths if length is greater than 3.

Javascript
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);
Drag options to blanks, or click blank then click option'
Aword
Blen
Dlength
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using incorrect variable names or properties for length.