🚀 **JavaScript: var vs let vs const (Every Developer Should Know This)** Understanding the difference between `var`, `let`, and `const` is one of the most important fundamentals in JavaScript. Let’s simplify it 👇 --- 🔴 **var** • Function scoped • Can be **reassigned** • Can be **redeclared** • Hoisted and initialized as `undefined` ```javascript var x = 10; x = 20; // ✅ allowed var x = 30; // ✅ allowed ``` ⚠️ Old JavaScript way. Avoid using `var` in modern code. --- 🟢 **let** • Block scoped `{ }` • Can be **reassigned** • ❌ Cannot be redeclared in the same scope • Hoisted but in **Temporal Dead Zone (TDZ)** ```javascript let y = 10; y = 20; // ✅ allowed let y = 30; // ❌ Error ``` ✔ Best for variables that will change. --- 🟣 **const** • Block scoped • ❌ Cannot be reassigned • ❌ Cannot be redeclared • Hoisted with **Temporal Dead Zone** ```javascript const z = 10; z = 20; // ❌ Error ``` ✔ Best for constants. --- 🎯 **Best Practice** ✔ Use **const by default** ✔ Use **let when value changes** ❌ Avoid **var** This makes your code **cleaner, safer, and predictable.** --- 💬 Interview Question: What is **Temporal Dead Zone (TDZ)** in JavaScript? Comment your answer 👇 --- #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #SoftwareEngineering #LearnToCode #DeveloperTips #JS #TechCommunity
JavaScript var vs let vs const: Best Practices for Developers
More Relevant Posts
-
But I can still change const even though it is immutable, Const a = [] a.push(7) Above code is completely valid. Can anyone explain that .. comment below 👇
Immediate Joiner - Software Developer | Full Stack Web Developer | NODE JS | REACT JS | PHP | JS | GITHUB | PYTHON | DJANGO | REST API | MYSQL | MONGO DB | FLASK | WORDPRESS
🚀 **JavaScript: var vs let vs const (Every Developer Should Know This)** Understanding the difference between `var`, `let`, and `const` is one of the most important fundamentals in JavaScript. Let’s simplify it 👇 --- 🔴 **var** • Function scoped • Can be **reassigned** • Can be **redeclared** • Hoisted and initialized as `undefined` ```javascript var x = 10; x = 20; // ✅ allowed var x = 30; // ✅ allowed ``` ⚠️ Old JavaScript way. Avoid using `var` in modern code. --- 🟢 **let** • Block scoped `{ }` • Can be **reassigned** • ❌ Cannot be redeclared in the same scope • Hoisted but in **Temporal Dead Zone (TDZ)** ```javascript let y = 10; y = 20; // ✅ allowed let y = 30; // ❌ Error ``` ✔ Best for variables that will change. --- 🟣 **const** • Block scoped • ❌ Cannot be reassigned • ❌ Cannot be redeclared • Hoisted with **Temporal Dead Zone** ```javascript const z = 10; z = 20; // ❌ Error ``` ✔ Best for constants. --- 🎯 **Best Practice** ✔ Use **const by default** ✔ Use **let when value changes** ❌ Avoid **var** This makes your code **cleaner, safer, and predictable.** --- 💬 Interview Question: What is **Temporal Dead Zone (TDZ)** in JavaScript? Comment your answer 👇 --- #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #SoftwareEngineering #LearnToCode #DeveloperTips #JS #TechCommunity
To view or add a comment, sign in
-
-
Method: Array.from() In JavaScript, Array.from() is one of the most underrated yet powerful methods that can make code cleaner, smarter, and more efficient. What is Array.from()? In simple words, Array.from() is a built-in JavaScript method that creates a new array from: ✅ Arrays ✅Array-like objects (like arguments or NodeList) ✅ Iterable objects like Maps and Sets Basic Syntax: Array.from(arrayLike, mapFunction) Example 1: const str = 'Hello' const array = Array.from(str) console.log(array); output: ['H', 'e', 'l', 'l', 'o '] Example 2: const numbers = [1, 2, 3, 4] const result = Array.from(numbers, number => number * 2) console.log(result); output: [2, 4, 6, 8] Example 2: const nums = Array.from({ length:10 },(value, i )=> i + 1) console.log(nums); output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #120DaysOfCode #JavaScript #WebDevelopment #Networking #API #JSON #AsyncAwait #FullStackDeveloper #MERNStackDeveloper #ReactDeveloper #BackendEngineer
To view or add a comment, sign in
-
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
To view or add a comment, sign in
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
🚀 JavaScript Scope Explained (Global, Function & Block Scope) One of the most important concepts every JavaScript developer must understand is **Scope**. Scope defines **where a variable can be accessed in your code**. Let’s break it down 👇 1️⃣ Global Scope Variables declared outside any function are accessible everywhere. ```javascript let name = "Abhishek"; function greet() { console.log(name); } ``` 2️⃣ Function Scope (var) Variables declared with `var` inside a function are only accessible within that function. ```javascript function test() { var message = "Hello"; } console.log(message); // Error ``` 3️⃣ Block Scope (let / const) `let` and `const` are block scoped, meaning they only exist inside `{ }`. ```javascript if(true){ let age = 25; } console.log(age); // Error ``` ⚠️ Common Mistake with `var` ```javascript if(true){ var age = 25; } console.log(age); // 25 (unexpected) ``` ✔ Best Practice Use **const by default** Use **let when value changes** Avoid **var** in modern JavaScript. 💬 Interview Question: What is the **Temporal Dead Zone (TDZ)** in JavaScript? #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 **Understanding JavaScript Variables Like a Pro (var vs let vs const)** If you're working with JavaScript, choosing the right keyword — `var`, `let`, or `const` — is more important than you think. Here’s a simple breakdown 👇 🔸 **var** * Function scoped * Can be re-declared * Can be re-assigned * Hoisted with `undefined` 👉 Mostly avoided in modern JavaScript due to unexpected behavior. --- 🔹 **let** * Block scoped * Cannot be re-declared in same scope * Can be re-assigned * Hoisted but in Temporal Dead Zone (TDZ) 👉 Best for variables that will change. --- 🔒 **const** * Block scoped * Cannot be re-declared * Cannot be re-assigned * Must be initialized at declaration 👉 Best for constants and safer code. --- 💡 **Pro Tip:** Always prefer `const` by default → use `let` when needed → avoid `var`. --- 📊 The attached diagram explains: * Scope hierarchy (Global → Function → Block) * Memory behavior * Key differences visually --- 🔥 Mastering these fundamentals helps you: ✔ Write cleaner code ✔ Avoid bugs ✔ Crack interviews easily --- #JavaScript #WebDevelopment #Frontend #Coding #Programming #Developers #LearnToCode #Tech #SoftwareEngineering #NodeJs #Json
To view or add a comment, sign in
-
-
Catching bugs at 2:00 PM but they don’t wake me up at 2:00 AM. 🛠️ Moving from #JavaScript to #TypeScript wasn’t just a syntax change; it was a shift in confidence. By defining our data structures upfront, we’ve effectively eliminated the "undefined is not a function" errors that used to haunt our production logs. The Difference: In JS, you pass an object and hope the property exists. In TS, the editor won't even let you save the file until you've handled the possibility of it being missing. Example: // JavaScript: The "Finger-Crossing" Method function getUsername(user) { return user.profile.name; // Runtime Error if profile is missing! } // TypeScript: The "Contract" Method interface User { profile?: { name: string }; } function getUsername(user: User) { return user.profile?.name ?? "Guest"; // Type-safe and explicit } The initial setup takes a few extra minutes, but the hours saved in debugging are immeasurable. Have you made the switch yet? Or are you still team Vanilla? 👇 #WebDevelopment #TypeScript #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
🚨 A small JavaScript behavior wasted 30 minutes of my debugging time today. I was extracting payment_ids from an array and wrote this: let paymentIds = filterArray ?.map(item => item.payment_id) .filter(item => item != null) .join(","); if (paymentIds.length > 0) { // run logic } And the condition paymentIds.length > 0 was always true. At first, I thought this was a bug in my code. But it turns out that JavaScript works this way. filterArray = [{id:1},{id:2},{id:3}] If the objects don’t contain payment_id, this happens: [undefined, undefined, undefined] and paymentIds outputs ",,,," So the string still has a length greater than 0, even though there are no real values. So, the correct approach is let paymentIds=filterArray ?.map(i => i.payment_id) .filter(Boolean) .join(","); Lesson learned When working with arrays in JavaScript: 👉 map() doesn't remove invalid values. 👉 join() will still create separators for undefined items. 👉 Checking string length alone can be misleading. Sometimes the smallest behaviors cause the biggest debugging sessions. #javascript #webdevelopment #frontend #reactjs #softwareengineering #codingtips
To view or add a comment, sign in
Explore related topics
- Coding Best Practices to Reduce Developer Mistakes
- Clear Coding Practices for Mature Software Development
- Ways to Improve Coding Logic for Free
- Simple Ways To Improve Code Quality
- Writing Functions That Are Easy To Read
- How to Write Clean, Error-Free Code
- How to Refactor Code Thoroughly
- How to Improve Code Maintainability and Avoid Spaghetti Code
- Importance of Removing Dead Code in Software Development
- Importance of Clear Coding Conventions in Software Development
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
But I can still change const even though it is immutable, Const a = [] a.push(7) Above code is completely valid. Can anyone explain that .. comment below 👇