Master var, let, and const — how they differ in scoping, hoisting, and reassignment. Learn how block, function, and global scope work in JavaScript.
Why: var is function-scoped and hoisted; let and const are block-scoped. Use const by default, let when you need to reassign, and avoid var in modern code.
const name = 'Alice'; // cannot be reassigned
let age = 30; // can be reassigned
age = 31;
// var leaks out of blocks — avoid it
if (true) {
var leaked = 'I exist outside the block';
let scoped = 'I stay inside';
}
console.log(leaked); // 'I exist outside the block'
// console.log(scoped); // ReferenceError
console.log(name, age);Why: JavaScript moves var declarations (not their values) to the top of their function. let and const are hoisted but not initialized — accessing them before declaration throws a ReferenceError.
// var is hoisted and initialized to undefined
console.log(x); // undefined, not an error
var x = 5;
console.log(x); // 5
// Function declarations are fully hoisted
console.log(greet()); // works!
function greet() { return 'Hello'; }
// let/const are in the "temporal dead zone" before declaration
try {
console.log(y); // ReferenceError
let y = 10;
} catch (e) {
console.log(e.message);
}Why: names must start with a letter, $, or _. They are case-sensitive and cannot be reserved words. Conventions: camelCase for variables and functions, UPPER_CASE for constants.
// Valid names
let firstName = 'Alice';
let _private = true;
let $element = null;
let MAX_SIZE = 100;
let camelCase = 'yes';
// Names are case-sensitive
let color = 'red';
let Color = 'blue';
console.log(color, Color); // 'red' 'blue'
// These would cause syntax errors (commented out):
// let 1name = 'bad'; // starts with digit
// let let = 'bad'; // reserved word
console.log(firstName, MAX_SIZE);Why: scope determines where a variable is accessible. Block scope means inside {}, function scope means inside a function, and global scope means accessible everywhere.
// Global scope
const globalVar = 'I am global';
function outerFn() {
// Function scope
const fnVar = 'I am in outerFn';
if (true) {
// Block scope
const blockVar = 'I am in the block';
console.log(globalVar); // accessible
console.log(fnVar); // accessible
console.log(blockVar); // accessible
}
// console.log(blockVar); // ReferenceError — outside block
console.log(fnVar);
}
outerFn();
console.log(globalVar); // accessible everywhere
// console.log(fnVar); // ReferenceError — outside function