20

7 Interview Questions on JavaScript Closures. Can You Answer Them?

 3 years ago
source link: https://dmitripavlutin.com/javascript-closures-interview-questions/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

7 Interview Questions on JavaScript Closures. Can You Answer Them?

Every JavaScript developer must know what a closure is. During a JavaScript coding interview there’s a good chance you’ll get asked about the concept of closures.

I compiled a list of 7 interesting and increasingly challenging questions on JavaScript closures.

Take a pencil and a piece of paper, and try to answer the questions without looking at the answers, or running the code. In my estimation, you would need about 30 minutes.

Have fun!

If you need a refresh on closures, I recommend checking the post A Simple Explanation of JavaScript Closures.

Questions 1: Closures raise your hand

Consider the following functions clickHandler, immediate, and delayedReload:

let countClicks = 0;
button.addEventListener('click', function clickHandler() {
  countClicks++;
});
const result = (function immediate(number) {
  const message = `number is: ${number}`;
  return message;
})(100);
setTimeout(function delayedReload() {
  location.reload();
}, 1000);

Which of these 3 functions access outer scope variables?

Expand answer

Questions 2: Lost in parameters

What will log to console the following code snippet:

(function immediateA(a) {
  return (function immediateB(b) {
    console.log(a); // What is logged?
  })(1);
})(0);

Expand answer

Questions 3: Who’s who

What will log to console the following code snippet:

let count = 0;
(function immediate() {
  if (count === 0) {
    let count = 1;
    console.log(count); // What is logged?
  }
  console.log(count); // What is logged?
})();

Expand answer

Questions 4: Tricky closure

What will log to console the following code snippet:

for (var i = 0; i < 3; i++) {
  setTimeout(function log() {
    console.log(i); // What is logged?
  }, 1000);
}

Expand answer

Questions 5: Right or wrong message

What will log to console the following code snippet:

function createIncrement() {
  let count = 0;
  function increment() { 
    count++;
  }

  let message = `Count is ${count}`;
  function log() {
    console.log(message);
  }
  
  return [increment, log];
}

const [increment, log] = createIncrement();
increment(); 
increment(); 
increment(); 
log(); // What is logged?

Expand answer

Questions 6: Restore encapsulation

The following function createStack() creates instances of stack data structure:

function createStack() {
  return {
    items: [],
    push(item) {
      this.items.push(item);
    },
    pop() {
      return this.items.pop();
    }
  };
}

const stack = createStack();
stack.push(10);
stack.push(5);
stack.pop(); // => 5

stack.items; // => [10]
stack.items = [10, 100, 1000]; // Encapsulation broken!

The stack works as expected, but with one small problem. Anyone can modify items array directly because stack.items property is exposed.

That’s an issue since it breaks the encapsulation of the stack: only push() and pop() methods should be public, but stack.items or any other details shouldn’t be accessible.

Refactor the above stack implementation, using the concept of closure, such that there is no way to access items array outside of createStack() function scope:

function createStack() {
  // Write your code here...
}

const stack = createStack();
stack.push(10);
stack.push(5);
stack.pop(); // => 5

stack.items; // => undefined

Expand answer

Questions 7: Smart multiplication

Write a function multiply() that multiples 2 numbers:

function multiply(num1, num2) {
  // Write your code here...
}

If multiply(num1, numb2) is invoked with 2 arguments, it should return the multiplication of the 2 arguments.

But if invoked with 1 argument const anotherFunc = multiply(num1), the function should return another function. The returned function when called anotherFunc(num2) performs the multiplication num1 * num2.

multiply(4, 5); // => 20
multiply(3, 3); // => 9

const double = multiply(2);
double(5);  // => 10
double(11); // => 22

Expand answer

Summary

Compare your answers with the answers in the post:

  • You have a good understanding of closures if you answered correctly 5 or more questions
  • But you need a good refresher on closures if you answered correctly less than 5 questions. I recommend checking my post A Simple Explanation of JavaScript Closures.

Ready for a new challenge? Try to solve the 7 Interview Questions on “this” keyword in JavaScript.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK