Javascript Study Chapter ยท Official ReferenceAfzaal Suleman Knowledge Base
JavaScript offers three ways to declare variables: var, let, and const. Understanding their differences in scope, hoisting, and mutability is crucial for writing clean, bug-free code.
Scope Differences
- var: Function-scoped, can be redeclared
- let: Block-scoped, cannot be redeclared
- const: Block-scoped, cannot be redeclared or reassigned
๐ป
Code Demonstration & Syntax
javascript
// var - function scoped
function testVar() {
if (true) {
var x = 10;
}
console.log(x); // 10 - accessible outside block
}
// let - block scoped
function testLet() {
if (true) {
let y = 20;
}
console.log(y); // ReferenceError - not accessible
}
// const - block scoped, immutable
const PI = 3.14159;
PI = 3.14; // TypeError - cannot reassignOutput
10 ReferenceError: y is not defined TypeError: Assignment to constant variable
๐
Chapter Rules & Key Notes
๐ก
Remember This
- Always prefer const by default, use let when you need reassignment
- Avoid var in modern JavaScript code
- const objects can have their properties modified (only the reference is immutable)
๐
Important Rules
- Use const for variables that should not be reassigned
- Use let for variables that need to be reassigned
- Never use var in ES6+ code
โ ๏ธ
Common Mistakes
- Thinking const makes objects completely immutable
- Using var instead of let in loops
- Forgetting that let/const are block-scoped
โฆโฆโฆ