๐ Quick Study Guide: JS Variables
- ๐ก
var Keyword:- ๐ Scope: Function-scoped or global-scoped.
- ๐ Re-declaration/Re-assignment: Can be re-declared and re-assigned within its scope.
- โฌ๏ธ Hoisting: Hoisted to the top of its scope and initialized with `undefined`.
- ๐ซ Modern Use: Generally discouraged in modern JS due to potential for bugs.
- ๐
let Keyword:- ๐งฑ Scope: Block-scoped (e.g., inside `{}`).
- โ Re-declaration: Cannot be re-declared in the same scope.
- โ
Re-assignment: Can be re-assigned.
- โฐ Hoisting/TDZ: Hoisted, but not initialized. Accessing before declaration results in a `ReferenceError` (Temporal Dead Zone - TDZ).
- ๐
const Keyword:- ๐๏ธ Scope: Block-scoped.
- ๐ซ Re-declaration/Re-assignment: Cannot be re-declared or re-assigned after initial declaration.
- โ ๏ธ Initialization: MUST be initialized at the time of declaration.
- โณ Hoisting/TDZ: Also subject to the Temporal Dead Zone (TDZ).
- โจ Immutability (Objects): For objects, `const` prevents re-assignment of the variable itself, but the properties of the object can still be modified.
- โ๏ธ Key Differences Summary:
- ๐ฏ Scoping: `var` (function/global), `let`/`const` (block).
- ๐ Flexibility: `var` (most flexible), `let` (re-assignable, not re-declarable), `const` (neither).
- ๐ก๏ธ Best Practice: Prefer `const` by default, use `let` when re-assignment is necessary, avoid `var`.
๐ง Practice Quiz: JavaScript Variables
Click to see Answers
1. C (var allows both re-declaration and re-assignment)
2. C (let is block-scoped)
3. C (const declares a constant variable)
4. B (var is hoisted and initialized with undefined)
5. C (let is hoisted but not initialized, leading to TDZ)
6. B (Re-assigning a const variable causes a TypeError)
7. B (let and const are preferred for their block-scoping and clearer behavior)