In JavaScript, var
and const
(along with let
) are used to declare variables, but they have important differences regarding scope, hoisting, and mutability.
// var example function exampleVar() { if (true) { var x = 10; } console.log(x); // 10, since var is function-scoped } // let example function exampleLet() { if (true) { let y = 20; console.log(y); // 20 } // console.log(y); // ReferenceError, since let is block-scoped } // const example function exampleConst() { const z = 30; // z = 40; // TypeError, since const cannot be reassigned const obj = { key: 'value' }; obj.key = 'newValue'; // This is allowed console.log(obj.key); // 'newValue' } exampleVar(); exampleLet(); exampleConst();
var
- Scope:
- Function-scoped: Variables declared with
var
are scoped to the function in which they are declared. - They are not block-scoped: If
var
is declared in a block (e.g., inside anif
statement), it is still accessible outside the block.
- Hoisting:
- Variables declared with
var
are hoisted to the top of their scope. However, the initialization is not hoisted, only the declaration.
- Re-declaration:
var
allows re-declaration within the same scope.
let
- Scope:
- Block-scoped: Variables declared with
let
are only accessible within the block they are declared in.
- Hoisting:
- Variables declared with
let
are hoisted but are not initialized. They remain in a “temporal dead zone” until the declaration is encountered.
- Re-declaration:
let
does not allow re-declaration within the same scope.
const
- Scope:
- Block-scoped: Variables declared with
const
are only accessible within the block they are declared in.
- Hoisting:
- Variables declared with
const
are hoisted but are not initialized. They remain in a “temporal dead zone” until the declaration is encountered.
- Re-declaration:
const
does not allow re-declaration within the same scope.
- Mutability:
const
creates a read-only reference to a value. However, if the variable is an object or array, the properties or elements can still be modified.
Examples
In summary:
- Use
var
for function-scoped variables (although its use is generally discouraged in modern JavaScript). - Use
let
for block-scoped variables that you might need to reassign. - Use
const
for block-scoped variables that should not be reassigned.