Loading

Quipoin Menu

Learn • Practice • Grow

java-script / Scope And Hoisting
interview

Q1. What is Scope in JavaScript?
Scope in JavaScript refers to the accessibility or visibility of variables, functions, and objects in different parts of the program. It determines where variables can be accessed and used.

JavaScript mainly has three types of scope:
  • Global Scope
  • Function Scope
  • Block Scope
Example
let globalVar = "I am global";

function test() {
    let functionVar = "I am inside function";
    console.log(globalVar);
}

test();
console.log(globalVar);

  • globalVar can be accessed everywhere.
  • functionVar can only be accessed inside the function.


Q2. What is Global Scope?
A variable declared outside any function or block is called a global variable. It can be accessed from anywhere in the program.

Example
let name = "John";

function greet() {
    console.log(name);
}

greet();

The variable name is accessible inside the function.


Q3. What is Block Scope?
Block scope means variables declared inside a block {} can only be accessed within that block. Variables declared using let and const follow block scope.

Example
if (true) {
    let age = 25;
    console.log(age);
}

console.log(age);

This will produce an error because age is block scoped.


Q4. What is Hoisting in JavaScript?
Hoisting is JavaScript's behavior where variable and function declarations are moved to the top of their scope during the compilation phase before code execution.
This means you can use variables and functions before they are declared, but behavior depends on how they are declared.

Example
console.log(a);
var a = 10;

Output
undefined

JavaScript moves declaration to the top but not the value assignment.

Internally JavaScript treats it like:
var a;
console.log(a);
a = 10;


Q5. How does Hoisting behave differently with var, let, and const?
Hoisting with var
console.log(x);
var x = 5;

Output
undefined

Var is hoisted and initialized with undefined.


Hoisting with let and const
console.log(y);
let y = 10;

Output
ReferenceError

let and const are hoisted but NOT initialized. They stay in a "Temporal Dead Zone" until declared.