QA
Beginner LevelJavaScript & TypeScript

What is scope in JavaScript (global, function, block, and lexical scope)?

❓ Interview Prompt: Explain scope hierarchies in JavaScript and how scope chains resolve variable lookups.

Scope determines the accessibility and visibility of variables and functions in different parts of your code.

Types of Scope:

1
Global Scope: Default scope for variables declared outside any function or block. Accessible everywhere.
2
Function (Local) Scope: Variables declared with var, let, or const inside a function are accessible only within that function.
3
Block Scope: Variables declared with let and const inside curly braces {} (if statements, loops) cannot be accessed outside the block.
4
Lexical Scope: Inner functions have access to variables declared in their outer parent scope based on where code is written.

Code Implementation Example

javascript
const globalVar = 'Global';

function outerFunction() {
  const outerVar = 'Outer';

  if (true) {
    var functionScoped = 'Var in block'; // Leaks to outerFunction scope
    const blockScoped = 'Let in block';   // Block-scoped to IF block
  }

  console.log(functionScoped); // "Var in block"
  // console.log(blockScoped);  // ReferenceError!

  function innerFunction() {
    // Lexical Scope Chain: inner -> outer -> global
    console.log(`${globalVar} -> ${outerVar} -> ${functionScoped}`);
  }
  innerFunction();
}
💡Lexical scope chain resolution and block scope containment.
🎯 Interview Key Takeaway

Lexical scoping means variable access is determined by where functions are written in source code.

#Scope#Lexical Scope#Variables#Beginner
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?