{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
10 JavaScript Problems to Improve Your Problem-Solving Skills
More Relevant Posts
-
🚀 JavaScript Trick — structuredClone() Native Deep Cloning (No more JSON hacks!) Most developers still do this to deep clone an object: const clone =JSON.parse(JSON.stringify(obj)); But this approach breaks on: ❌ Date objects → converts to string ❌ undefined values → gets removed ❌ Functions → silently dropped ❌ Infinity, NaN → becomes null ❌ Circular references → throws an error ✅ Meet structuredClone() — built into modern JS: const original = { name: "Bob", born: new Date("1995-12-05"), scores: [10, 20, 30], meta: undefined }; const clone = structuredClone(original); clone.scores.push(60); clone.name=“Alice”; console.log(original.name); // "Bob" ✅ not affected console.log(original.scores); // [10, 20, 30] ✅ not affected console.log(clone.born); // Date object ✅ not a string! console.log(clone.meta); // undefined ✅ preserved! structuredClone() handles what JSON.parse() can't: ✅ Dates stay as Date objects ✅ undefined values are preserved ✅ Circular references work fine ✅ Faster performance overall 📦 No lodash. No JSON tricks. Just one clean native method. Available in Node 17+, Chrome 98+, Firefox 94+ #JavaScript #WebDevelopment #JSTips #Frontend #Programming
To view or add a comment, sign in
-
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
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
-
🚀 Memory Management & Garbage Collection in JavaScript — Explained Simply Ever wondered how JavaScript handles memory without manual control? 🤔 👉 Unlike languages like C/C++, JS manages memory automatically 🧩 What is Memory Management? 👉 Process of: • Allocating memory • Using memory • Releasing memory ✔ All handled automatically by JavaScript engine ⚙️ How It Works 1️⃣ Allocation → Memory is created when you declare variables 2️⃣ Usage → You read/write data 3️⃣ Release → Memory is freed when no longer needed 🧠 What is Garbage Collection (GC)? 👉 Process of removing unused memory ✔ Runs automatically in background ✔ Prevents memory leaks 🔍 How GC Decides What to Remove 👉 Uses Mark & Sweep Algorithm • Mark → Find reachable objects • Sweep → Remove unreachable ones ⚡ Key Concept ✔ Objects referenced → kept in memory ❌ Objects not referenced → removed ⚠️ Common Memory Leaks (Real-world) ❌ Global variables ❌ Unremoved event listeners ❌ setInterval / setTimeout not cleared ❌ Closures holding large data ❌ Detached DOM elements 🧠 React-Specific Example useEffect(() => { const interval = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(interval); // cleanup }, []); 👉 Without cleanup → memory leak ❌ ⚡ Best Practices ✔ Clean up effects (`useEffect`) ✔ Avoid unnecessary global variables ✔ Remove event listeners ✔ Use WeakMap / WeakSet when needed ✔ Keep references minimal 🔥 Real Impact ✔ Better performance ✔ Avoid crashes ✔ Stable applications 🧠 Simple Way to Understand • Referenced → stays in memory ✅ • Not referenced → garbage collected ❌ 💬 Have you ever debugged a memory leak in your app? #JavaScript #React #WebDevelopment #Frontend #Performance #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
Most JavaScript bugs aren’t caused by complex logic. They come from choosing the wrong array method. The difference between find() and filter(), map() and forEach(), or some() and every() looks small—until it reaches production. That’s where performance, readability, and hidden bugs start to matter. Examples: filter()[0] instead of find() → unnecessary full array scan Using forEach() when map() should return transformed data → broken data pipelines Calling sort() directly in React state → silent mutation bugs Using filter().length > 0 instead of some() → extra work for no reason Overusing reduce() for simple logic → clever code, poor readability Great developers don’t just know array methods. They know: ✔ When to use them ✔ When not to use them ✔ Their performance cost ✔ Their side effects ✔ Their production impact Simple rule: Code should not only work. It should be readable, predictable, and efficient. Because in real applications, small method choices create big system behavior. The engineers I respect most don’t use reduce() to look smart. They use find() instead of filter()[0]. They spread before sort(). They know forEach() returns nothing. That’s the difference between writing JavaScript and engineering with JavaScript. #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #SoftwareEngineering #Programming #CodeQuality #TechLeadership
To view or add a comment, sign in
-
-
🚀 Day 20 – Deep vs Shallow Copy in JavaScript Ever changed a copied object… and accidentally modified the original too? 😅 Yeah, that’s the shallow copy trap. Let’s fix that today 👇 🔹 Shallow Copy Copies only the first level 👉 Nested objects still share the same reference 🔹 Deep Copy Creates a fully independent clone 👉 No shared references, no unexpected bugs 💡 Real-world example (Angular devs 👇) When working with forms, APIs, or state (NgRx), a shallow copy can silently mutate your original data — leading to hard-to-debug UI issues. ⚡ Best Ways to Deep Copy ✔️ structuredClone() (modern & recommended) ✔️ JSON.parse(JSON.stringify(obj)) (with limitations) ✔️ _.cloneDeep() (lodash) 🔥 TL;DR Shallow Copy → Shares references Deep Copy → Fully independent Prefer structuredClone() whenever possible 💬 Have you ever faced a bug because of shallow copying? Drop your experience 👇 #JavaScript #Angular #WebDevelopment #Frontend #Programming #100DaysOfCode
To view or add a comment, sign in
-
-
Shallow Copy vs Deep Copy in JavaScript Many developers struggle with this concept early in their careers and honestly, it’s one of those things that can silently break your application if not understood properly. What’s really happening behind the scenes? In JavaScript, objects are stored in memory, and variables don’t hold the actual object they hold a reference (address) to that object. 🔹 Shallow Copy Creates a new outer object But nested objects are NOT copied Instead, their reference is shared That’s why modifying nested data affects both Think of it like: Two people pointing to the same house if one changes it, both see the change. 🔹 Deep Copy Creates a completely new object Nested objects are also duplicated No shared references Changes remain isolated Think of it like: Building an entirely new house changes don’t affect the original. ⚠️ Why does this matter in real projects? React state bugs Unexpected UI updates Data mutation issues in APIs Debugging nightmares Final Takeaway: Shallow Copy = Shared References (Risky) Deep Copy = Independent Data (Safe) Have you ever faced a bug because of shallow copy? Let’s discuss #JavaScript #ReactJS #WebDevelopment #Frontend #Programming #SoftwareEngineering #CodingLife #Developers #LearnToCode #Tech
To view or add a comment, sign in
-
-
😵💫𝗢𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴 𝘁𝗵𝗶𝗻𝗴𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: `...` At first glance, it looks simple. But depending on where you use it, it completely changes its role. Same syntax. Different behavior. That’s where most developers get tripped up. So I decided to break it down clearly: ✍️ New Blog Published: 𝗦𝗽𝗿𝗲𝗮𝗱 𝘃𝘀 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗘𝘅𝗽𝗮𝗻𝗱 𝗼𝗿 𝗖𝗼𝗹𝗹𝗲𝗰𝘁 𝗟𝗶𝗸𝗲 𝗮 𝗣𝗿𝗼 https://lnkd.in/gFPgrdEv 🔍 What you’ll learn: 🔹 When ... acts as a Spread Operator (expanding data) 🔹 When it becomes a Rest Operator (collecting data) 🔹 Real-world use cases to eliminate confusion Hitesh Choudhary Piyush Garg Chai Aur Code Anirudh J. Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
🔍 Understanding JSON.parse() — What Works & What Breaks Instantly One of the most common pitfalls in JavaScript is assuming that anything looks like JSON can be parsed. But JSON.parse() is strict — and that’s where many bugs begin. ✅ Valid JSON (Parses Successfully): Objects: {"a":1} Arrays: [1,2,3] Strings: "hello" (must be in double quotes!) Numbers, booleans, and null ❌ Invalid JSON (Fails Immediately): Unquoted strings → hello Unquoted keys → {a:1} Single quotes → {'a':1} Empty string → "" Random text → INVALID 💡 Key Insight: JSON is not JavaScript. It’s a strict data format with clear rules: Keys must be in double quotes Strings must be in double quotes No trailing commas, no shortcuts 🚨 Why this matters: When working with APIs, local storage, or backend data, a small formatting mistake can break your entire app. 👉 Think of JSON.parse() as a strict gatekeeper — if your data doesn’t follow the exact rules, it won’t even let you in. #JavaScript #WebDevelopment #Frontend #Programming #CodingTips #JSON #Developers #reactjs #nodejs
To view or add a comment, sign in
-
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Understanding Prototypal Inheritance and the Prototype Chain Dive into the fascinating world of prototypal inheritance in JavaScript. Let's unravel the prototype chain together! hashtag#javascript hashtag#prototypalinheritance hashtag#programming hashtag#webdevelopment ────────────────────────────── Core Concept Have you ever wondered how JavaScript objects inherit properties? Prototypal inheritance allows one object to access properties and methods of another object — but how does that play out in practice? Key Rules - All JavaScript objects have a prototype. - The prototype chain is a series of links between objects. - Properties or methods not found on an object can be looked up on its prototype. 💡 Try This const animal = { eats: true }; const rabbit = Object.create(animal); rabbit.hops = true; console.log(rabbit.eats); // true ❓ Quick Quiz Q: What does the Object.create method do? A: It creates a new object with the specified prototype object. 🔑 Key Takeaway Mastering prototypal inheritance can unlock powerful patterns in your JavaScript projects! ────────────────────────────── 🔗 Read the full detailed guide with code examples, comparison tables & step-by-step instructions: https://lnkd.in/gKG6Ez9k
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
#letsconnecteveryone