🚀 Day 2 – Level 2 of my 4 Days JavaScript Challenge! 💡 Today's question: Why is the output of this code unexpected? 🤔 const obj = {}; const a = { id: 1 }; const b = { id: 2 }; obj[a] = "A"; obj[b] = "B"; console.log(obj[a]); // ❓ 🧠 Expected Output: "A" 😅 Actual Output: "B" 👉 Reason: When you use objects as keys in a plain JavaScript object {}, they are automatically converted to strings — specifically "[object Object]". So in the above code: obj[a] ➜ obj["[object Object]"] = "A" obj[b] ➜ obj["[object Object]"] = "B" Both keys collide because they share the same string representation, and the last one ("B") overwrites the first one. ✅ Correct Approach – Use Map instead! const map = new Map(); const a = { id: 1 }; const b = { id: 2 }; map.set(a, "A"); map.set(b, "B"); console.log(map.get(a)); // "A" console.log(map.get(b)); // "B" 🧩 Key Takeaway: Use Map when you need object references as keys — it preserves their identity and avoids overwriting issues. 🔥 Coming up tomorrow – Day 3: One of the most confusing yet important JavaScript interview concepts you must master! #JavaScript #FrontendDevelopment #WebDevelopment #CodingChallenge #CleanCode #InterviewPreparation #TechJourney #Objects #Map #JSInterview
JavaScript Challenge: Unexpected Output with Objects as Keys
More Relevant Posts
-
Understanding this in JavaScript this — one of the most misunderstood keywords in JavaScript. It’s simple in theory… until it suddenly isn’t 😅 Here’s what makes it tricky — this depends entirely on how a function is called, not where it’s written. Its value changes with context. Let’s look at a few examples 👇 const user = { name: "Sakura", greet() { console.log(`Hello, I am ${this.name}`); }, }; user.greet(); // "Sakura" ✅ const callGreet = user.greet; callGreet(); // undefined ❌ (context lost) const boundGreet = user.greet.bind(user); boundGreet(); // "Sakura" ✅ (context fixed) Key takeaways 🧠 ✅ this refers to the object that calls the function. ✅ Lose the calling object → lose the context. ✅ Use .bind(), .call(), or .apply() to control it. ✅ Arrow functions don’t have their own this — they inherit from the parent scope. These small details often trip up developers in interviews and real-world debugging sessions. Once you understand the context flow, this becomes a lot less scary to work with. 💪 🎥 I simplified this in my Day 28/50 JS short video— check it out here 👇 👉 https://lnkd.in/gyUnzuZA #javascript #webdevelopment #frontend #backend #programming #learnjavascript #softwaredevelopment #developerslife #techsharingan #50daysofjavascript
To view or add a comment, sign in
-
🍏 JS Daily Bite #7 🧬 JavaScript Inheritance: Understanding the Prototype Chain JavaScript's approach to inheritance is unique — and understanding it is key to mastering the language. 🚀 What is the Prototype Chain? JavaScript objects are dynamic collections of properties ("own properties"). But here's where it gets interesting: every object also has a link to a prototype object. When you try to access a property, JavaScript doesn't just look at the object itself — it searches up the prototype chain until it either finds the property or reaches the end of the chain. 🧩 🔑 Key Concepts to Know: [[Prototype]] is the internal link to an object's prototype, accessible via Object.getPrototypeOf() and Object.setPrototypeOf(). Don’t confuse obj.__proto__ with func.prototype — the latter specifies what prototype will be assigned to instances created by a constructor function. In object literals, you can use { __proto__: c } to set the prototype directly. 🧠 The “Methods” Twist: JavaScript doesn’t have methods in the traditional class-based sense. Functions are just properties that can be inherited like any other. And here's a critical detail: when an inherited function executes, this points to the inheriting object — not the prototype where the function is defined. ⚡ 💡 Why This Matters: Understanding prototypes is essential for working with JavaScript's object model, debugging inheritance issues, and leveraging modern class syntax (which is really just syntactic sugar over prototypes). 👉 Next up: Constructors — how JavaScript creates and links objects during instantiation! #JavaScript #JSDailyBite #WebDevelopment #Programming #FrontendDevelopment #SoftwareEngineering #LearnToCode #TechEducation #CodeNewbie #Developers #100DaysOfCode
To view or add a comment, sign in
-
JavaScript’s hidden magic tricks Did you know JavaScript secretly helps your primitives behave like objects? Ever wondered how this works? 👇 "hello".toUpperCase(); // "HELLO" (42).toFixed(2); // "42.00" true.toString(); // "true" Wait a second… A string, a number, and a boolean — all have methods? But these are primitive values, not objects! So how can they call methods like .toUpperCase() or .toFixed()? 💡 The Secret: Temporary Wrapper Objects When you try to access a property or method on a primitive, JavaScript automatically creates a temporary object — a process called autoboxing. Here’s what happens behind the scenes const str = "hello"; // Step 1: JavaScript wraps it const temp = new String(str); // Step 2: Calls the method on that temporary object const result = temp.toUpperCase(); // Step 3: Discards the wrapper temp = null; console.log(result); // "HELLO" So, "hello" behaves like an object for a moment — but it’s still a primitive! ✅ typeof "hello" → "string" ❌ "hello" instanceof String → false Why this matters It keeps primitives lightweight and fast. You can safely call methods on them. But don’t confuse them with their object counterparts created using new: const s = new String("hello"); // actual object typeof s; // "object" s instanceof String → true #JavaScript #Tricks
To view or add a comment, sign in
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
JavaScript interview Questions #day3rd Loops & Conditions Q1: What are the different types of loops in JavaScript? for loop: Traditional loop with initialization, condition, and increment while loop: Executes while condition is true, checks condition before execution do-while loop: Executes at least once, checks condition after execution for...in: Iterates over enumerable properties of objects for...of: Iterates over iterable values (arrays, strings, etc.) Q2: How does for...in differ from for...of? for...in: Iterates over enumerable property keys (including prototype chain), best for objects for...of: Iterates over iterable values (arrays, strings, maps, sets), doesn't work with plain objects Q3: What is the difference between switch and if-else statements? if-else: Better for range comparisons, complex conditions, boolean checks switch: Better for exact value matching, more readable for multiple discrete values, uses strict comparison Q4: Explain break and continue statements break: Completely terminates the loop or switch statement continue: Skips the current iteration and continues with the next iteration of the loop Q5: What is short-circuit evaluation in JavaScript? Using logical operators (&&, ||) for conditional execution: a && b: Returns a if falsy, otherwise returns b a || b: Returns a if truthy, otherwise returns b Commonly used for default values and conditional execution #javascript #js #interview #questions #topquestions #javascriptinterview #100dayschallange #day3rd #3rdday #learningjavascript #learnjs #learnjavascript #howtoprefaireforjavascriptinterview #daythree
To view or add a comment, sign in
-
-
JS Learners & Web Devs! Ever wondered why you can call a function before it’s defined in JavaScript, but let or const throw a ReferenceError? Our latest blog dives deep into Hoisting in JavaScript: How JS engine really works Understanding the Temporal Dead Zone (TDZ) Function vs variable hoisting Common pitfalls & best practices Stop guessing and start writing safer, cleaner JS code! https://lnkd.in/dCeqNnRf #javascript #webdevelopment #hoistinginjs #learnjavascript #coding #programming #FrontendDevelopment #webdev #CodeNewbie #wenowadays
To view or add a comment, sign in
-
💡 JavaScript: The Little Things That Fool Even Experienced Devs (Day 6/50) Ever debugged something in JavaScript that made zero sense — but later realized it was 100% logical once you understood what was happening? 😅 Let’s uncover 3 of those sneaky concepts 👇 --- ⚙️ 1️⃣ Promises vs setTimeout — Who runs first? Even if both have a 0ms delay, Promises (microtasks) run before setTimeout (macrotasks). That’s how the JavaScript Event Loop works — it always clears the microtask queue first. So, when debugging async code, remember: ✅ Promises first, then timers later. --- 🧩 2️⃣ Objects as Keys — The Silent Overwrite When you use objects as keys inside another object, JavaScript doesn’t treat them as unique objects. It converts them to the string "[object Object]". So your carefully separated keys might actually overwrite each other 😬 If you really need objects as keys → use a Map, not a plain object. --- 🎯 3️⃣ The “this” Trap in Arrow Functions Arrow functions don’t have their own this. They inherit it from the surrounding scope. That’s why this inside an arrow function often points to the wrong place (like window or undefined) — while a regular function gets its own this when called. 👉 Moral: Use normal functions when you want this to refer to your object. --- ✨ Takeaway: It’s these small but powerful details that make JavaScript fun — and frustrating 😄 Mastering them means you’re not just writing code… you’re understanding it. --- 🎥 We covered these with real code examples in Day 6 of our “50 Days of JavaScript Tricky Interview Questions” series! Watch here 👉 https://lnkd.in/g5_bPcur #javascript #webdevelopment #frontenddeveloper #backenddeveloper #asyncjavascript #eventloop #thiskeyword #objectkeys #codinginterview #learnjavascript #fullstackdeveloper #techsharingan
To view or add a comment, sign in
-
💥 Redux Made Easy: The Simple JavaScript Concept Behind compose() If you've used Redux but want to understand the core logic behind its power? It starts with one JavaScript concept: "Composition". It was a total 💡 lightbulb moment for me. It revealed how Redux builds it's entire middleware pipeline using elegant, core JavaScript. "Composition" chains simple functions into a powerful one. Think of an assembly line: output of one becomes input for the next. 🧠 Think of it like water flowing through filters where each function cleans or transforms the data before passing it on. The compose utility in Redux is not a built-in JS function but it's a pattern typically created using reduceRight(). Why "reduceRight" ? Because it assembles functions backwards, ensuring that data flows forwards which is exactly the way a pipeline should. Short Example: List: [LogTiming function, AuthorizeUser function, RunQuery function] Problem: The RunQuery must run first, then AuthorizeUser, then LogTiming. Solution: reduceRight() builds the function chain backwards, ensuring data flows forwards through the required order: RunQuery → AuthorizeUser → LogTiming. "Real-World Example": Cleaning Data This pattern lets us process data reliably. Here's how we build compose in vanilla JS: "📸 [refer to the attached image for better understanding]" 👉 This same composition pattern is exactly what Redux uses internally for its middleware pipeline. 🔁 How Redux Uses Compose The compose pattern is essential for Redux middleware (applyMiddleware). When you list middleware (like thunk for async operations and logger for debugging), Redux uses its internal "compose" utility to wrap them into a single, cohesive processing unit. Every action flows consistently through this pipeline before hitting your reducers. Understanding reduceRight() really helps you see how Redux turns multiple features into one reliable machine. It’s just ✨ JavaScript. 💬 If you've got JavaScript concept that helped you understand a complex library better? 👇 Drop your “lightbulb moment” in the comments or DM! #Redux #JavaScript #FunctionalProgramming #WebDevelopment #React #CodingTips #ReduceRight
To view or add a comment, sign in
-
-
Today's Topic: Promise Chaining in JavaScript In JavaScript, Promise chaining allows you to execute asynchronous tasks one after another, ensuring that each step waits for the previous one to finish. Instead of nesting callbacks (callback hell ), promises make your code cleaner and easier to maintain. Example: function step1() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 1 completed ✅"); resolve(10); }, 1000); }); } function step2(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 2 completed ✅"); resolve(value * 2); }, 1000); }); } function step3(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 3 completed ✅"); resolve(value + 5); }, 1000); }); } // Promise Chaining step1() .then(result => step2(result)) .then(result => step3(result)) .then(finalResult => console.log("Final Result:", finalResult)) .catch(error => console.error("Error:", error)); ✅ Output (after 3 seconds): Step 1 completed ✅ Step 2 completed ✅ Step 3 completed ✅ Final Result: 25 Each .then() runs after the previous promise resolves — making async flow easy to read and manage. --- 🔖 #JavaScript #WebDevelopment #PromiseChain #AsyncProgramming #CodingTips #FrontendDevelopment #Developers #JSConcepts #CodeLearning #100DaysOfCode #WebDevCommunity
To view or add a comment, sign in
-
More from this author
Explore related topics
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
Nice example. It’s a simple way to show why map can be so useful compared to plain objects