Most JavaScript devs think Object keys follow insertion order. And it’s caught even senior devs off guard. Create an object and add keys in this order: "b", "a", "1". const obj = {}; obj.b = 'second'; obj.a = 'third'; obj.1 = 'first'; Log Object.keys(obj). You’d expect: ['b', 'a', '1'] You get: ['1', 'b', 'a'] 🤯 The number jumped to the front, but the strings stayed in order. Same object. Same assignment logic. Completely unexpected order. This silently breaks: → API wrappers that expect keys to match a specific schema → UI components that map over objects for "alphabetical" sorting → Testing suites that compare object snapshots No error thrown. Just a data structure that "rearranges" itself. Why does this happen? It’s defined in the ECMAScript spec (OrdinaryOwnPropertyKeys). JavaScript objects don't have a single "order." They follow a strict three-tier hierarchy: 1. Integer Indices: Sorted in ascending numeric order (always first). 2. String Keys: Sorted in chronological insertion order. 3. Symbol Keys: Sorted in chronological insertion order (always last). The engine treats "1" as an integer index, so it "cuts the line" and moves to the very front, regardless of when you added it. Once you know this, you'll stop trusting Object.keys() for ordered data and start reaching for Map. 🔖 Learn more about how JS engines handle property order → https://lnkd.in/gRY6hdcM Were you aware that numbers always "cut the line" in JS objects? 1️⃣ Yes / 2️⃣ No 👇 #JavaScript #WebDev #Coding #SoftwareEngineering #Frontend
JavaScript Object Keys Don't Follow Insertion Order
More Relevant Posts
-
JavaScript prototypes clicked for me the moment I stopped thinking about copying and started thinking about linking. Here's the mental model that made it stick 👇 🔹 The core idea Every object in JavaScript has a hidden link to another object — its prototype. When you access a property, JS doesn't just look at the object itself. It walks the chain: Check the object Not found? Check its prototype Still not found? Check the prototype's prototype Keep going until null That's the prototype chain. Simple as that. 🔹 See it in action jsconst user = { name: "Aman" }; const admin = { isAdmin: true }; admin.__proto__ = user; console.log(admin.name); // "Aman" ✅ admin doesn't have name — but JS finds it one level up. 🔹 Why constructor functions use this jsfunction User(name) { this.name = name; } User.prototype.sayHi = function () { console.log(`Hi, I am ${this.name}`); }; Every User instance shares one sayHi method. Not copied — linked. That's free memory efficiency, built into the language. 🔹 Two things worth keeping straight prototype → a property on constructor functions __proto__ → the actual link on any object The modern, cleaner way to set that link: jsconst obj = Object.create(user); 🔹 Why bother understanding this? Because it shows up everywhere — class syntax, frameworks, unexpected undefined bugs, performance decisions. Prototypes aren't a quirk. They are the inheritance model. One line to remember: JS doesn't copy properties. It searches a chain of linked objects. #JavaScript #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
⚡15 JavaScript Senior level questions about objects: 1) How do property descriptors work, and how do get/set interact with writable/configurable/enumerable? 2) Walk through the [[Get]] and [[Set]] algorithm (prototype chain, shadowing, strict mode) 3) What’s the difference between in, hasOwnProperty, and Object.hasOwn? When is Object.hasOwn preferable? 4) Explain Object.create(null) and when you’d use it over {}. 5) this binding in object methods, method extraction, and arrow pitfalls 6) Enumerability, reflection, and key order: for…in vs Object.keys vs Object.getOwnPropertyNames vs Reflect.ownKeys 7) Deep copy strategies: structuredClone, JSON, spread, and Object.assign 8) Freezing, sealing, and extensibility: semantics and pitfalls 9) Proxies, invariants, and why Reflect is your friend 10) Symbols and well-known symbols: make plain objects iterable & controllable 11) Class fields and private fields: what are they actually? 12) super, [[HomeObject]], and why copying methods can break super 13) JSON serialization edge cases: toJSON, replacers, and lost values 14) Property definition vs assignment: descriptors, accessors, and side effects 15) Objects vs Map/WeakMap: key types, iteration, GC, and performance #JavaScript #TechInterview
To view or add a comment, sign in
-
JavaScript Proxy — A Hidden Superpower You Should Know Most of us create objects like this: const frameworkName = { name: "Next JS" }; But what if you could intercept and control every operation on this object? That’s exactly what JavaScript Proxy does. Think of it like a gatekeeper sitting in front of your object — it can monitor, modify, or block any interaction. const frameworkName = { name: "Angular" }; const proxyFramework = new Proxy(frameworkName, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updating ${prop} to ${value}`); if (value === "React") { console.log("React is not allowed!"); throw new Error("React is not allowed!"); // Throw an error to prevent the update return false; // Prevent the update } target[prop] = value; return true; } }); proxyFramework.name; // 👉 Reading name proxyFramework.name = "Next"; Why should you care? ✔ Track changes (great for debugging) ✔ Add validation before updating values ✔ Build reactive behavior (like frameworks do) ✔ Control or restrict access to data Real-world use cases: • Form validation without extra libraries • Logging state changes for debugging • Building custom state management • Data sanitization before saving Pro Tip: Frameworks like Vue use Proxy internally to make data reactive. Understanding this can level up your frontend skills. Have you used Proxy in your projects, or are you still sticking with plain objects? #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
🧠 Day 25 — JavaScript Destructuring (Advanced Use Cases) Destructuring isn’t just syntax sugar — it can make your code cleaner and more powerful 🚀 --- 🔍 What is Destructuring? 👉 Extract values from arrays/objects into variables --- ⚡ 1. Object Destructuring const user = { name: "John", age: 25 }; const { name, age } = user; --- ⚡ 2. Rename Variables const { name: userName } = user; console.log(userName); // John --- ⚡ 3. Default Values const { city = "Delhi" } = user; --- ⚡ 4. Nested Destructuring const user = { profile: { name: "John" } }; const { profile: { name } } = user; --- ⚡ 5. Array Destructuring const arr = [1, 2, 3]; const [a, b] = arr; --- ⚡ 6. Skip Values const [first, , third] = arr; --- 🚀 Why it matters ✔ Cleaner and shorter code ✔ Easier data extraction ✔ Widely used in React (props, hooks) --- 💡 One-line takeaway: 👉 “Destructuring lets you pull out exactly what you need, cleanly.” --- Master this, and your code readability improves instantly. #JavaScript #Destructuring #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
✨ 𝗪𝗿𝗶𝘁𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗛𝘂𝗺𝗮𝗻 ⤵️ Template Literals in JavaScript: Write Strings Like a Human ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/d_HhAEsM 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Why string concatenation becomes messy in real apps ⇢ Template literals — the modern way to write strings ⇢ Embedding variables & expressions using ${} ⇢ Multi-line strings without \n headaches ⇢ Before vs After — readability transformation ⇢ Real-world use cases: HTML, logs, queries, error messages ⇢ Tagged templates (advanced but powerful concept) ⇢ How interpolation works under the hood ⇢ Tradeoffs & common mistakes developers make ⇢ Writing cleaner, more readable JavaScript Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Frontend #Programming #CleanCode #Hashnode
To view or add a comment, sign in
-
{JS Problem Solving} Today, I solved some JavaScript problems to improve my problem-solving skills. Problems I solved=> 1. Deep Flatten Array No matter how deep the nested array is, make it completely flat flatten([1, [2, [3, [4]], 5]]) // output: [1,2,3,4,5] 2️. Debounce function Create a function that will execute with a delay if called rapidly debounce(fn, 500) Real use: search input optimization 3️. Throttle Function Run the function only once in a specified time throttle(fn, 1000) Real use: scroll event 4️. Custom Promise.all() Implement it yourself myPromiseAll([p1, p2, p3]) Output: Return the result if all are resolved 5️. LRU Cache Implement Least Recently Used cache const cache = new LRUCache(2) cache.put(1, 1) cache.get(1) Real use: browser caching 6️. Group By Function Group an array groupBy(users, "age") 7️. Deep Clone Object clone nested object (no reference) deepClone(obj) JSON.parse cannot be used 8️. Infinite Curry Function Will support unlimited chaining sum(1)(2)(3)(4)() // 10 9️. Event Emitter (Node.js style) Create a custom event system emitter.on("click", fn) emitter.emit("click") 10. Retry API Call with Limit API will retry if it fails retry(fetchData, 3) Repo link: https://lnkd.in/gXtcS9qP #problemsolver #programmer #javascriptdeveloper
To view or add a comment, sign in
-
-
🧠 Day 28 — WeakMap & WeakSet in JavaScript (Simplified) You’ve seen Map & Set — now let’s look at their smarter versions 👀 --- 🔍 What makes them “Weak”? 👉 They hold weak references to objects 👉 If the object is removed, it can be garbage collected automatically --- ⚡ 1. WeakMap 👉 Key-value pairs (like Map) 👉 Keys must be objects only let obj = { name: "John" }; const weakMap = new WeakMap(); weakMap.set(obj, "data"); console.log(weakMap.get(obj)); // data --- ⚠️ Important ❌ Keys must be objects ❌ Not iterable (no loop) ❌ No size property --- ⚡ 2. WeakSet 👉 Collection of unique objects let obj1 = { id: 1 }; const weakSet = new WeakSet(); weakSet.add(obj1); console.log(weakSet.has(obj1)); // true --- 🧠 Why use them? 👉 Helps with memory management 👉 Avoids memory leaks 👉 Used internally in frameworks --- 🚀 Real-world use ✔ Caching objects temporarily ✔ Tracking object references ✔ Managing private data --- 💡 One-line takeaway: 👉 “WeakMap & WeakSet allow objects to be garbage collected automatically.” --- If you want to go deeper into JavaScript internals, this is a great concept. #JavaScript #WeakMap #WeakSet #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
Most developers think they understand Closures… until an interview question destroys their confidence. Here’s the truth 👇 Closures are not just a “concept” — they’re the reason JavaScript feels powerful. --- 🔒 So what is a Closure? A closure is when a function remembers variables from its outer scope even after that outer function is finished. --- 🧠 Simple Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 👉 Even though `outer()` is done, `inner()` still remembers `count`. That’s a Closure. --- 🔥 Why should you care? Closures are everywhere: ✔ React Hooks (useState, useEffect) ✔ Event handlers ✔ API calls ✔ Functional programming --- 💡 Real Power: Closures help you: • Create private variables • Build reusable functions • Manage state without global variables --- ⚠️ Common mistake: for (var i = 1; i <= 3; i++) { setTimeout(() => console.log(i), 1000); } Output: `4 4 4` 😵 👉 Fix? Use `let` or closure --- 🎯 Interview Golden Line: A closure is a function that remembers its lexical scope even after the outer function has executed. --- 🚀 If you master closures: You stop memorizing JavaScript… and start understanding it. --- 💬 What confused you most about closures? Let’s discuss 👇 --- #JavaScript #Closures #WebDevelopment #Frontend #ReactJS #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
Many developers confuse slice() and splice() in JavaScript. The difference is simple but important. 1️⃣ slice() — Creates a copy slice() returns a portion of an array without changing the original array. Example: const numbers = [10, 20, 30, 40, 50] const result = numbers.slice(1, 4) Result → [20, 30, 40] Original → [10, 20, 30, 40, 50] Use it when you want to extract data safely without modifying the source array. 2️⃣ splice() - Modifies the array splice() changes the original array. It can remove, add, or replace elements. Example 1 - Remove items: const numbers = [10, 20, 30, 40, 50] numbers.splice(2, 2) Result → [10, 20, 50] It removed 30 and 40 from the original array. Example 2 - Add Items : constnumbers= [10, 20, 50]; numbers.splice(2, 0, 30, 40); console.log(numbers); // [10, 20, 30, 40, 50] Explanation: It Start at index 2, Remove 0 items and Insert 30 and 40 Key Difference slice() → non-destructive (does not modify the array) splice() → destructive (modifies the array) Quick rule to remember slice → copy splice → change Understanding this small difference prevents many bugs, especially when working with React state and immutable data patterns. #javascript #webdevelopment #frontend #reactjs #programming
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 30 JavaScript feels fast… But have you ever wondered 👇 👉 How does it handle multiple tasks at once? 👉 How does async code run without blocking? This is where the **Event Loop** comes in 😎 --- ## 🤯 The Big Confusion JavaScript is **single-threaded** 👉 It can do **one thing at a time** Then how does this work? 👇 ```javascript id="el1" console.log("Start") setTimeout(() => { console.log("Async Task") }, 0) console.log("End") ``` 👉 Output: Start End Async Task Wait… why? 🤔 --- ## 🔥 Behind the Scenes JavaScript has 3 main parts: 👉 Call Stack 👉 Web APIs 👉 Callback Queue --- ## 🔹 Step by Step Flow 1️⃣ `console.log("Start")` → runs first 2️⃣ `setTimeout` → goes to **Web API** 3️⃣ `console.log("End")` → runs next 4️⃣ Callback goes to **Queue** 5️⃣ Event Loop checks → stack empty? 6️⃣ Yes → push callback to stack 👉 Then runs → "Async Task" --- ## 🔍 Visualization ```id="viz1" Call Stack → Executes code Web APIs → Handles async tasks Queue → Stores callbacks Event Loop → Manages everything ``` --- ## 🔥 Real Life Example Think of a **restaurant 🍽️** 👉 Waiter takes order → sends to kitchen 👉 Kitchen prepares food 👉 Meanwhile waiter serves others 👉 When food is ready → serves you 👉 Event Loop = waiter managing tasks --- ## 🔥 Simple Summary JS → single-threaded Async → handled outside Event Loop → manages execution --- ### 💡 Programming Rule **JavaScript is not multi-threaded… but it behaves like it is.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
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
No