JavaScript - var Keyword
Overview
Estimated time: 10–15 minutes
var
is function-scoped and hoisted. Prefer let
/const
to avoid surprises.
Learning Objectives
- Understand function scope vs block scope.
- Recognize hoisting and redeclaration hazards.
Prerequisites
Function scope
function demo(){
if (true) {
var x = 1;
}
console.log(x); // 1 (function scoped)
}
Hoisting and redeclaration
console.log(a); // undefined (hoisted declaration)
var a = 10;
var a = 20; // redeclaration allowed
Recommendation
- Use
const
by default;let
when reassignment is needed; avoidvar
.