I tried implementing the internal working of forEach and map to better understand how they operate under the hood. Both are higher order functions because they accept another function as an argument. Internally, they iterate over the array (typically via a loop) and execute the callback for each element. forEach : Iterates through the array. Executes the provided callback on each element. Does not return a new array (returns undefined). Primarily used for logging map : Iterates through the array. Executes the callback on each element. Stores the callback’s return value in a new array. Returns the new transformed array. Does not mutate the original array. Rewriting these methods manually with a for loop really clarifies their behavioral difference : forEach is about execution, map is about transformation. #JavaScript #WebDevelopment #FunctionalProgramming #LearnInPublic #ChaiAurCode
Understanding forEach and map in JavaScript
More Relevant Posts
-
I thought I understood map(), filter() and reduce()… until I wrote their polyfills. We use these methods daily in JavaScript. But I wanted to understand what actually happens behind the scenes. Building polyfills is one of the best ways to master: 1️⃣ Prototypes: How inheritance actually works in JS. 2️⃣ Execution Context: Mastering the behavior of this. 3️⃣ Edge Cases: Handling reduce() accumulators without an initial value. I’ve put together a deep dive into these internals. What’s inside: The logic behind Array.prototype. Step-by-step custom implementations. The "hidden" index logic in .reduce(). Which polyfill was the hardest for you to learn? Let’s discuss below! #Javascript #Chai aur Code #Polyfills
To view or add a comment, sign in
-
🚀 Array Flatten in JavaScript — Quick Concept Nested arrays like [1, [2, 3], [4, [5, 6]]] can be tricky to work with. Flattening helps convert them into a simple structure: 👉 [1, 2, 3, 4, 5, 6] 💡 Why it matters: ✔️ Cleaner data handling ✔️ Easier iteration & transformations ✔️ Common in real-world APIs ✔️ Frequently asked in interviews 🧠 Popular approaches: 🔹 flat() — simple & built-in 🔹 Recursion — best for interviews 🔹 reduce() — functional style 🔹 Stack — iterative solution 👉 Rule to remember: If it’s an array → go deeper, else collect it 📌 Check out the sketchnote infographic for a quick visual understanding! Read the full guide:- https://lnkd.in/gYhbZRpw Chai Aur Code #JavaScript #Coding #WebDevelopment #InterviewPrep #DevTips #chaicode #chaiaurcode
To view or add a comment, sign in
-
-
Another productive class today! 💻✨ We dived deep into core JavaScript concepts: 🔁 Closures – understanding lexical scope and how functions remember their environment 🗑️ Garbage Collector – how memory management works behind the scenes 🌐 DOM Manipulation – dynamically interacting with web pages ⏳ Promises – handling asynchronous operations the right way To apply everything practically, we built a To-Do Website Project 📝 — implementing DOM updates, event handling, and async logic in real time. Learning theory is important, but building projects is where real understanding happens. Consistency + Practice = Mastery 🚀 #JavaScript #WebDevelopment #Closures #Promises #DOM #FrontendDevelopment #CodingJourney Chai Code
To view or add a comment, sign in
-
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled a common but insightful logical challenge: finding the second largest number in an array. This 🧩 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 often appears in technical interviews and requires careful thought to handle edge cases effectively. My ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 involved iterating through the array using JavaScript, keeping track of both the largest and second largest numbers encountered so far. I initialized variables for both to handle the initial comparisons and ensured proper updates as I scanned the array. The 🐞 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗣𝗿𝗼𝗰𝗲𝘀𝘀 was crucial. I performed several dry runs mentally to trace the logic, visualized the flow of variables, and used console logs to verify the state of 'largest' and 'secondLargest' at each step. This helped me catch and correct a minor flaw in the initial comparison logic. A 📚 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 for me was the importance of precise variable initialization and comparison order to correctly handle duplicate maximum values and empty or single-element arrays. Check out the solution in my latest pull request here: https://lnkd.in/dCcT48U9 How do you ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 finding the nth largest element in an array? Share your favorite techniques below! 📦 Repo: https://lnkd.in/dCcT48U9 #ArrayManipulation #JavaScript #Algorithm #ProblemSolving #CodingChallenge #Debugging #SoftwareEngineering #LogicalThinking #DataStructures #LearnToCode
To view or add a comment, sign in
-
-
Arrow Functions — the modern way to write functions Here's the thing about arrow functions. They don't do anything a regular function can't do. They just do it in far fewer characters. And once you see them inside map() and filter(), you never want to go back. In this chapter I cover: → What arrow functions are and why they exist → Basic syntax with a full anatomy diagram (every part labelled) → One parameter — when you can drop the parentheses → Multiple parameters — when they come back → Implicit return vs explicit return (the biggest shortcut) → Arrow vs normal function — comparison table The moment it clicks for most people: Instead of: const doubled = numbers.map(function(n) { return n * 2; }); You write: const doubled = numbers.map(n => n * 2); Same result. One line. Instant readability. Link : https://lnkd.in/gJJV8ARv checkout the hashnode profile : https://lnkd.in/gAwxuryw #JavaScript #ES6 #WebDevelopment #LearnToCode #Frontend #JSFundamentals #chaicode #hoteshchoudhary #piyushgargh
To view or add a comment, sign in
-
-
Solved Linked List Cycle II using Floyd’s Cycle Detection Algorithm (Tortoise and Hare). The approach uses two pointers moving at different speeds to first detect the cycle and then identify the exact node where the cycle begins. Once the pointers meet, resetting one pointer to the head and moving both one step at a time leads them to the cycle start node. Key Takeaways: Efficient cycle detection in linked lists O(n) time complexity O(1) space complexity Classic two-pointer technique #DataStructures #Algorithms #LinkedList #JavaScript #LeetCode #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
📣 𝗡𝗲𝘅𝘁 𝗕𝗹𝗼𝗴 𝗶𝘀 𝗛𝗲𝗿𝗲! ⤵️ Array Methods You Must Know — Writing Less Loops, More Logic ⚡🧠 Working with arrays using only loops feels repetitive. Modern JavaScript gives cleaner tools — and this blog explains them step by step. 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/gqQKdsAc 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Adding and removing elements using push, pop, shift, unshift ⇢ Looping arrays cleanly with forEach() ⇢ Transforming data using map() ⇢ Filtering values using filter() ⇢ Combining array values using reduce() ⇢ Traditional loops vs modern method chaining ⇢ Real beginner examples and practice assignments ⇢ Common mistakes like forgetting return in map/filter ⇢ Mental model to choose the right method 💬 If arrays still feel like “write loop → do work → repeat”, this article helps you understand how modern array methods make code cleaner, shorter, and easier to reason about. #ChaiAurCode #JavaScript #ArrayMethods #WebDevelopment #ProgrammingBasics #Beginners #LearningInPublic #100DaysOfCoding
To view or add a comment, sign in
-
-
🚀 Understanding Promises, Async/Await & Higher-Order Functions (Deep Dive) Today I focused on how JavaScript works behind the scenes — not just syntax, but the logic. #Promises → Handle async operations using the Microtask Queue (higher priority than callback queue). #Async/Await → Cleaner way to write Promises. async returns a Promise, await pauses only that function — not the whole thread. #Higher-Order Functions → Functions that take/return other functions. Powered by closures and lexical scope. Now I understand: • Call Stack • Event Loop • Microtask Queue • Closures JavaScript feels more logical now, not magical. 💻🔥 #JavaScript #WebDevelopment #LearningInPublic #AsyncAwait #100DaysOfCode Vikas Kumar Pratyush Mishra Likitha S Prakash Sakari
To view or add a comment, sign in
-
-
The new Date() object is finally a thing of the past. Welcome to the era of Temporal. 🕰️ We all know the "trauma" of the native Date: zero-indexed months, quirky timezone handling, and the constant reliance on external libraries like date-fns or dayjs. In 2026, the Temporal API is the standard that finally solves these issues for good. THE EVOLUTION OF DATES: 📍 The Old way (Confusion): const date = new Date(); const nextWeek = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000); // Hard to read, easy to make mistakes with milliseconds. 📍 The Modern way (Precision): const today = Temporal.Now.plainDateISO(); const nextWeek = today.add({ days: 7 }); // Readable, semantic, and safe. WHY TEMPORAL WINS: 🔹 Immutability: All Temporal objects are immutable. You no longer have to worry about accidentally mutating a date object in your state management. 🔹 Clear API: Methods like .add(), .subtract(), and .until() are intuitive. No more manual math for durations. 🔹 Native Timezones: Handling timezones with ZonedDateTime is now native and logical. No more "offset" headaches. ⚠️ Note: While Temporal is the new standard, browser support in early 2026 is strong but not universal. For older environments, you’ll still want to keep a polyfill (like @js-temporal/polyfill) in your toolkit. Small architectural shifts like this are what define a modern, maintainable codebase. If you are still fighting with new Date(), it's time for an upgrade. Have you already purged moment.js and dayjs from your projects, or is Temporal still a novelty for you? Let’s discuss below! 👇 #JavaScript #TemporalAPI #WebDev #Programming #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Shipping is a habit! 🚀 2 Days, 2 Projects, and a deeper dive into JavaScript. I’ve been heads-down in the #ChaiAurCode journey, and the momentum is real. Over the last 48 hours, I’ve moved from understanding basic logic to shipping functional mini-projects. Project 1: Dynamic List Creator 📝 Focused on mastering the DOM. It’s one thing to see a list on a screen, it’s another to handle real-time user input, state updates, and clean element creation dynamically. 🌐 Try the List Creator: https://lnkd.in/grMrRqMt Project 2: Color Palette Generator 🎨 This one was a technical "Aha!" moment. 🌐 Try the Palette Generator: https://lnkd.in/gCUwyhrc Key takeaways: ➡️ Precision Math: Implementing Math.random() * (max - min) + min to control color tones (Light vs. Dark). ➡️ String Manipulation: Using .padStart(2, "0") to ensure valid Hex codes a small detail that prevents major UI bugs. ➡️ The Backend Loop: I even experimented with running an Express server and frontend logic in a single file to visualize the full Request-Response cycle. Big thanks to my mentors Hitesh Choudhary and Suraj Kumar Jha for the guidance during the T-class sessions! Github repo links - List Creator - https://lnkd.in/gH9hzGY3 Palette Generator - https://lnkd.in/gEAv7NJ4 (I've shared the screen recording for the List Creator in the comments below! 👇) Anirudh J. Akash Kadlag Jay Kadlag Piyush Garg #WebDevelopment #JavaScript #BuildInPublic #FullStackJourney #LearningTogether #Vercel #CodingProgress
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