Why you should NEVER delete items from an array while looping through it. I encountered a classic JavaScript "gotcha" that can catch even experienced developers off guard. Consider this code snippet: const numbers = [2, 4, 6, 8, 10]; numbers.forEach((num, index) => { if (num % 2 === 0) { numbers.splice(index, 1); } }); console.log(numbers); Pop Quiz: What does console.log(numbers) output? A) [] (Empty array - all evens removed) B) [4, 8] C) [2, 4, 6, 8, 10] D) ReferenceError The answer may not be what you'd expect. In fact, if you run this, you'll find that half of your data is still there! I've explained WHY this happens (and the 2-line fix) in the first comment. Check it out to avoid this silent bug in your next pull request. #JavaScript #WebDevelopment #CodingTips #CleanCode #SoftwareEngineering
Avoid Deleting Array Items While Looping in JavaScript
More Relevant Posts
-
🚀 𝐃𝐚𝐲 𝟕/𝟏𝟓 𝐨𝐟 𝐌𝐲 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠 𝐒𝐞𝐫𝐢𝐞𝐬 Today I learned about Arrays in JavaScript 💡 👉 Arrays are used to store multiple values in a single variable. 📌 Example: let numbers = [1, 2, 3, 4, 5]; 👉 Access values using index (starts from 0): console.log(numbers[0]); // 1 📌 Common Array Operations: push() → add element at end pop() → remove last element numbers.push(6); // [1,2,3,4,5,6] numbers.pop(); // [1,2,3,4,5] 👉 Arrays are very useful for handling lists of data 💻✨ 💬 Question: Have you used arrays in any project yet? Let’s learn together 🚀 #JavaScript #WebDevelopment #LearningInPublic #Day7 #FrontendDevelopment
To view or add a comment, sign in
-
-
🚀 Use structuredClone() for deep cloning in JavaScript Instead of this ❌ const clone = JSON.parse(JSON.stringify(obj)); Use this ✅ const clone = structuredClone(obj); Why? ✔️ Supports Date, Map, Set, etc. ✔️ Handles circular references ✔️ Keeps data types intact Example const original = { name: "Programmer", skills: new Set(["React", "TypeScript"]), created: new Date(), }; const clone = structuredClone(original); console.log(clone.skills instanceof Set); // true console.log(clone.created instanceof Date); // true ⚠️ Things to know Functions ❌ are not cloned DOM elements ❌ are not cloned Works in modern browsers & Node.js 17+
To view or add a comment, sign in
-
Code Privacy: Why Your Logic Needs a One-Way Mirror Ever felt like your code is too "exposed"? When every variable and function is out in the open, your logic is vulnerable to accidental changes. The Crux: - The "Building" Analogy: A nested function is like a room on the top floor. It can look out at the global data, but the outside world can never look in. - The Secure Handover: We use an "Outer" function to guard the data and an "Inner" function to do the secret work. - The Goal: Moving from cluttered scripts to Private, Encapsulated Logic. The Evolution: - We don't just nest functions for fun; we do it to build a "One-Way Mirror" where our internal logic stays hidden and our code stays clean. Full guide to building "Private Logic": https://lnkd.in/d2GuikmF #JavaScript #CleanCode #SoftwareArchitecture #ProgrammingTips
To view or add a comment, sign in
-
Everyone reads about ".call()", ".bind()", ".apply()" But the real confusion is: 👉 Where do we actually use them? A simple example from real code: const user = { name: "Jayhind" }; function greet() { console.log("Hello " + this.name); } Now imagine this function is reused somewhere else: const anotherUser = { name: "Rahul" }; greet.call(anotherUser); // Hello Rahul 👉 Here ".call()" helps us control "this" dynamically --- Now ".bind()": const greetRahul = greet.bind(anotherUser); greetRahul(); // Hello Rahul 👉 Useful when you want to store function with fixed context --- Real-world use case: class Service { constructor() { this.name = "API Service"; } log() { console.log(this.name); } } const service = new Service(); setTimeout(service.log, 1000); // undefined ❌ setTimeout(service.log.bind(service), 1000); // API Service ✅ 👉 This is where ".bind()" actually matters --- One simple way to remember: - ".call()" → run function immediately with context - ".apply()" → same as call, but args in array - ".bind()" → return new function with fixed context Most tutorials explain syntax. Real understanding comes from where it breaks. #JavaScript #NodeJS #CallBindApply #BackendDevelopment #JSConcepts
To view or add a comment, sign in
-
-
🚀 map() vs. forEach(): Do you know the difference? The Hook: One of the first things we learn in JavaScript is how to loop through arrays. But using the wrong method can lead to "hidden" bugs that are a nightmare to fix. 🛑 🔍 The Simple Difference: ✅ .map() is for Creating. Use it when you want to take an array and turn it into a new one (like doubling prices or changing names). It doesn't touch the original data. ✅ .forEach() is for Doing. Use it when you want to "do something" for each item, like printing a message in the console or saving data to a database. It doesn't give you anything back. 💡 Why should you care? 1. Clean Code: .map() is shorter and easier to read. 2. React Friendly: Modern frameworks love .map() because it creates new data instead of changing the old data (this is called Immutability). 3. Avoid Bugs: When you use .forEach() to build a new list, you have to create an empty array first and "push" items into it. It’s extra work and easy to mess up! ⚡ THE CHALLENGE (Test your knowledge! 🧠) Look at the image below. Most developers get this wrong because they forget how JavaScript handles "missing" returns. What do you think is the output? A) [4, 6] B) [undefined, 4, 6] C) [1, 4, 6] D) Error Write your answer in the comments! I’ll be replying to see who got it right. 👇 #JavaScript #JS #softwareEngineer #CodingTips #LearnToCode #Javascriptcommunity #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
-
In 2026, the "React Hack" is simply Suspense + the use hook. ### 💻 The Code Shift: function UserProfile({ id }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetchUser(id).then(data => { setUser(data); setLoading(false); }); }, [id]); if (loading) return <Spinner />; return <div>{user.name}</div>; } The 2026 "Clean" Way: // No state, no effect, no manual loading checks. function UserProfile({ userPromise }) { const user = use(userPromise); return <div>{user.name}</div>; } // Wrapped in a Parent <Suspense fallback={<Spinner />}> <UserProfile userPromise={fetchUser(id)} /> </Suspense> Why this is a win: Readable Logic: The component only cares about the UI, not the lifecycle of the fetch. Streaming: The server starts sending HTML to the browser before the data is even finished loading. Less Bugs: No more "race conditions" where the wrong data shows up because an old fetch finished late. The best code is the code you don't have to write. Are you still a useEffect purist, or have you moved your data fetching to the server? Let's talk architecture below. 👇 #ReactJS #CleanCode #WebDevelopment #JavaScript #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
🧩 Demystifying the Node.js Event Loop: It's Not Just One Thread! Ever wondered what actually happens when you call setTimeout(() => {}, 1000)? Most people say "Node is single-threaded," but that’s only half the story. Here is the visual breakdown of how Node.js orchestrates asynchronous magic using libuv: 1. The Handoff (Main Thread) When you set a timer, the Main JS thread (V8) doesn't wait. It registers the callback and duration with libuv and moves on to the next line of code. 2. The Engine Room (libuv) This is where the heavy lifting happens. libuv maintains a Min-Heap—a highly efficient data structure that sorts timers by their expiration time. It puts the thread to "sleep" using OS-level polling (like epoll or kqueue) until the nearest timer is ready. 3. The Queue & The Tick Once the time arrives, libuv moves your callback into the Callback Queue. But it doesn't run yet! The Event Loop must cycle back to the "Timers Phase" to pick it up. ⚠️ The "Golden Rule" of Node.js Don't block the loop. If you run a heavy synchronous operation (like a massive while loop), the Event Loop gets stuck. Even if your timer has expired in the background, the Main Thread is too busy to check the queue. This is why a setTimeout(cb, 100) might actually take 5 seconds to fire if your main thread is congested. Key Takeaway: Node.js is fast because it offloads waiting to the OS via libuv, keeping the main thread free for execution. Keep your synchronous tasks light, and let the loop do its job! 🌀 #NodeJS #WebDevelopment #SoftwareEngineering #Backend #Javascript #ProgrammingTips
To view or add a comment, sign in
-
🔥 **ES6 Power Moves: Spread, Rest & Template Literals – Level Up Your JS!** 🔥 Senior dev tip: These 3 ES6 features make your code *elegant* and *efficient*. Here's the deep dive with examples—read once, master forever. 🚀 **1. Spread (...) – Expand & Merge** 📈 Unpacks arrays/objects. *Use for:* Cloning, merging, function args. ```js const merged = [...arr1, ...arr2]; // Immutable magic! const copy = { ...obj, newProp: 'value' }; ``` *Why?* No mutations in React/Redux. 🛡️ **2. Rest (...) – Gather Args** 🥳 Collects "leftover" params into an array. *Use for:* Flexible functions. ```js function sum(...numbers) { return numbers.reduce((a,b)=>a+b); } sum(1,2,3,4); // 10 ``` Spread *expands*, Rest *gathers*. Opposite superpowers! 🔄 **3. Template Literals (``)** ✨ Multiline + `${expr}`. *Use for:* Dynamic strings, logs, queries. ```js const msg = `Hi ${name}! Age: ${age}`; // True multiline, no escapes! ``` *Why?* Readable APIs & configs. 🌍 **Pro takeaway:** Cut boilerplate, write cleaner code. Practice these daily! 💪 Which ES6 feature changed your workflow? Comment below! 👇 #JavaScript #ES6 #WebDev #MERN #CodingTips #100DaysOfCode #DeveloperLife
To view or add a comment, sign in
-
-
Stop the console.log madness. 🛑 We’ve all been there: chasing a bug for hours, littering the code with console.log('here'), and accidentally pushing those logs to production. 🤦♂️ After 2 years of Full Stack development, I finally found a better way. The Fix: VS Code JavaScript Debug Terminal 🛠️ Instead of a standard terminal: Open the Terminal dropdown. Select "JavaScript Debug Terminal." Run your service normally (npm start). Why it’s a game changer: Breakpoints: Pause code execution instantly. Live Inspection: Hover over variables to see real-time data. Cleaner Code: Zero logs to delete before you push. Simple, clean, and much faster. Your production logs will thank you. #Javascript #NodeJS #VSCode #WebDev #CodingTips #FullStack
To view or add a comment, sign in
-
-
Today I practiced some important array methods in JavaScript. Arrays get really powerful when you start manipulating data instead of just storing it. Here are a few methods I worked on: let fruits = ["Apple", "Banana", "Mango"]; fruits.push("Orange"); // add at end fruits.pop(); // remove last fruits.shift(); // remove first fruits.unshift("Grapes"); // add at start console.log(fruits); console.log(fruits.includes("Mango")); // check value console.log(fruits.indexOf("Banana")); // find index These methods make handling lists much easier in real projects. Small practice, but now arrays feel way more useful 💻🔥 #JavaScript #FrontendDevelopment #WebDevelopment #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
More from this author
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
The Answer: B) [4, 8] Why? When you use .splice(), you are mutating the array in place. At Index 0, we remove 2. The array "shifts" left. Now, 4 is at Index 0. But the loop moves to Index 1... which is now 6. Result: The number 4 was completely skipped because it moved into the spot the loop already finished! The Fix? Stop using forEach for filtering! Use the built-in .filter() method. It doesn’t mutate the original array and is much more readable: const cleanArray = numbers.filter(num => num % 2 !== 0);