5 Questions on JavaScript Closures
by Kwiz
Qs
5
Difficulty
Mid
Plays
1
Record
n/a
Description

This quiz on JavaScript closures is based on the fantastic & in-depth article by one of the most prolific thought-leaders & bloggers in the React / JS space: Dmitri Pavlutin. The questions you'll find in this quiz are based on his article 7 Interview Questions on JavaScript Closures. Can You Answer Them?.

This quiz includes 5 questions from the article that you might encounter while interviewing for a React or JavaScript developer role, and each question includes in-depth explanations written by Dmitri that you can view once you've completed the quiz! The questions in this quiz are challenging, but also extremely important for front-end developers to understand.

Good luck!

Make sure to follow Dmitri on Twitter and check out his blog

Question Preview
Which of these 3 functions access outer scope variables?
/** 
  Note: consider each function to be running in its own file
*/

// Function 1
let countClicks = 0;
button.addEventListener('click', function clickHandler() {
  countClicks++;
});

// Function 2
const result = (function immediate(number) {
  const message = `number is: ${number}`;
  return message;
})(100);

// Function 3
setTimeout(function delayedReload() {
  location.reload();
}, 1000);
Question Preview
What will the following code snippet log to the console?
(function immediateA(a) {
  return (function immediateB(b) {
    console.log(a); // What is logged?
  })(1);
})(0);
Question Preview
What will the following code snippet log to the console?
let count = 0;
(function immediate() {
  if (count === 0) {
    let count = 1;
    console.log(count); // What is logged?
  }
  console.log(count); // What is logged?
})();
Question Preview
What will the following code snippet log to the console?
for (var i = 0; i < 3; i++) {
  setTimeout(function log() {
    console.log(i); // What is logged?
  }, 1000);
}
Question Preview
What will the following code snippet log to the console?
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?