Understand global vs local scope, hoisting, and closures in JavaScript.
Example demonstrating scope, hoisting, and closures:
// 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:
var
.let
and const
.Scope: Defines the visibility and lifetime of variables and functions in JavaScript.
var
declarations are hoisted and initialized with undefined
, whereas let
and const
are hoisted but not initialized, causing a temporal dead zone.Q1: Which statement about var
hoisting is true?
var
are hoisted and initialized to undefined
.var
are not hoisted.var
throw an error if accessed before declaration.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?
Answer: A. A function bundled with references to its surrounding state.
Q3: Variables declared with let
and const
are:
undefined
.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();
Answer: B. 10