🚨 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
JavaScript Gotcha: Objects as Keys Explained
More Relevant Posts
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
🚀 𝐃𝐚𝐲 6 – 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 (𝐒𝐢𝐦𝐩𝐥𝐞 & 𝐂𝐥𝐞𝐚𝐫) JavaScript is single-threaded… 👉 But then how does it handle things like `setTimeout`? 🤔 Let’s understand the real flow 👇 --- 💡 The Setup JavaScript uses: * Call Stack → runs code * Web APIs → handles async tasks * Callback Queue → waits for execution * Event Loop → manages everything --- 💡Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); --- 💡 Output: Start End Timeout --- 💡 Why? (Step-by-step) * `Start` → runs immediately * `setTimeout` → sent to Web APIs * `End` → runs immediately * Timer completes → callback goes to Queue * Event Loop checks → Stack empty * Callback pushed to Stack → executes --- ⚡ Key Insight 👉 Even with `0ms`, it does NOT run immediately 👉 It waits until the Call Stack is empty --- 💡 Simple Mental Model 👉 “Async code runs after sync code finishes” --- 💡 Why this matters? Because it explains: * execution order * async behavior * common bugs --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Promises (Async Made Better)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
I used to work on a JavaScript codebase where… Every file looked like this 👇Wrapped inside a self-invoking function (IIFE). And honestly…It didn’t make sense to me at first. Why are we doing this? Then I started asking basic questions: 👉 Why do we even split code into multiple files? At a high level → separation of concerns + reusability. We write logic in one file → use it in another.That’s basically what a module system does in any language. Then the next question hit me: 👉 What does IIFE have to do with modules? Here’s the catch: JavaScript initially didn’t have a module system. No imports. No exports. So what happens? 👉 Everything runs in the global scope. Which means: My variables = global Your variables = global Third-party library variables = also global Now imagine same variable names… 💥 Collision. So how did developers deal with this? 👉 Using functions. Because functions in JavaScript create their own scope. So the idea became: Wrap everything inside a function→ invoke it immediately→ expose only what’s needed --> return statement const module = (() => { const p1 = () => {} const p2 = [] const exports = { x1: () => {}, x2: [] } return exports })() Now think about it: 👉 p1 and p2 → private👉 x1 and x2 → public Nothing leaks into global scope. That’s when it clicked for me. This is basically a manual module system. Before:→ CommonJS→ ES Modules Funny thing is… Today we just write: export const x1 = () => {} …but back then, people had to build this behavior themselves. It is not about how things work today but why they exist in the first place. BTW this pattern is called 🫴Revealing Module Pattern.👈 #JavaScript #WebDevelopment #CleanCode #DeveloperJourney #Coding #FrontendDevelopment
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
-
-
👽 Understanding Higher-Order Functions in JavaScript One of the most powerful features in JavaScript is Higher-Order Functions (HOFs). 💤 A Higher-Order Function is a function that: Takes another function as an argument, OR Returns a function as its result This concept is the backbone of modern JavaScript patterns like functional programming and clean, reusable code. 🔹 Example 1: Function as Argument function greet(name) { return "Hello " + name; } function processUser(callback) { console.log(callback("Amina")); } processUser(greet); 🔹 Example 2: Function Returning Function function multiplier(factor) { return function(number) { return number * factor; }; } const double = multiplier(2); console.log(double(5)); // 10 👁️🗨️ Why Higher-Order Functions matter: Promote code reusability Enable clean and modular design Power built-in methods like map(), filter(), reduce() Make code more declarative and readable Mastering HOFs is a key step toward becoming confident in JavaScript and understanding real-world frameworks. #JavaScript #WebDevelopment #Coding #FunctionalProgramming #FrontendDevelopment
To view or add a comment, sign in
-
🚀Day 30 — Scope Chain & Scope Types in JavaScript (Simplified) Understanding scope is one of the most important fundamentals in JavaScript 🚀 --- 🔍 What is Scope? 👉 Scope decides where variables can be accessed in your code In simple words: 👉 “Who can access what?” --- ⚡ Types of Scope 1. Global Scope 👉 Variables declared outside functions or blocks let name = "John"; function greet() { console.log(name); // accessible } --- 2. Function Scope 👉 Variables declared inside a function function test() { let age = 25; console.log(age); } console.log(age); // ❌ Error --- 3. Block Scope 👉 Variables declared with let and const inside {} if (true) { let city = "Delhi"; } console.log(city); // ❌ Error --- 🔗 What is Scope Chain? 👉 If JS can’t find a variable in current scope, it looks in the outer scope, then outer again… until global scope. This is called the Scope Chain --- 🚀 Why it matters ✔ Prevents variable conflicts ✔ Helps understand closures ✔ Improves debugging skills --- 💡 One-line takeaway: 👉 “JavaScript looks upward to find variables — that’s the scope chain.” --- Mastering scope makes closures, hoisting, and debugging much easier. #JavaScript #Scope #ScopeChain #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🚀 Understanding Prototypes in JavaScript (Simple Breakdown) 🔹 Every JavaScript object has a hidden property called [[Prototype]] 👉 It links to another object and allows inheritance 💡 Why Prototypes? Instead of creating duplicate methods for every object, JavaScript shares them using prototypes → saves memory ✅ 🔹 Example: toString() isn’t inside your object, but JS finds it through the prototype chain object → prototype → null 🔗 Prototype Chain (Search Order) Check the object Check its prototype Continue up the chain Stop at null 🔹 Constructor + Prototype Functions can use prototype to share methods: function Person(name) { this.name = name; } Person.prototype.sayHello = function() { console.log("Hello " + this.name); }; ✔ Method stored once, reused by all objects 🔹 proto vs prototype prototype → belongs to constructor __proto__ → belongs to object (actual link) p1.__proto__ === Person.prototype // true 🔥 Key Takeaways ✔ JavaScript uses prototype-based inheritance ✔ Objects inherit via prototype chain ✔ Memory efficient (shared methods) ✔ Core concept for interviews & real-world JS #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode #Developers
To view or add a comment, sign in
-
💡 Simplifying JavaScript with map, filter, and reduce When working with JavaScript, many of us rely on traditional loops like for and forEach. But there are cleaner and more modern ways to write more readable code 👇 🔹 map() Used to transform each element in an array into something new ➡️ Result: a new array with the same length 🔹 filter() Used to select specific elements based on a condition ➡️ Result: a new array with only the elements that match 🔹 reduce() Used to turn an array into a single value (sum, object, etc.) ➡️ Result: one final value instead of an array 🔥 The real power? You can combine them: array.filter(...).map(...).reduce(...) ✨ Result: Cleaner, shorter, and more maintainable code 📌 Summary: * map → transform data * filter → select data * reduce → aggregate data Start using them and you’ll notice a big improvement in your code quality 👨💻 #JavaScript #WebDevelopment #CleanCode #Programming #Frontend
To view or add a comment, sign in
-
🔥 var vs let vs const in JavaScript (Explained Simply) Understanding the difference between `var`, `let`, and `const` is essential for writing clean and bug-free JavaScript code. Let’s break it down 👇 🔹 1️⃣ var #Example var name = "Amit"; var name = "Rahul"; // Re-declaration allowed ✅ Function scoped ✅ Can be re-declared and updated ⚠️ Hoisted with `undefined` ❌ Can cause unexpected bugs 👉 Avoid using `var` in modern JavaScript. 🔹 2️⃣ let #Example let age = 25; age = 30; // Update allowed ✅ Block scoped ❌ Cannot be re-declared in same scope ✅ Can be updated ✅ Safer than `var` 👉 Use `let` when the value needs to change. 🔹 3️⃣ const #Example const pi = 3.14; // pi = 3.1415; ❌ Error ✅ Block scoped ❌ Cannot be re-declared ❌ Cannot be updated ✅ Must initialize at declaration 💡 For objects/arrays → You can modify properties, but not reassign the reference. 🚀 Best Practice ✔️ Use `const` by default ✔️ Use `let` when reassignment is required ❌ Avoid `var` Writing cleaner code starts with choosing the right variable declaration. #JavaScript #WebDevelopment #Frontend #Programming #CodingTips #Developers
To view or add a comment, sign in
-
-
🔍 A small JavaScript detail that can cause unexpected bugs: Object key ordering Many developers assume object keys are always returned in insertion order, but JavaScript actually follows a specific ordering rule when you iterate over object properties (Object.keys, Object.entries, for...in). The order is: • Integer index keys → sorted in ascending order • String keys → insertion order • Symbol keys → insertion order (not included in Object.keys) This is one of the reasons why using Object as a map can sometimes lead to unexpected iteration behavior when numeric keys are involved. If key order matters, Map is usually the more predictable choice since it preserves insertion order for all key types. Small language details like this are easy to overlook, but they often explain those subtle bugs you run into during debugging. #JavaScript #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
Explore related topics
- Coding Best Practices to Reduce Developer Mistakes
- Simple Ways To Improve Code Quality
- How Developers Use Composition in Programming
- How to Add Code Cleanup to Development Workflow
- How to Write Maintainable, Shareable Code
- How to Write Clean, Error-Free Code
- How Developers Translate Business Rules Into Code
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