DEV Community

jackma
jackma

Posted on

πŸ”₯ JavaScript Interview Series(2): Hoisting, Scope & Closures

1. What's the output of console.log(x); var x = 5; and why?

Core Concept: Hoisting with var.

Standard Answer: The output will be undefined. This is because of hoisting, a JavaScript mechanism where variable declarations using var are moved to the top of their scope before code execution. So, the code is interpreted as if it were written like this:

var x;
console.log(x);
x = 5;
Enter fullscreen mode Exit fullscreen mode

When console.log(x) is called, x has been declared but not yet assigned a value, so its value is undefined.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. How would the result differ if let or const were used instead of var?
  2. Can you explain the difference between a function declaration and a function expression in the context of hoisting?
  3. How does hoisting affect variables within a function scope versus the global scope?

2. What is the Temporal Dead Zone (TDZ)?

Core Concept: Hoisting with let and const.

Standard Answer: The Temporal Dead Zone is the period between entering a scope and where a let or const variable is declared. While let and const declarations are also hoisted, they are not initialized. Accessing them before the declaration results in a ReferenceError. This helps enforce cleaner code by preventing the use of variables before they are declared.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. Why was the TDZ introduced in ES6?
  2. Can a typeof check still throw a ReferenceError in the TDZ?
  3. How can you practically avoid errors related to the TDZ in your code?

3. What are the different types of scope in JavaScript?

Core Concept: Understanding of JavaScript Scopes.

Standard Answer: JavaScript has three main types of scope:

  • Global Scope: Variables declared outside of any function have global scope and are accessible from anywhere in the code.
  • Function Scope: Variables declared with var inside a function are only accessible within that function.
  • Block Scope: Introduced with ES6, variables declared with let and const inside a block (e.g., in an if statement or for loop) are only accessible within that block.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. Can you explain the concept of lexical scoping?
  2. How does the var keyword behave differently in terms of scope compared to let and const?
  3. What is the scope chain and how does it work?

4. Explain what a closure is in your own words.

Core Concept: Definition and Understanding of Closures.

Standard Answer: A closure is a function that remembers the environment in which it was created. This means it has access to its own scope, the scope of the outer function, and the global scope. A closure can access variables from its outer function even after the outer function has finished executing.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. Can you provide a practical, real-world example of when you would use a closure?
  2. How do closures relate to data privacy and encapsulation in JavaScript?
  3. What are the potential memory implications of using closures?

5. What will the following code log to the console?

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}
Enter fullscreen mode Exit fullscreen mode

Core Concept: Closures and Asynchronous Behavior in Loops.

Standard Answer: This code will log the number 3 three times. The setTimeout callback function is executed after the loop has completed. Since var is function-scoped, there is only one i variable that is shared. By the time the callbacks execute, the loop has finished and the value of i is 3.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. How could you modify this code to log 0, 1, and 2?
  2. Explain how using let instead of var in the loop fixes this issue.
  3. Can you solve this problem without using let, perhaps with an Immediately Invoked Function Expression (IIFE)?

6. How can you use a closure to create a private counter?

Core Concept: Practical Application of Closures for Data Encapsulation.

Standard Answer: You can create a private counter by defining a variable within an outer function and returning an inner function (or an object with methods) that has access to that variable. The outside world cannot access the count variable directly, only through the methods exposed by the closure.

function createCounter() {
  let count = 0;
  return {
    increment: function() {
      count++;
    },
    getValue: function() {
      return count;
    }
  };
}

const counter = createCounter();
counter.increment();
console.log(counter.getValue()); // Logs 1
Enter fullscreen mode Exit fullscreen mode

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. This pattern is related to the "Module Pattern." Can you explain what that is?
  2. What are the benefits of data encapsulation and making variables private?
  3. How could you extend this to include a decrement function?

7. What's the difference between a function declaration and a function expression in terms of hoisting?

Core Concept: Hoisting of Functions.

Standard Answer: A function declaration is fully hoisted, meaning you can call the function before it is defined in the code. A function expression, on the other hand, is not fully hoisted. If it's declared with var, the variable name is hoisted but its value is undefined until the assignment is reached. If declared with let or const, it's subject to the Temporal Dead Zone.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. Can you provide a code example that would work with a function declaration but fail with a function expression due to hoisting?
  2. What are arrow functions and how are they treated in terms of hoisting?
  3. When would you choose to use a function expression over a function declaration?

8. Explain the concept of the scope chain.

Core Concept: Scope Resolution.

Standard Answer: The scope chain is the order in which JavaScript looks for variables. When you try to access a variable, JavaScript starts by looking in the current scope. If it doesn't find the variable there, it moves up to the parent scope and continues this process until it reaches the global scope. If the variable is not found in the global scope, a ReferenceError is thrown.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. How does the scope chain relate to closures?
  2. Can you give an example of a nested function and explain how the scope chain would work in that context?
  3. How can the scope chain impact the performance of your code?

9. What is an Immediately Invoked Function Expression (IIFE) and what is it used for?

Core Concept: IIFEs and Scope Management.

Standard Answer: An IIFE is a JavaScript function that runs as soon as it is defined. It's a common pattern for creating a local scope for variables to avoid polluting the global scope. This is particularly useful in older JavaScript code (before ES6 modules) for creating private variables and functions.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. Can you write the syntax for an IIFE from memory?
  2. How can you pass arguments into an IIFE?
  3. Why are IIFEs less common in modern JavaScript with the introduction of ES6 modules?

10. How do closures and garbage collection interact?

Core Concept: Memory Management with Closures.

Standard Answer: When a closure is created, the variables in its parent scope are not garbage collected as long as the closure exists. This is because the closure might need to access those variables later. If closures are not managed properly, they can lead to memory leaks, where memory is consumed by variables that are no longer needed but are kept alive by a lingering closure.

Possible Follow-up Questions:
πŸ‘‰ (Want to test your skills? Try a Mock Interviews)

  1. Can you give an example of a potential memory leak caused by a closure?
  2. How can modern browser developer tools help you identify memory leaks related to closures?
  3. What are some best practices to avoid memory leaks when using closures?

Top comments (0)