Stop misusing JavaScript array methods. Small choices like this quietly shape code quality. One of the most common clean-code mistakes I see is using `forEach()` when the real intention is transformation. If your goal is to create a new array from existing data, `map()` is the right tool. `map()` returns a new array. It keeps your logic functional and predictable. It communicates intent clearly: “I am transforming data.” That clarity improves readability and long-term maintainability. `forEach()`, on the other hand, is built for side effects—logging, DOM updates, triggering external behavior. It does not return a new array. When you push into another array inside `forEach()`, you’re working against the language instead of with it. A simple rule of thumb: * If you’re creating a new array → use `map()` * If you’re performing side effects → use `forEach()` * If you’re filtering → use `filter()` instead of manual conditions Clean code isn’t about writing more lines. It’s about choosing the right abstraction for the job. Intentional developers let method names express meaning. So be honest—are you team `map()`, or still reaching for `forEach()` when transforming data? #JavaScript #CleanCode #FrontendDevelopment #WebEngineering #SoftwareCraftsmanship #CodeQuality #ReactJS
Choose map() for data transformation, forEach() for side effects
More Relevant Posts
-
Just wrapped up my 3rd JavaScript project - a Random Quote Generator! 🎲 This one was different. Not because it's complex (it's actually pretty simple), but because I finally *got* async/await. I've been reading about Promises and .then() chains for weeks. Understood them conceptually, but they always felt... messy? Like I was fighting with the syntax instead of just writing code. Then I rebuilt this project using async/await and something clicked. The code just reads like normal code. Top to bottom. No nesting. Clean error handling. It finally makes sense. Here's what changed for me: Before (with .then chains): fetch(url) .then(response => response.json()) .then(data => displayQuote(data)) .catch(error => handleError(error)); After (with async/await): async function getQuote() { try { const response = await fetch(url); const data = await response.json(); displayQuote(data); } catch (error) { handleError(error); } } Same functionality. Way easier to read. The debugging moment that taught me the most: Spent 15 minutes wondering why my quote wasn't displaying. Kept getting "undefined." Turns out the API returns an array, not an object. So data.quote didn't work. But data[0].quote did. Simple fix. But it taught me to always console.log() API responses first before assuming their structure. Built in about an hour. Learned way more than an hour's worth. Small projects. Real learning. 🌐 Live: https://lnkd.in/gsf3dvfe 💻 Code: https://lnkd.in/gt2mwRFH #JavaScript #AsyncAwait #WebDevelopment #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
-
🚀 JavaScript Async / Await Explained Simply ❓ Still confused about Async / Await in JavaScript? Many beginners struggle with asynchronous code when working with APIs, data fetching, or timers. But Async / Await makes it much simpler. ⚡ Instead of writing long Promise chains with .then(), you can write clean and readable code that looks synchronous. 💡 Why developers love Async / Await ✔ Cleaner and readable code ✔ Easier error handling with try...catch ✔ Perfect for API calls and real-world apps ✔ Built on top of Promises 📌 Simple Example async function getData() { const response = await fetch("https://lnkd.in/dMuhWf2B"); const data = await response.json(); console.log(data); } ⚡ Pro Tip: Before learning Async / Await deeply, make sure you understand JavaScript Promises. 🔥 Quick Question for Developers Do you prefer using: 1️⃣ Promises (.then) or 2️⃣ Async / Await Comment below 👇 📌 Follow for more JavaScript concepts explained simply. #javascript#webdevelopment#frontenddeveloper#coding#programming#learnjavascript#softwaredeveloper#100daysofcode#techcommunity
To view or add a comment, sign in
-
-
🚀 Day 3 / 100 — #100DaysOfCode Most people want to jump straight into frameworks. Today I did the opposite. I went back to the JavaScript fundamentals — because strong foundations compound faster than shiny tools. Here’s what I revised today 👇 🧠 Operators The building blocks of logic in JavaScript. From arithmetic (+ - * /) to comparison (===, !==) and logical operators (&&, ||). They help control how values interact and how conditions are evaluated. 🔁 Loops Automation for repetitive tasks. Revisited for, while, and for...of loops — essential when iterating over arrays, running repeated logic, or processing data collections. ⚙️ Functions Reusable blocks of logic. Functions allow us to write clean, modular code and avoid repetition. Also revisited arrow functions, which make syntax more concise. 📦 Array Methods Some of the most powerful tools in JavaScript. Refreshed methods like: • map() → transform data • filter() → extract specific items • reduce() → combine values into one result These are core to writing clean functional-style JavaScript. 🔒 var vs let vs const Understanding scope is critical. • var → function scoped, older JS • let → block scoped, mutable • const → block scoped, immutable reference Modern JS prefers let and const for predictable behavior. 🧩 Closures One of JavaScript’s most powerful concepts. A closure allows a function to remember variables from its outer scope even after the outer function has finished executing. This is used in callbacks, state management, and many JS patterns. ⏳ Promises & Async/Await JavaScript is asynchronous by nature. • Promises represent a value that will be available in the future • async/await makes asynchronous code look synchronous and much easier to read This is the backbone of API calls, database queries, and modern web apps. ✨ Lesson from today: Frameworks change every year. But JavaScript fundamentals stay forever. Small daily improvements → Big long-term growth. Day 3/100 complete. #JavaScript #WebDevelopment #100DaysOfCode #BuildInPublic #CodingJourney #Developers #LearnInPublic
To view or add a comment, sign in
-
-
🤯 JavaScript Promises Made Simple Ever written code that depends on something that takes time… like an API request or data loading? That’s where Promises come in. Think of a Promise like ordering food online 🍕. When you place the order, three things can happen: 1️⃣ Pending – Your order is being prepared 2️⃣ Fulfilled – Your food is delivered ✅ 3️⃣ Rejected – Something went wrong ❌ JavaScript uses Promises to handle tasks that take time without stopping the rest of the program. 💻 Simple Example const myPromise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Task completed!"); } else { reject("Task failed!"); } }); myPromise .then(result => console.log(result)) .catch(error => console.log(error)); 👉 How it works • resolve() → runs .then() • reject() → runs .catch() ⚡ Why developers use Promises • Handle asynchronous tasks easily • Avoid callback hell • Work perfectly with async/await 💬 Do you prefer using .then() or async/await when working with promises? 👇 Comment your answer! 🔁 Follow for more simple JavaScript explanations. #javascript #webdevelopment #frontenddeveloper #coding #learnprogramming #softwaredevelopment #100daysofcode #programminglife #developers #tech
To view or add a comment, sign in
-
-
Catching bugs at 2:00 PM but they don’t wake me up at 2:00 AM. 🛠️ Moving from #JavaScript to #TypeScript wasn’t just a syntax change; it was a shift in confidence. By defining our data structures upfront, we’ve effectively eliminated the "undefined is not a function" errors that used to haunt our production logs. The Difference: In JS, you pass an object and hope the property exists. In TS, the editor won't even let you save the file until you've handled the possibility of it being missing. Example: // JavaScript: The "Finger-Crossing" Method function getUsername(user) { return user.profile.name; // Runtime Error if profile is missing! } // TypeScript: The "Contract" Method interface User { profile?: { name: string }; } function getUsername(user: User) { return user.profile?.name ?? "Guest"; // Type-safe and explicit } The initial setup takes a few extra minutes, but the hours saved in debugging are immeasurable. Have you made the switch yet? Or are you still team Vanilla? 👇 #WebDevelopment #TypeScript #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
🚀 Deep Dive into JavaScript Promises: all, allSettled, race, and any! 🔥 Struggling to manage multiple asynchronous operations in JavaScript? Modern JS provides four powerful "combinator" methods to handle arrays of Promises. Here is your ultimate cheat sheet: 1️⃣ **Promise.all() — The Perfectionist** - Waits for all promises to resolve. - Rejects immediately (fast-fails) if even one promise fails. - Returns an array of results. - **Best for:** When every single piece of data is required to move forward. 2️⃣ **Promise.allSettled() — The Observer** - Waits for all promises to finish (either fulfilled or rejected). - Never rejects. Returns an array of objects detailing `{status, value/reason}` of each. - **Best for:** When you need all outcomes and want to handle successes and failures independently. 3️⃣ **Promise.race() — The Sprinter** - Settles as soon as the first promise settles (resolves OR rejects). - Ignores everything else. - **Best for:** Implementing timeouts (racing a fetch request against a rejection timer). 4️⃣ **Promise.any() — The Optimist** - Waits for the first promise to succeed. - Ignores failures unless all of them fail (throws an `AggregateError`). - **Best for:** Pinging multiple mirror servers and taking the first one that successfully responds. Save this post for your next coding session! 📌 #JavaScript #Promises #AsyncJS #WebDevelopment #CodingTips #FrontendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗮𝘀𝗶𝗰𝘀 𝗼𝗳 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗩𝘀 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 You write code in JavaScript. But do you know how it runs? - Synchronous code runs line by line, one after another. - Asynchronous code does not wait. Here is an example of Synchronous code: console.log("Start") function slowTask() { for (let i = 0; i < 1e9; i++) {} console.log("Task Done") } slowTask() console.log("End") Output: Start Task Done End Here is an example of Asynchronous code: console.log("Start") setTimeout(() => { console.log("Task Done") }, 2000) console.log("End") Output: Start End Task Done JavaScript is single-threaded. This means it can only do one task at a time. Asynchronous code helps with this. It lets your website keep running while it waits for something to happen. There are three main ways to write Asynchronous code in JavaScript: - Callback: an old method - Promise: a better method - Async/Await: the best and most modern method You can use Async/Await like this: function fetchData() { return new Promise((resolve) => { setTimeout(() => { resolve("Data fetched") }, 2000) }) } async function getData() { let data = await fetchData() console.log(data) } getData() Source: https://lnkd.in/gxZ4NMhr
To view or add a comment, sign in
-
⭕ Mastering JavaScript Array Methods with Practical Examples Understanding array methods like map(), filter(), reduce(), and find() is essential for writing clean and efficient JavaScript code. 🔹 1. map() – Transform Data const prices = [100, 200, 300]; const updatedPrices = prices.map(price => price + 50); console.log(updatedPrices); // [150, 250, 350] Used to transform each element and return a new array. ➖ ➖➖➖➖➖➖➖➖➖➖➖➖➖ 🔹 2. filter() – Select Data const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // [2, 4, 6] Used to return elements that match a condition. ➖ ➖➖➖➖➖➖➖➖➖➖➖➖➖ 🔹 3. reduce() – Accumulate Data const cart = [500, 1000, 1500]; const totalAmount = cart.reduce((total, item) => total + item, 0); console.log(totalAmount); // 3000 Used for totals, sums, and complex calculations. ➖➖➖➖➖➖➖➖➖➖➖➖➖ 🔹 4. find() – Find First Match const users = [ { id: 1, name: "Rahul" }, { id: 2, name: "Aman" } ]; const user = users.find(userObj => userObj.id === 2); console.log(user); // { id: 2, name: "Aman" } Used to retrieve a specific item based on a condition. ✨ Strong fundamentals in JavaScript improve React components, backend logic in Node.js, and overall project performance. Continuous learning + practical implementation = Better development skills. #JavaScript #MERN #WebDevelopment #FrontendDevelopment #NodeJS #Coding #Developers
To view or add a comment, sign in
-
🚨 Is .then().catch() dead after try...catch in JavaScript? Short answer: No. Both are alive and useful. The real difference is how you structure asynchronous code. 🔹 1️⃣ Promise style — .then().catch() This was the original way to handle async operations with Promises. Example: fetch("/api/data") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); ✅ Best when: You want simple promise chains Writing functional pipelines Handling single async operations 🔹 2️⃣ Async/Await style — try...catch Modern JavaScript introduced async/await, making async code look like synchronous code. Example: async function getData() { try { const res = await fetch("/api/data"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } ✅ Best when: You have multiple sequential async calls You want cleaner, readable code Handling complex error flows 💡 Key Insight async/await is actually built on top of Promises. So .then() and .catch() are still working under the hood. 👉 It's not about which one is better. 👉 It's about which one fits the situation. 📌 Quick Rule Small async chain → .then().catch() Complex async logic → async/await + try...catch JavaScript keeps evolving, but understanding both patterns makes you a stronger developer. #javascript #webdevelopment #frontend #nodejs #asyncawait #promises #coding #softwaredevelopment #100DaysOfCode
To view or add a comment, sign in
-
Explore related topics
- Simple Ways To Improve Code Quality
- Coding Best Practices to Reduce Developer Mistakes
- How to Achieve Clean Code Structure
- How to Improve Code Maintainability and Avoid Spaghetti Code
- Clean Code Practices For Data Science Projects
- Building Clean Code Habits for Developers
- How to Improve Your Code Review Process
- How Developers Use Composition in Programming
- Preventing Bad Coding Practices in Teams
- Best Practices for Writing Clean Code
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