What are var, let, const? How do they differ? What is hoisting?
sobes.tech AI
Answer from AI
In JavaScript, var, let, and const are keywords for declaring variables, but they differ in scope, reassignability, and hoisting.
-
vardeclares a variable with function or global scope. Variables declared withvarare hoisted, meaning their declaration is moved to the top of the function, but initialization remains in place. They can be redeclared and reassigned. -
letdeclares a variable with block scope (inside{}). It is not hoisted in the traditional sense — accessing the variable before declaration results in an error (temporal dead zone). It can be reassigned but not redeclared in the same scope. -
constalso has block scope, but the variable must be initialized at declaration and cannot be reassigned. However, if it is an object or array, its contents can be modified.
Hoisting is a mechanism where variable and function declarations are moved to the top of their scope during compilation. For var, this means the variable exists from the start of the function but is initialized where declared. For let and const, declarations are also hoisted, but access before declaration is forbidden (temporal dead zone).
Example:
console.log(a); // undefined (var is hoisted)
var a = 5;
console.log(b); // ReferenceError (temporal dead zone)
let b = 10;
const c = 15;
c = 20; // TypeError: Assignment to constant variable.