For vs. While: Which loop wins? 🔄 I just coded a battery drain simulator to test my JavaScript logic. Here’s the rule of thumb I used: Use FOR when you know the number of laps (e.g., "Loop 10 times"). Use WHILE when you’re waiting for a result (e.g., "Loop until the battery hits 0"). In this code, since the battery drop is random, I don't know the number of laps—making the while loop the perfect tool for the job. #Coding #JavaScript #WebDev #Logic
JavaScript Loop Choice: For vs While
More Relevant Posts
-
Here is the golden rule: Use .forEach() when you want to DO something. (Like logging to the console or pushing to an external array). It returns undefined. Use .map() when you want to CREATE something new. It returns a brand new array of the same length. JavaScript const numbers = [1, 2, 3]; // ❌ Bad: Using map just to loop (creates an unused array in memory) numbers.map(num => console.log(num)); // ✅ Good: Using map in React to create an array of JSX elements const UI = numbers.map(num => <li key={num}>{num}</li>); Understanding this difference is crucial for writing clean, bug-free components! #JavaScript #ReactJS #CodingLife #WebDevelopment #Programming #LearnToCode
To view or add a comment, sign in
-
-
Ever had perfectly fine-looking code… that just won’t run? 🤯 I ran into a sneaky JavaScript bug today: let x = 5; console.log(x) Looks correct, right? But it throws an error. The culprit 👉 that tiny character after 5 is not a real semicolon. It’s actually a Greek question mark (;) instead of the standard ;. ➡️ JavaScript doesn’t recognize it ➡️ The code breaks silently ➡️ You waste time debugging something that looks fine ✅ Fix: let x = 5; console.log(x); 💡 Lesson: Not all characters that look identical are actually the same — especially when copying code from PDFs, websites, or different keyboards. Sometimes debugging isn’t about logic… it’s about spotting the invisible. #JavaScript #Coding #Debugging #WebDevelopment #ProgrammingTips
To view or add a comment, sign in
-
-
DOM Manipulation Challenge: Are you doing it WRONG? Let's test your JavaScript logic! 🧠 Look at the code in the image. We added click listeners to 1,000 items. Then, we added a brand new item to the list. Question: When you click that NEW item, what happens in the console? A) "Item clicked!" B) Nothing at all C) Error If you guessed B, you're right! This is why "Event Delegation" is a senior-level skill every developer needs to master. It saves memory and handles new items automatically. 💻✨ Tell me your answer in the comments! 👇 Hashtags: #JavaScript #CodingQuiz #WebDev #100DaysOfCode #LearnToCode #CodeWithSarir #FrontendDevelopment #ProgrammingTips #JSLogic #codinglife #programmer
To view or add a comment, sign in
-
-
#Day7 Understanding Loops in JavaScript. I truly began to understand why they’re one of the most powerful concepts in programming. Loops are what turn static code into dynamic, intelligent systems. Whether you're processing user data, building animations, fetching API results, or running simulations, loops are doing the heavy lifting behind the scenes. Here are the types of loops listed in the diagram : => while Loop : It checks the condition before executing so if the condition is false from the start, the code never runs. => Do while loop : This is otherwise called the “optimistic” loop. It runs the code at least once before checking the condition. It is very useful for scenarios where you need user input or an initial action before validation. => For loop : This is my current favourite. Clean, readable, and perfect when you know the exact number of iterations or need control over the counter. Who else is currently learning or strengthening their JavaScript fundamentals? #M4ACELearningchallenge #LearningInPublic #JavaScript #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
-
LeetCode Day 21 : Problem 209 (Minimum Size Subarray Sum) Just solved my LeetCode problem for today. It was "Minimum Size Subarray Sum", find the shortest contiguous subarray whose sum is greater than or equal to a target. My first approach was trying to trim the array from both ends. Remove elements from the front if the sum still holds, then figure out the length at the end. It felt logical in my head but it failed on most test cases and I couldn't immediately see why. The bugs were deeper than I expected. The first one was a JavaScript gotcha that had nothing to do with the algorithm. I wrote newArr = nums thinking I was making a copy. I wasn't. Both variables pointed to the same array in memory, so when I called shift() on newArr, I was also mutating nums mid-loop. The loop was iterating over an array that was shrinking underneath it, silently skipping elements. The second issue was the trimming logic itself. I was only ever looking at the first element when deciding what to remove. That is not how you find a minimal window. You need to consider every possible left boundary, not just the front of the array at that moment. The third was a line I wrote thinking it was doing something: newArr.unshift() with no argument. It adds nothing, returns the length, and the result goes nowhere. Completely dead code that I mistook for a shrink operation. The correct approach is a dynamic sliding window. Expand the right pointer freely. The moment your window sum meets the target, record the length and shrink from the left. Keep shrinking as long as the condition still holds. The smallest window you ever record is your answer. The subtle difference from a longest-window problem is where you record the answer. Here it goes inside the shrink loop, before you remove the left element, because you want the smallest valid window not the largest. The real lesson? Mutating an array while iterating over it is one of the most silent bugs in JavaScript. Always copy with slice or spread when you need an independent array. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
Just realized something interesting about JavaScripts memory optimisation behaviour with primitives while digging into runtime behavior 👇 Values like true, false, undefined, null, and even common string literals (like "") aren’t recreated every time you declare them. JS engines (like V8) treat these as shared, immutable values: • They exist only once internally • Variables just hold references to them So when you write: let a = true; let b = true; You’re not creating two true values — both just point to the same underlying value. Same idea applies to: • false • undefined • null • frequently used string literals 👉 Small detail, but shows how much memory optimization happens under the hood, a neat reminder that JavaScript does more for performance than we often think. #JavaScript #V8 #Performance #Programming #Backend
To view or add a comment, sign in
-
🚀 JavaScript Challenge #1 What will be the output? console.log(1 + "2" + 3); Think before you answer 👇 Most people get this wrong. 👉 JS converts numbers to strings when needed: 1 + "2" → "12" "12" + 3 → "123" ✅ Output: "123" 💡 Lesson: Type coercion can silently change your logic. Did you get it right? 😄 Follow for more daily Challenges
To view or add a comment, sign in
-
If you're only using Arrays and Objects in JavaScript, you're limiting yourself. Map and Set exist for a reason — and they solve problems cleaner. → Need unique values? Set does it instantly → Need proper key-value storage? Map beats Object Less workaround. More clarity. Wrote a quick breakdown with examples. Read here: 🔗 https://lnkd.in/drqhd7Vg #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
-
JavaScript is single threaded, but handles async operations so smoothly 👇 That’s where the Event Loop comes in. At first, things seem simple: • Code runs line by line But then you see behavior like this: Even with 0ms, the timeout doesn’t run immediately. Because JavaScript uses: ✔ Call Stack ✔ Web APIs ✔ Callback Queue ✔ Event Loop Understanding this changed how I think about async code and debugging. Sometimes the delay isn’t about time, it’s about how the event loop schedules execution. #JavaScript #EventLoop #AsyncJavaScript #FrontendDevelopment #Programming
To view or add a comment, sign in
-
-
I spent HOURS debugging… and the bug was just ONE line. 😅 Everything looked fine. No syntax errors. No warnings. But the output? Completely wrong. console.log([] == false); // true console.log([] === false); // false Wait… what? 🤯 How can the same values give different results? Then it hit me — one of JavaScript’s most confusing concepts: 👉 Type Coercion Here’s what’s happening behind the scenes: "[] == false" ➡ JavaScript converts both values ➡ becomes "0 == 0" ➡ ✅ true "[] === false" ➡ Strict comparison (no conversion) ➡ ❌ false Same values. Different rules. Completely different results. ⚠️ This is where many bugs are born — not because we don’t know JavaScript… but because JavaScript behaves unexpectedly. 💡 Lesson (relearned the hard way): Always prefer "===" over "==" ✔ "===" → checks value + type ❌ "==" → tries to be “smart” (and gets risky) Sometimes debugging isn’t about writing more code… it’s about understanding how the language actually works. Have you ever faced a bug that made you question everything? 👇 #JavaScript #Debugging #WebDevelopment #Programming #Developers #Coding #SoftwareEngineering #LearnToCode #TechLife
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