Time, tide, and JavaScript wait for none. Let's look at a classic interview-style challenge that proves this with Closures and the Event Loop. The Challenge: Print 1 after 1 second, 2 after 2 seconds, and so on, up to 5. The most intuitive (but flawed) approach using var: function x() { for (var i = 1; i <= 5; i++) { setTimeout(function () { console.log(i); }, i * 1000); } console.log("Hello AI World"); } x(); The Actual Output: Hello AI World 6 6 6 6 6 🤯 Why the Wrong Output? The fundamental reason the original code fails is due to closures interacting with var's function scope. The correct output is achieved by replacing var with let because let creates a block-scoped variable for each iteration, which the closure can then correctly capture. #JavaScript #ReactJS #WebDevelopment #learning
JavaScript Closures and the Event Loop Challenge
More Relevant Posts
-
3 Ways to Access Object Properties in JavaScript When working with objects in JavaScript, you’ll often need to read or update property values. Here are the three essential ways to access them: 1️⃣ Dot Notation – obj.name The most common and readable method. Use it when the property name is a simple, valid identifier. Example: obj.name 2️⃣ Bracket Notation – obj['age'] Helpful when property names contain spaces, special characters, or start with numbers. Also required when the key is dynamic. Example: obj['age'] 3️⃣ Variable (Dynamic) Access – obj[prop] Used when the property name is stored in a variable. Perfect for loops, functions, or dynamic operations. Example: let prop = "name"; obj[prop]; 🚀 Mastering these three access methods is fundamental to understanding how objects work in JavaScript. Let me know if you want a deeper explanation or examples! #Js #AI #Java #php #out #tech #world #dev
To view or add a comment, sign in
-
-
Think recursion is scary? Reversing an array takes just two lines-and the logic is cleaner than you expect 🎯 Let me break down how recursion reverses an array step by step - this'll change how you think about problem-solving! 💪 𝐓𝐡𝐞 𝐓𝐰𝐨-𝐋𝐢𝐧𝐞 𝐌𝐚𝐠𝐢𝐜: function reverseArray(arr, start = 0, end = arr.length - 1) { if (start >= end) return arr; [arr[start], arr[end]] = [arr[end], arr[start]]; return reverseArray(arr, start + 1, end - 1); } 𝐇𝐞𝐫𝐞'𝐬 𝐭𝐡𝐞 𝐬𝐭𝐞𝐩-𝐛𝐲-𝐬𝐭𝐞𝐩 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧 𝐭𝐡𝐚𝐭'𝐥𝐥 𝐦𝐚𝐤𝐞 𝐢𝐭 𝐜𝐥𝐢𝐜𝐤: 🎯 𝐁𝐚𝐬𝐞 𝐂𝐚𝐬𝐞 - When start meets or exceeds end, we're done (no more swapping needed!) 🎯 𝐒𝐰𝐚𝐩 - Exchange elements at start and end positions using destructuring 🎯 𝐑𝐞𝐜𝐮𝐫𝐬𝐢𝐯𝐞 𝐂𝐚𝐥𝐥 - Move inward (start+1, end-1) and let recursion handle the rest 𝐖𝐚𝐭𝐜𝐡 𝐢𝐭 𝐰𝐨𝐫𝐤 𝐰𝐢𝐭𝐡 [1,2,3,4,5]: • Call 1: Swap positions 0,4 → [5,2,3,4,1] • Call 2: Swap positions 1,3 → [5,4,3,2,1] • Call 3: start=2, end=2 (base case reached - we're done!) 𝐖𝐡𝐲 𝐭𝐡𝐢𝐬 𝐚𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝐢𝐬 𝐩𝐮𝐫𝐞 𝐠𝐞𝐧𝐢𝐮𝐬: Recursion handles the "unwinding" naturally. Each call focuses on one swap, then trusts the next call to handle the rest. No loops, no complex indexing - just clean, mathematical thinking that reads like English! 🚀 As a React developer, this same recursive pattern shows up everywhere - component trees, state management, you name it. Master it here and watch those concepts become second nature. Drop a ❤️ if this made recursion click for you! #WebDevelopment #JavaScript #Recursion
To view or add a comment, sign in
-
🧠 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐜𝐚𝐧 𝐛𝐞 𝐰𝐞𝐢𝐫𝐝. 𝐄𝐬𝐩𝐞𝐜𝐢𝐚𝐥𝐥𝐲 𝐰𝐡𝐞𝐧 𝐢𝐭 𝐜𝐨𝐦𝐞𝐬 𝐭𝐨 𝐭𝐲𝐩𝐞 𝐜𝐨𝐞𝐫𝐜𝐢𝐨𝐧. You write a simple expression. Expect a number. Get a string. Or worse NaN. Let’s walk through 5 real examples that trip up even experienced devs and what they actually return. 👇 🔹 1 + "2" + "2" Returns: "122" Why? 1 + "2" → "12" (number + string = string) "12" + "2" → "122" 🔹 1 + +"2" + "2" Returns: "32" Why? +"2" → 2 1 + 2 → 3 3 + "2" → "32" 🔹 1 + -"1" + "2" Returns: "02" Why? -"1" → -1 1 + (-1) → 0 0 + "2" → "02" 🔹 +"1" + "1" + "2" Returns: "112" Why? +"1" → 1 1 + "1" → "11" "11" + "2" → "112" 🔹 "A" - "B" + 2 Returns: NaN Why? "A" - "B" → NaN NaN + 2 → still NaN 💡 Key takeaways: - Unary + converts strings to numbers. - Mixing strings and numbers with + leads to string concatenation. - Non-numeric strings in math return NaN. - Always check your operand types before using +, -, or ==. If you’ve ever been confused by JavaScript’s quirks, you’re not alone. Type coercion is one of the most common sources of bugs in JS. Want more no fluff JavaScript breakdowns? Follow me here 👉 Sumit Mitra JavaScript can be weird. Especially when it comes to type coercion. #JavaScript #WebDevelopment #Frontend #CodingTips #TypeCoercion #JS #SoftwareEngineering
To view or add a comment, sign in
-
A Voyage through Algorithms using JavaScript: Radix Sort - Anatomy of Radix Sort and its implementation. - How digit-by-digit sorting subroutines and stability preservation build sorted output. - Real-world use cases and performance analysis. #javascript #computerscience https://lnkd.in/dDHBQ_jx
To view or add a comment, sign in
-
💡 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 — 𝐓𝐡𝐞 𝐏𝐨𝐰𝐞𝐫 𝐨𝐟 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐌𝐞𝐦𝐨𝐫𝐲 Ever noticed how a function in JavaScript can remember variables — even after it’s done executing? That hidden ability is called a Closure 🔒 🧠 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚 𝐂𝐥𝐨𝐬𝐮𝐫𝐞? A closure happens when an inner function accesses variables from its outer function — even after the outer one has returned. Think of it like a backpack 🎒 the function carries, holding all the variables it needs from where it was created. 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 𝐠𝐢𝐯𝐞 𝐲𝐨𝐮𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 “𝐦𝐞𝐦𝐨𝐫𝐲” — allowing them to retain data, maintain state, and protect variables from being modified externally. ⚙️ 𝐖𝐡𝐲 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 𝐌𝐚𝐭𝐭𝐞𝐫: ✅ Maintain state between function calls. ✅ Create private variables (data privacy). ✅ Build modular, reusable, and cleaner code. ✅ Essential for callbacks, event listeners, and async behavior. 𝐇𝐞𝐫𝐞’𝐬 𝐭𝐡𝐞 𝐦𝐚𝐠𝐢𝐜✨ — Even though createCounter() has finished running, the inner function still remembers count because of the closure. Each call updates the same stored value, proving that functions in JavaScript can truly remember. 🚀 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲: Closures may seem tricky at first, but once you master them, you’ll unlock a deeper understanding of how JavaScript handles scope, memory, and data flow. #JavaScript #WebDevelopment #Frontend #CodingTips #Closures #Programming #TechLearning #Developers
To view or add a comment, sign in
-
-
Let me confess something......... In my early days, "React", "TypeScript", "Next.js" and "DSA" looked shiny and exciting. Meanwhile, I was still fighting Javascript and stuck in tutorial hell, hoping the next video would finally make sense. It never did......!!!! I barely understood my own code, but I still believed I “knew Javascript.” Eventually I realised No one knows a language 100%. 50% simply means everyone is always learning, because this field never stops evolving. I used to avoid documentation, but "MDN docs", "javascript.info" and many other Documentations changed everything. Concepts finally connected. Errors made sense. And even if you love “vibe coding,” fundamentals are what save you. They reduce your 10 AI prompts to 2. AI will not replace you now, it will just watch you write longer prompts. So if you are starting out Just Remember these slow down, learn your basics, and read documentation. #GoingBackToBasics #Frontend #JavaScript
To view or add a comment, sign in
-
🚀 #Day14 DSA & JavaScript Algorithms Journey Binary Search Algorithm Precision in Action ⚡ Today, I finally implemented the Binary Search Algorithm — one of the most efficient search techniques in DSA. 🧩 Problem Statement: Given a sorted array of n elements and a target element (t), find the index of t in the array. If the target element is not found, return -1. (Remember: Binary Search only works on sorted arrays!) 💡 How It Works: In every iteration, the input size reduces by half, as the search focuses only on the relevant portion of the array using the two-pointer method left and right boundaries keep narrowing down until the target is found. 🧮 Examples: 1️⃣ arr = [-5, 2, 4, 6, 10], t = 10 → Output: 4 2️⃣ arr = [-5, 2, 4, 6, 10], t = 6 → Output: 3 3️⃣ arr = [-5, 2, 4, 6, 10], t = 20 → Output: -1 (Not Found) ⚙️ Efficiency: The power of Binary Search lies in its ability to cut the problem size in half each step making it far more efficient than linear search for large datasets. This was a fun and insightful problem to solve, sharpening both logic and optimization thinking! 💪 #DSA #JavaScript #BinarySearch #CodingJourney #ProblemSolving #LearnInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA Notes: Mastering Loops & Operators in JavaScript 🔁 1. for Loop — Most Common in DSA A for loop repeats code a specific number of times — making it ideal when the iteration count is known. ✅ Definition: A loop that runs as long as the condition is true, incrementing a counter on each step. 📌 Example for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } 🎯 Why It Matters in DSA Used in: Array traversal Linear search Prefix sums Dynamic Programming table filling Sliding window Counting problems 🔄 2. while Loop — Condition-Based Iteration A while loop runs until a condition becomes false. Perfect for scenarios where the number of steps is unpredictable. ✅ Definition: A loop that keeps running based on a logical condition instead of a fixed count. 📌 Example let i = 0; while (i < arr.length) { console.log(arr[i]); i++; } 🎯 Used in DSA For Two-pointer techniques BFS / DFS traversal Reading streams Iterations that depend on data, not fixed size 🟦 3. Key JavaScript Operators (DSA-Focused) 🔹 Assignment Operator OperatorMeaningExample=Assigns valuelet a = 10 🔹 Equality Operators Very important for comparing values in conditions. OperatorTypeMeaning==Loose equalityCompares values only===Strict equalityCompares value + type!=Loose inequalityNot equal (value only)!==Strict inequalityNot equal (value + type) 📌 Example 5 == "5" // true (value same) 5 === "5" // false (type different) 🔹 Relational Operators Used heavily in searching, sorting, and comparisons. OperatorMeaning<Less than>Greater than<=Less than or equal>=Greater than or equal 📌 Example if (num > max) { max = num; }
To view or add a comment, sign in
-
-
JavaScript Simplified: Destructuring & Spread Operator Ever noticed how JavaScript lets you write cleaner and shorter code? That’s where Destructuring and the Spread Operator (...) come in! What is Destructuring? Destructuring means “unpacking” values from arrays or objects into variables— instead of accessing each one manually. const user = { name: "Sameer", age: 22 }; const { name, age } = user; console.log(name, age); // Sameer 22 You can even rename or set default values: const { country: location = "India" } = user; What is the Spread Operator (...)? The spread operator helps you copy, merge, or expand arrays and objects effortlessly. const fruits = ["apple", "banana"]; const moreFruits = ["orange", "grapes"]; const allFruits = [...fruits, ...moreFruits]; console.log(allFruits); // ["apple", "banana", "orange", "grapes"] It also works great with objects: const user = { name: "Sameer", age: 22 }; const updatedUser = { ...user, age: 23 }; console.log(updatedUser); // { name: "Sameer", age: 23 } In short: Destructuring → Pull out values easily Spread → Copy or merge effortlessly #JavaScript #WebDevelopment #Frontend #CodingTips #Destructuring #SpreadOperator #LearnJS
To view or add a comment, sign in
-
💡JavaScript Reboot: JavaScript's New Era, ECMAScript 2025 + AI Magic🤖 🚀 JavaScript in 2025: ECMAScript Leaps & AI-Powered Apps! Just dropped: JavaScript’s ECMAScript 2025 update is packed with brand-new features that make coding cleaner, faster, and more advanced. 💡Highlights: - Pattern Matching for smarter, readable conditionals. - Immutable Records & Tuples for superstable data. - Async upgrades for smoother APIs. - Powerful new Set methods (union, intersection, difference) - Promise.try() for error-handling made easy But that’s not all! 🤖🛠️ AI is now woven into the JavaScript developer toolkit: with TensorFlow.js and generative AI APIs, you can build 🧠 Intelligent, interactive web apps right in the browser—NO BACKEND REQUIRED 🚫🖥️(lightweight tasks and interactive web experiences). Are you using these features or building with AI in JS? Please feel free to comment and share your thoughts. 😊
To view or add a comment, sign in
Explore related topics
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