JavaScript Interview Questions and Concepts

Aug 4, 2024

JavaScript Interview Questions

Introduction

  • The video covers five JavaScript questions commonly asked in interviews.
  • Questions will test understanding of JavaScript fundamentals, specifically around let, var, and other concepts.

Question 1: Difference Between let and var

  • Purpose: To check understanding of block scope versus function scope.
  • Explanation:
    • let creates block-scoped variables.
    • Variables defined with let cannot be accessed outside their block.
  • Output Behavior:
    • If let a = 1 and let b = 2 are defined in a block and accessed outside, it will throw a ReferenceError.
    • Only the outputs from within the block will be shown before the error occurs.

Question 2: Hoisting Behavior of var and let

  • Question: What happens when we console.log a variable before it is assigned?
  • Output:
    • For var, it returns undefined because var is hoisted.
    • For let, it throws a ReferenceError due to the Temporal Dead Zone (TDZ).
  • Example with name variable:
    • If var name = '' is declared, console.log(name) outputs an empty string, not undefined.

Question 3: Variable Shadowing

  • Context: Understanding how local and global scopes interact.
  • Example:
    • A global var x = 20 and a local var x = 10 will cause the local variable to shadow the global one.
    • Accessing x inside the function returns undefined because the function creates its variable before the assignment.
  • Key Point: If a local variable exists, the function will not access the global variable.

Question 4: Closures

  • Definition: A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
  • Example:
    • Returning an inner function from an outer function allows access to variables from the outer function.
  • Verification: Using console.dir can show how variables are bundled with the inner function.

Question 5: Event Loop and Asynchronous Behavior

  • Main Idea: Understand the execution order of synchronous vs asynchronous code.
  • Output Sequence: The order of logs will be start, end, and then timeout.
  • Explanation:
    • console.log statements are synchronous and execute in order.
    • setTimeout is asynchronous and does not execute until the call stack is empty, even if the timeout is set to 0 milliseconds.
  • Implication: Event loop processes callbacks only after completing the synchronous code execution.

Conclusion

  • Emphasize understanding the fundamentals of JavaScript rather than memorizing answers.
  • Encouraged to explore more about JavaScript basics and asynchronous behavior.