So, you're working with data in JavaScript. It's all about Maps and Sets. They're essential. You use them to store data, but in different ways - Maps are like a phonebook, where you have names and numbers, key-value pairs, if you will. Sets, on the other hand, are like a list of unique guests at a party, no duplicates allowed. Here's the thing: Maps let you look up values using keys, like finding a phone number by name. Sets, by contrast, check if a value is already in the set, like checking if a guest is already on the list. And, Maps can use any type as a key - it's like using a picture or a song as a key to unlock a value. Sets, though, are all about uniqueness, no duplicates. Now, when to use each? Use a Map when you need to look up values by key, like finding a specific book in a library. Use a Set when you need to check for unique values, like ensuring all your website users have a unique username. And, if you need JSON serialization and your keys are strings, an object might be the way to go. Maps and Sets aren't just nice to have - they're crucial for modeling relationships and unique values in your code. This makes your code faster, more accurate, and way easier to maintain, which is a beautiful thing. Innovation, strategy, and creativity all come into play when working with Maps and Sets. So, next time you're working with data in JavaScript, remember: Maps and Sets are your friends. Check out this guide for more info: https://lnkd.in/gNQG4Tgj #JavaScript #MapsAndSets #DataStorage
JavaScript Maps and Sets for Data Storage and Lookup
More Relevant Posts
-
𝗧𝗵𝗲 𝗦𝗲𝗰𝗿𝗲𝘁 𝗧𝗼 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 You write JavaScript code and it doesn't work as expected. You think it's a bug, but it's not. It's how JavaScript works. Let's look at an example: ```javascript const user = { name: "Alice", role: "user" }; const admin = user; admin.role = "admin"; console.log(user.role); // "admin" ``` You might expect "user", but you get "admin". This happens because `admin` and `user` point to the same object. Here's what's happening: - The Stack is like a temporary order board. It holds function calls, variables, and pointers. - The Heap is like a storage room. It holds objects, arrays, and functions. When you write `const user = { name: "Alice" }`, JavaScript does this: ``` STACK HEAP ┌─────────────┐ ┌──────────────────┐ │ user: ──────┼────────>│ { │ └─────────────┘ │ name: "Alice" │ │ } │ └──────────────────┘ ``` The variable `user` lives on the stack and holds a pointer to the object on the heap. When you copy a variable, you copy the pointer, not the object. So, `admin` points to the same object as `user`. To fix this, you can create a new object: ```javascript const user = { name: "Alice", role: "user" }; const admin = { ...user }; admin.role = "admin"; console.log(user.role); // "user" ``` Now, `admin` points to a new object, and changing it doesn't affect `user`. This understanding is crucial when working with React state or any code that depends on detecting changes in objects. Source: https://lnkd.in/gfUaubUy
To view or add a comment, sign in
-
⚔️ Normal JavaScript vs. War‑Style JavaScript What works locally often breaks in production. Here’s how to tell the difference—and why it matters. 🧪 Normal JavaScript You write it in a sandbox. The data is clean, the network is fast, and the user follows the happy path. ✅ No null or undefined to worry about ✅ Async/await with no .catch() ✅ const user = data.user.profile.email; – works every time This is lab‑grade code. Great for prototypes. Dangerous in production. 🛡️ War‑Style JavaScript This code has seen things. It’s been through code reviews, pentesting, and a 3am outage. 🔹 Defensive reading const email = data?.user?.profile?.email ?? 'fallback@example.com'; 🔹 Error handling that actually handles try { await riskyCall(); } catch (err) { logger.error(err); // Recover, don’t just crash } 🔹 Input validation – never trust the client 🔹 Performance under load – debouncing, throttling, memoization 🔹 Security – escape user input, validate JWTs, use Helmet.js 🔹 Observability – logs, metrics, structured errors War‑style code assumes the worst: 📉 Network fails 🧨 Third‑party API changes shape 🐞 Users type “eval()” into a text box 📈 The Real Difference Normal JS War‑Style JS Works on my machine Works for 10k concurrent Throws undefined Shows a friendly error One developer knows it Handover‑ready, documented “It’s fine for now” “How will this scale?” 🔥 Why This Matters War‑style isn’t over‑engineering—it’s respect. Respect for your users, your future self, and the people who will maintain your code. Start by auditing your last PR. Did you handle the unhappy paths? Did you log failures? Did you assume nothing? Normal JavaScript gets the job done. War‑style JavaScript keeps the job done. 💬 What’s one “war‑style” habit you always practice? I’ll go first: optional chaining and nullish coalescing are non‑negotiable. 👇
To view or add a comment, sign in
-
💡JavaScript/React Tip💡 Using an array reduce method helps to write better code. Let’s say you want to separate users based on their status or type. You might write code like this: const activeUsers = users.filter((user) => user.status === "active"); const inActiveUsers = users.filter((user) => user.status === "inactive"); Looks clean, right? But here's what's happening behind the scenes: 🔁 You're looping over the same array two times . Now imagine if your users list grows to 10,000+ users… That could affect performance. Also, If later you want to filter users by another status like disabled, then you need to add another line of code using the filter function. ✅ Better approach: Use .reduce() to do all the grouping in one iteration. const { activeUsers, inActiveUsers } = users.reduce( (acc, user) => { if (user.status === "active") acc.activeUsers.push(user); if (user.status === "inactive") acc.inactiveUsers.push(user); return acc; }, { activeUsers: [], inactiveUsers: [] } ); 🧠 What’s happening here? → We loop through the array only once. → We check each user and push them into the appropriate bucket. → At the end, we destructure the object returned by the reduce method and get all two arrays. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲.
To view or add a comment, sign in
-
-
🎓 Just published two new articles on Medium diving deeper into JavaScript! I explored some of the most important yet often misunderstood parts of the language: 🔑 The Mysterious Key “this” – Understanding how this behaves in different contexts, from object methods to classes, with practical examples to avoid common pitfalls. Read here https://lnkd.in/dwHdN6K9 🧱 Object-Oriented JavaScript – A hands-on look at objects, classes, constructors, static methods, inheritance, and how to work with getters, setters, and public/private fields. Read here https://lnkd.in/dSr_uSnP I will be happy if these posts help anyone strengthen their JavaScript and understand these concepts better! #JavaScript #OOP #WebDevelopment #Frontend #LearningJourney #ProgrammingTips #MediumArticles
To view or add a comment, sign in
-
🔹Asynchronous JavaScript — Callbacks, Promises & Async/Await JavaScript doesn’t wait. It executes code asynchronously, which makes web apps fast and responsive. Understanding async JS is mandatory for APIs, React, and backend communication. 1️⃣ What is Asynchronous JavaScript? Async code allows tasks like: ✔ API calls ✔ Database requests ✔ Timers to run without blocking the main thread. 2️⃣ Callbacks (The Old Way) A function passed into another function to run later. setTimeout(() => { console.log("Data loaded"); }, 1000); ❌ Hard to manage ❌ Leads to callback hell 3️⃣ Promises (Cleaner Approach) fetch(url) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); ✔ Better readability ✔ Handles success & failure 4️⃣ Async / Await (Best Practice) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } ✔ Looks synchronous ✔ Easy to debug ✔ Widely used in production 5️⃣ Why This Matters ✔ Fetch backend data ✔ Handle user actions smoothly ✔ Required for React & Spring Boot APIs Async JavaScript = professional frontend code. #AsyncJavaScript #Promises #AsyncAwait #FrontendDevelopment #JavaFullStack #WebDevJourney #CodingLife #PlacementReady
To view or add a comment, sign in
-
-
Most Developers Misuse map() in JavaScript — Here’s Why It Matters I often review Angular / React code where I see this users.map(user => { console.log(user.name); }); This is a code smell. Why? Because map() is NOT meant for side effects. ✅ What map() is ACTUALLY for map() is used to transform data and return a new array. const userNames = users.map(user => user.name); ✔ Clear intent ✔ Immutable ✔ Chainable ✔ Functional style ❌ Common Mistake Developers Make Using map() instead of forEach() when: No new array is needed Only logging / mutation / API calls are happening Returned value is ignored This leads to: Confusing code Wasted memory Wrong mental model ✅ When forEach() is the RIGHT choice Use forEach() for side effects only: users.forEach(user => { console.log(user.name); }); ✔ Intent is clear ✔ No unnecessary array creation Real Production Bug I’ve Seen Using forEach() with async code users.forEach(async user => { await saveUser(user); }); console.log("Done"); // Executes too early ✅ Correct approach: await Promise.all( users.map(user => saveUser(user)) ); Simple Rule to Remember map = transform data forEach = side effects If you’re not using the returned array → don’t use map().
To view or add a comment, sign in
-
Garbage Collection (GC) in JavaScript is often simplified to the notion that "JavaScript automatically frees memory." While this is true, it is an incomplete explanation. The essence of GC is that it removes memory that your program can no longer access. The core concept is straightforward: - If an object is reachable, it remains in memory. - If it is unreachable, it can be collected. Garbage Collection is based on reachability rather than whether you still "use" something conceptually. Here's a simplified overview of how the GC process works: - JavaScript maintains a set of roots, which include global variables, active function scopes, closures, and the call stack. - The GC starts from these roots and marks everything they reference. - Anything that cannot be reached from these roots is deemed garbage, and that memory is reclaimed. This method is known as mark-and-sweep, forming the foundation of modern JavaScript engines. A common misunderstanding arises with examples like: ```javascript let user = { name: "Kishor" }; user = null; ``` In this case, the object becomes unreachable and is eligible for GC. However, consider: ```javascript let cache = []; cache.push({ data: 123 }); ``` Even if you "stop using" that object, it remains reachable through the cache, preventing GC from removing it. This is a primary cause of memory leaks in JavaScript. Closures also play a significant role in memory management. They can extend the lifetime of memory; if a closure references a large object, that object stays in memory as long as the closure exists. This can be powerful but potentially dangerous if not properly understood. While GC is automatic, it is not without cost. It runs when the engine determines it can pause execution briefly, and large object graphs can make GC more resource-intensive. This is why long-running applications still require memory awareness. The key takeaway is that Garbage Collection does not prevent memory leaks; it only cleans up memory
To view or add a comment, sign in
-
JSX is NOT HTML. It’s JavaScript in Disguise. 🎭⚛️ When you start learning React, JSX feels like magic. You are writing HTML... inside a JavaScript function? But under the hood, it’s not HTML at all. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐢𝐧𝐠? Browsers don't understand JSX. Before your code hits the browser, tools like 𝐁𝐚𝐛𝐞𝐥 transform that "HTML" into standard JavaScript objects. 𝐓𝐡𝐞 𝐓𝐫𝐚𝐧𝐬𝐟𝐨𝐫𝐦𝐚𝐭𝐢𝐨𝐧 𝐅𝐥𝐨𝐰: 1️⃣ You write: `<div className="box">Hello</div>` 2️⃣ Babel compiles it to: `React.createElement('div', { className: 'box' }, 'Hello')` 3️⃣ React turns that into a lightweight JS object (Virtual DOM). 4️⃣ Finally, React updates the real DOM. 𝐖𝐡𝐲 𝐢𝐬 𝐉𝐒𝐗 𝐬𝐭𝐫𝐢𝐜𝐭𝐞𝐫 𝐭𝐡𝐚𝐧 𝐇𝐓𝐌𝐋? Ever got an error for leaving a tag unclosed or using `class` instead of `className`? Since JSX becomes JavaScript function calls: • `class` is a reserved word in JS ➔ so we use `className`. • Function arguments must be well-defined ➔ so every tag must close. 𝐓𝐡𝐞 𝐏𝐨𝐰𝐞𝐫 𝐌𝐨𝐯𝐞: Because it is JavaScript, you can embed logic directly: `{ isLoggedIn ? <Dashboard /> : <Login /> }` Check out the visual breakdown below to see the full journey from JSX to DOM! 👇 Do you prefer writing JSX, or have you ever tried writing raw `React.createElement` code (just for fun)? 😅 #ReactJS #WebDevelopment #Frontend #JavaScript #JSX #CodingBasics #Babel
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗦𝗲𝗰𝗿𝗲𝘁 𝗧𝗼 𝗝𝗮𝗏𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 You write JavaScript code and it doesn't work as expected. You think it's a bug, but it's not. It's how JavaScript works. Let's look at an example: ```javascript const user = { name: "Alice", role: "user" }; const admin = user; admin.role = "admin"; console.log(user.role); // "admin" ``` You might think this logs "user", but it logs "admin". This is because `admin` and `user` point to the same object. Here's what's happening: - The variable `user` lives on the stack and holds a pointer to the object. - The object lives on the heap. - When you copy a variable, you're copying the pointer, not the object itself. To fix this, you need to create a new object: ```javascript const user = { name: "Alice", role: "user" }; const admin = { ...user }; admin.role = "admin"; console.log(user.role); //user``` Now `admin` points to a new object, and changing it doesn't affect `user`. This is a fundamental concept in JavaScript: the difference between the stack and the heap. The stack is fast and temporary, while the heap is slower and permanent. When you understand this, you'll be able to write better code and avoid common mistakes. You'll know how to create new objects and avoid mutating existing ones. Some key takeaways: - Use the spread operator to create new objects: `const newObj = { ...oldObj };` - Be careful with nested objects: `const copy = { ...original };` only creates a shallow copy. - Use `JSON.stringify()` or a library like Lodash to compare object contents. Source: https://lnkd.in/gfUaubUy
To view or add a comment, sign in
-
JavaScript Output-Based Questions Question1: function getAge(...arg){ console.log(typeof arg) } getAge(21) Output : Object Why? Rest parameters (...arg) always collect arguments into an array — and in JavaScript, arrays are objects. Question2: function checkAge(data){ if(data === {age : 18}){ console.log("you are adult"); }else if(data == {data : 18}){ console.log("You are still an adult"); }else{ console.log("Hmm.. I don't have age guess"); } } checkAge(18) Output :Hmm.. I don't have age guess. Why? Objects in JavaScript are compared by reference, not by value, so comparing a number with an object literal always fails. You DON’T compare objects directly. You compare their properties or their values. Question3: let number = 0; console.log(number++) console.log(++number) console.log(number) Output: 0 2 2 Why ? Post-increment returns the value before incrementing, while pre-increment increments first and then returns the value. Question 4 : let a = 3; let b = new Number(3); let c = 3; console.log(a == b) console.log(a === b) console.log(b === c) console.log(a == b) console.log(c == b) Output: true false false true true Why? Type-coercion new Number() creates a Number object, while numbers without new are primitives. Question 5: for(var i = 0; i<3;i++){ setTimeout(()=>console.log(i),1) } for(let i = 0; i<3;i++){ setTimeout(()=>console.log(i),1) } Output: 3 3 3 0 1 2 Why? var: Only one variable exists in the function. Each loop iteration shares the same variable. let: Each loop iteration creates a new variable binding in its own block scope.
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