Chapter 3JavaScript Tutorial~2 min read
var vs let vs const
Scope आणि Hoisting समजून घ्या
var, let, आणि const — तिन्ही variables declare करतात पण त्यांचे scoping rules वेगळे आहेत. Modern JavaScript मध्ये let आणि const वापरणे best practice आहे.
var — Function Scoped (जुना method)
var — Function Scope
javascript
// var function-scoped आहे — block बाहेर पण accessible
if (true) {
var message = "Hello!";
}
console.log(message); // ✅ "Hello!" — var block बाहेर पण चालतो
// var redeclare करता येतो — bug चे source
var name = "Rahul";
var name = "Priya"; // ✅ Error नाही — पण हे धोकादायक!let — Block Scoped (Modern)
let — Block Scope
javascript
// let block-scoped आहे — { } बाहेर accessible नाही
if (true) {
let score = 100;
console.log(score); // ✅ 100
}
// console.log(score); // ❌ ReferenceError: score is not defined
// let reassign होतो पण redeclare नाही
let city = "Pune";
city = "Mumbai"; // ✅ reassign OK
// let city = "Nagpur"; // ❌ SyntaxErrorconst — Block Scoped, Immutable
const — Constant Values
javascript
// const value बदलता येत नाही
const PI = 3.14159;
// PI = 3.14; // ❌ TypeError: Assignment to constant variable
// const declare करताना value assign करणे mandatory
// const x; // ❌ SyntaxError — initialization missing
// पण Object/Array contents बदलता येतात!
const person = { name: "Rahul", age: 25 };
person.age = 26; // ✅ OK — object मधील value बदलली
// person = {}; // ❌ Error — reference बदलता येत नाही
const colors = ["red", "blue"];
colors.push("green"); // ✅ OKComparison Table
- ▸var: Function scope | Redeclare: ✅ | Reassign: ✅ | वापर: Legacy code, avoid करा
- ▸let: Block scope | Redeclare: ❌ | Reassign: ✅ | वापर: Value बदलणाऱ्या variables साठी
- ▸const: Block scope | Redeclare: ❌ | Reassign: ❌ | वापर: Fixed values, objects, arrays
Marathi Analogy
🏠 Analogy: var म्हणजे घराचे key जे कुठेही duplicate करता येते. let म्हणजे room specific key — फक्त त्या room मध्येच चालते. const म्हणजे lock झालेले safe — आतले बदलता येते पण safe बदलता येत नाही.
📌
Modern JavaScript मध्ये: Default म्हणून const वापरा. Value बदलायची असेल तेव्हाच let वापरा. var वापरणे avoid करा.
✅ Key Points — लक्षात ठेवा
- ▸var = function scope, redeclare होतो — avoid
- ▸let = block scope, reassign होतो, redeclare नाही
- ▸const = block scope, reassign नाही, redeclare नाही
- ▸const मध्ये object/array contents बदलता येतात
- ▸Best practice: const by default, let जेव्हा हवे, var never
0/13 chapters पूर्ण