Scope

Understand global vs local scope, hoisting, and closures in JavaScript.

Present State

Scope in JavaScript defines the accessibility of variables and functions in different parts of the code. Understanding the difference between global and local scope, hoisting behavior, and closures is crucial for writing bug-free and maintainable code.

Code Example

Example demonstrating scope, hoisting, and closures:

JavaScript Scope Example

// Global Scope
var globalVar = "I am global";

function outer() {
  // Local Scope
  var localVar = "I am local";

  function inner() {
    // Closure capturing localVar
    console.log(globalVar); // Accessible (global)
    console.log(localVar);  // Accessible (closure)
  }

  inner();
}

outer();

// Hoisting example
console.log(hoistedVar); // undefined (due to hoisting)
var hoistedVar = "This is hoisted";

// let/const are not hoisted in the same way:
// console.log(notHoisted); // ReferenceError
// let notHoisted = 10;
          

This code demonstrates:

  • The difference between global and local scope.
  • How closures allow inner functions to access outer variables.
  • Variable hoisting behavior with var.
  • Difference in hoisting with let and const.

Description

Scope: Defines the visibility and lifetime of variables and functions in JavaScript.

  • Global Scope: Variables declared outside any function or block are globally accessible.
  • Local Scope: Variables declared within a function or block are only accessible within that scope.
  • Hoisting: JavaScript moves declarations (not initializations) to the top of their scope during compilation. var declarations are hoisted and initialized with undefined, whereas let and const are hoisted but not initialized, causing a temporal dead zone.
  • Closures: Functions retain access to the scope in which they were created, allowing them to remember variables from their outer scope even after that scope has finished execution.
Understanding these concepts helps prevent common bugs related to variable access and lifecycle.

Applications

  • Encapsulation: Using local scope to hide internal data and avoid polluting global namespace.
  • Callbacks and Async Programming: Closures allow callback functions to access outer variables.
  • Module Pattern: Leveraging closures to create private variables and methods.
  • Hoisting Awareness: Prevent bugs by understanding when and how variables are accessible.

Multiple Choice Questions

Q1: Which statement about var hoisting is true?

  • A. Variables declared with var are hoisted and initialized to undefined.
  • B. Variables declared with var are not hoisted.
  • C. Variables declared with var throw an error if accessed before declaration.
  • D. var behaves the same as let regarding hoisting.

Answer: A. Variables declared with var are hoisted and initialized to undefined.

Q2: What is a closure in JavaScript?

  • A. A function bundled with references to its surrounding state.
  • B. A special type of global variable.
  • C. A method to declare private variables globally.
  • D. A loop that runs indefinitely.

Answer: A. A function bundled with references to its surrounding state.

Q3: Variables declared with let and const are:

  • A. Hoisted and initialized to undefined.
  • B. Not hoisted at all.
  • C. Hoisted but not initialized, causing temporal dead zone.
  • D. Accessible globally no matter where declared.

Answer: C. Hoisted but not initialized, causing temporal dead zone.

Q4: What will be logged to the console?

function outer() {
  var x = 10;
  return function inner() {
    console.log(x);
  }
}
const fn = outer();
fn();
  • A. undefined
  • B. 10
  • C. Error
  • D. null

Answer: B. 10