JavaScript
JavaScript Refresher: Declarations, Initializations, Closures, Hoisting

JavaScript Variable Fundamentals
Understanding how variables work in JavaScript is crucial. Let's explore declarations, initializations, closures, and hoisting.
Variable Declarations
JavaScript has three ways to declare variables:
var x = 10; // Function-scoped, hoisted
let y = 20; // Block-scoped, not hoisted
const z = 30; // Block-scoped, not hoisted, cannot be reassigned
Hoisting
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation:
console.log(a); // undefined (declaration hoisted, not assignment)
var a = 5;
console.log(b); // ReferenceError (let is not hoisted)
let b = 5;
Closures
A closure is a function that has access to variables from its outer (enclosing) scope, even after the outer function has returned:
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3
Scope
var is function-scoped, meaning it's accessible throughout the function where it's declared. let and const are block-scoped, limited to the block (if statement, loop, etc.) where they're declared.
Best Practices
- Use
constby default - Use
letwhen you need to reassign - Avoid
varin modern JavaScript
JavaScriptVariablesClosuresHoisting