Hey LinkedIn Family 👋 A small JavaScript habit that improved how I handle arrays: 🚀 Use Array.filter(Boolean) to clean data quickly. Earlier, I used to write: const values = ["React", "", null, "JavaScript", undefined]; const clean = values.filter(item => item); Now I prefer: const values = ["React", "", null, "JavaScript", undefined]; const clean = values.filter(Boolean); Result 👇 ["React", "JavaScript"] Why this works well ✅ Cleaner and more expressive ✅ Removes falsy values (null, undefined, "", 0, false) ✅ Very useful for API responses and dynamic data Real-world usage 👇 const tags = [user?.skill1, user?.skill2, user?.skill3].filter(Boolean); ⚠️ Watch out This also removes 0 and false. If those are valid values in your data, this can introduce subtle bugs. Biggest Lesson: Good JavaScript is not just about shortcuts… It’s about knowing when to use them and when not to. What’s a small JS trick you use that saved you from a bug? 👇 #JavaScript #ReactJS #ReactNative #Programming #SoftwareEngineering #CodingTips #DeveloperLife
Use Array.filter(Boolean) to Clean Arrays in JavaScript
More Relevant Posts
-
Stop writing basic JavaScript! 🛑🚀 If you want to write cleaner, faster, and more professional code, you need to move past the basics and use modern JS features. I’ve put together a quick carousel covering 4 real-world JavaScript tips that I use every day as a Full-Stack Developer to keep my codebase clean: 1️⃣ Destructuring Aliases: Rename variables instantly when pulling them out of an object. const { data: userList } = response; 2️⃣ Optional Chaining (?.): Stop your app from crashing when an object property is undefined! const name = user?.profile?.name; 3️⃣ Nullish Coalescing (??): Set fallbacks only for null or undefined (unlike || which catches 0 and ""). const limit = userLimit ?? 10; 4️⃣ Fast Boolean Conversion (!!): The fastest way to convert any truthy/falsy value into a real Boolean. const hasData = !!data.length; Swipe through the carousel to see them in action! 👉 Which one of these do you use the most? Let me know below! 👇 #JavaScript #WebDevelopment #ReactJS #NodeJS #CodingTips #BuildInPublic #TechCommunity #MERN
To view or add a comment, sign in
-
🚀 Mastering Async/Await in JavaScript (Without the Headaches) If you’ve ever dealt with messy ".then()" chains in JavaScript, you know how quickly things can get out of hand. That’s where async/await comes in — making asynchronous code look and behave more like synchronous code. 🔹 What is async/await? It’s a modern way to handle asynchronous operations in JavaScript, built on top of Promises. 🔹 Basic Example: async function fetchData() { try { const response = await fetch('https://lnkd.in/gDCe34XD'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } 🔹 Why use async/await? ✔ Cleaner and more readable code ✔ Easier error handling with "try...catch" ✔ Avoids “callback hell” and long ".then()" chains 🔹 Key Points to Remember: - "async" makes a function return a Promise - "await" pauses execution until the Promise resolves - Use "try...catch" for error handling - Works only inside "async" functions 💡 Pro Tip: Use async/await for API calls, database queries, or any operation that takes time — your future self (and your teammates) will thank you. #JavaScript #WebDevelopment #AsyncAwait #CodingTips #Frontend #Developers
To view or add a comment, sign in
-
-
Every JavaScript developer has shipped this bug: async function processStream(response) { const reader = response.body.getReader() while (true) { const { done, value } = await reader.read() if (done) break processChunk(value) // ← throws an error } reader.releaseLock() // ← never reached. Stream locked forever. } The fix? A try...finally block you have to remember to write every single time. ES2026's using keyword makes this class of bug impossible. 🔒 using readerResource = { reader: response.body.getReader(), [Symbol.dispose]() { this.reader.releaseLock() } } // releaseLock() called automatically — even if processChunk throws Add [Symbol.dispose]() to any class, and using guarantees cleanup when scope exits — on return, on break, or on error. For async resources, await using + [Symbol.asyncDispose] handles it: await using redis = new RedisClient(config) // redis.quit() runs automatically when scope exits The proposal also ships: → DisposableStack — manage multiple resources, disposed LIFO → SuppressedError — preserves both errors if cleanup itself throws → Works in for loops — dispose at end of each iteration TypeScript has supported it since 5.2. Chrome 134+, Firefox 134+, Node.js 22+. Babel transpiles it for older targets. I wrote the complete guide for DB connections, transactions, streams, WebSockets, mutexes, perf timers, and DisposableStack patterns. Have you started using this yet? 👇 #JavaScript #ES2026 #WebDev #NodeJS #Programming #100DaysOfBlogging
To view or add a comment, sign in
-
JavaScript in 2026: The Dev Update You Didn't Know You Needed ECMAScript continues to evolve, and this year's updates are particularly noteworthy for JavaScript developers. Here’s a comprehensive overview of what’s new, what’s on the horizon, and why it matters. 1. Temporal API — The Biggest JS Feature in Years (ES2026) Date handling in JavaScript has faced challenges since 1995. With the Temporal API, that’s changing. const now = Temporal.Now.zonedDateTimeISO("Asia/Kolkata"); console.log(now.toLocaleString()); // Correct. Always. 2. using keyword — Automatic Resource Cleanup (ES2026) This feature simplifies resource management in asynchronous functions. async function saveData() { await using file = new FileHandle("output.txt"); await file.write("hello"); // file auto-closed here, even on error } No more worries about forgetting to close database connections or file handles. The runtime ensures cleanup when the variable goes out of scope, which is a significant improvement for server-side Node.js development. 3. Iterator Helpers — Lazy Evaluation (ES2025) This update enhances efficiency by allowing lazy evaluation without creating extra arrays. // Old way: creates 3 new arrays array.map(x => x*2).filter(x => x>10).slice(0, 3); // New way: zero extra arrays, stops after 3 Iterator.from(array).map(x => x*2).filter(x => x>10).take(3).toArray(); This feature works seamlessly with Sets, Maps, Generators, and any iterable, improving performance and memory usage. Additional updates include: - Array.fromAsync() — Collect async generator results into an array effortlessly - Iterator.concat() — Lazily iterate across multiple pages/sources - Error.isError() — Reliably detect real Error #JavaScript #ECMAScript2026 #WebDevelopment #TypeScript #FrontendDev #NodeJS #Programming #SoftwareEngineering #TechNews #CodingLife
To view or add a comment, sign in
-
-
🚀 𝐃𝐚𝐲 6 – 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 (𝐒𝐢𝐦𝐩𝐥𝐞 & 𝐂𝐥𝐞𝐚𝐫) JavaScript is single-threaded… 👉 But then how does it handle things like `setTimeout`? 🤔 Let’s understand the real flow 👇 --- 💡 The Setup JavaScript uses: * Call Stack → runs code * Web APIs → handles async tasks * Callback Queue → waits for execution * Event Loop → manages everything --- 💡Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); --- 💡 Output: Start End Timeout --- 💡 Why? (Step-by-step) * `Start` → runs immediately * `setTimeout` → sent to Web APIs * `End` → runs immediately * Timer completes → callback goes to Queue * Event Loop checks → Stack empty * Callback pushed to Stack → executes --- ⚡ Key Insight 👉 Even with `0ms`, it does NOT run immediately 👉 It waits until the Call Stack is empty --- 💡 Simple Mental Model 👉 “Async code runs after sync code finishes” --- 💡 Why this matters? Because it explains: * execution order * async behavior * common bugs --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Promises (Async Made Better)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
JavaScript Proxy — A Hidden Superpower You Should Know Most of us create objects like this: const frameworkName = { name: "Next JS" }; But what if you could intercept and control every operation on this object? That’s exactly what JavaScript Proxy does. Think of it like a gatekeeper sitting in front of your object — it can monitor, modify, or block any interaction. const frameworkName = { name: "Angular" }; const proxyFramework = new Proxy(frameworkName, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updating ${prop} to ${value}`); if (value === "React") { console.log("React is not allowed!"); throw new Error("React is not allowed!"); // Throw an error to prevent the update return false; // Prevent the update } target[prop] = value; return true; } }); proxyFramework.name; // 👉 Reading name proxyFramework.name = "Next"; Why should you care? ✔ Track changes (great for debugging) ✔ Add validation before updating values ✔ Build reactive behavior (like frameworks do) ✔ Control or restrict access to data Real-world use cases: • Form validation without extra libraries • Logging state changes for debugging • Building custom state management • Data sanitization before saving Pro Tip: Frameworks like Vue use Proxy internally to make data reactive. Understanding this can level up your frontend skills. Have you used Proxy in your projects, or are you still sticking with plain objects? #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
*JavaScript Beginner Roadmap* 🌐✨ 📂 *Start Here* ∟📂 Set Up Your Environment (Browser Console, VS Code) ∟📂 Write & Run Your First JS Script 📂 *JavaScript Basics* ∟📂 Variables (`let`, `const`, `var`) ∟📂 Data Types (Number, String, Boolean, Null, Undefined, Object) ∟📂 Operators (Arithmetic, Comparison, Logical) ∟📂 Control Flow (`if`, `else`, `switch`) ∟📂 Loops (`for`, `while`, `do-while`) 📂 *Functions* ∟📂 Function Declaration & Expression ∟📂 Arrow Functions ∟📂 Parameters & Return Values ∟📂 Scope & Closures 📂 *Objects & Arrays* ∟📂 Creating & Accessing Objects ∟📂 Arrays & Array Methods (`push`, `pop`, `map`, `filter`) 📂 *DOM Manipulation* ∟📂 Selecting Elements (`getElementById`, `querySelector`) ∟📂 Changing Content & Styles ∟📂 Event Handling (`click`, `input`) 📂 *Asynchronous JavaScript* ∟📂 Callbacks ∟📂 Promises ∟📂 Async/Await 📂 *Debugging & Tools* ∟📂 Console & Breakpoints ∟📂 DevTools Basics 📂 *Practice Projects* ∟📌 Interactive To-Do List ∟📌 Simple Calculator ∟📌 Quiz App 📂 ✅ *Next Steps* ∟📂 Learn ES6+ Features ∟📂 Introduction to Frameworks (React, Vue) ∟📂 Explore APIs & Fetch Data JavaScript Resources: https://lnkd.in/d4hnv6C2 *React "❤️" for more!* #js #webdev #webdeveloper #webaap #web
To view or add a comment, sign in
-
🚀 JavaScript String Methods Strings are one of the most common data types in JavaScript, and yet, so many devs underuse the powerful methods that come with them. Here are some essential ones to know: ✂️ 𝘀𝗹𝗶𝗰𝗲(𝘀𝘁𝗮𝗿𝘁, 𝗲𝗻𝗱): extract a substring 🔄 𝗿𝗲𝗽𝗹𝗮𝗰𝗲() / 𝗿𝗲𝗽𝗹𝗮𝗰𝗲𝗔𝗹𝗹(): update parts of a string 🔍 𝗶𝗻𝗰𝗹𝘂𝗱𝗲𝘀(): check if a substring exists 🔠 𝘁𝗼𝗨𝗽𝗽𝗲𝗿𝗖𝗮𝘀𝗲() / 𝘁𝗼𝗟𝗼𝘄𝗲𝗿𝗖𝗮𝘀𝗲(): format consistently 🔢 𝗶𝗻𝗱𝗲𝘅𝗢𝗳() / 𝗹𝗮𝘀𝘁𝗜𝗻𝗱𝗲𝘅𝗢𝗳(): find character positions 📏 𝗹𝗲𝗻𝗴𝘁𝗵: total character count 🧼 𝘁𝗿𝗶𝗺() / 𝘁𝗿𝗶𝗺𝗦𝘁𝗮𝗿𝘁() / 𝘁𝗿𝗶𝗺𝗘𝗻𝗱(): clean up whitespace 🔗 𝘀𝗽𝗹𝗶𝘁(): break a string into an array ➕ 𝗰𝗼𝗻𝗰𝗮𝘁(): combine strings (or just use +) 🔡 𝗰𝗵𝗮𝗿𝗔𝘁() / 𝗰𝗵𝗮𝗿𝗖𝗼𝗱𝗲𝗔𝘁(): access individual characters Save & share with your team! Download Our Free Full-Stack Developer Starter Kit ➡️ https://buff.ly/JbI0Qof --- If you found this guide helpful, follow TheDevSpace | Dev Roadmap, w3schools.com, and JavaScript Mastery for more tips, tutorials, and cheat sheets on web development. Let's stay connected! 🚀 #React #JavaScript #CheatSheet #WebDevelopment
To view or add a comment, sign in
-
-
JavaScript Polyfills (forEach, map, filter, reduce): I explored how commonly used JavaScript array methods work internally by creating my own custom polyfills. ✔ forEach() – Iterates over each element (no return) ✔ map() – Transforms data and returns a new array ✔ filter() – Returns elements that satisfy a condition ✔ reduce() – Accumulates values into a single output Writing these polyfills helped me understand: • Callback function execution • Internal iteration logic • How new arrays are created • How reduce builds value step-by-step • Difference between transformation and filtering This exercise improved my understanding of higher-order functions and core JavaScript fundamentals. Naveen Kumar K G Raghu K #JavaScript #Polyfill #FrontendDevelopment #WebDevelopment #LearnInPublic #MERNStack #CodingJourney #JavaScriptDeveloper #BackendDevelopment #NodeJS #ExpressJS #MongoDB
To view or add a comment, sign in
-
😵💫𝗢𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴 𝘁𝗵𝗶𝗻𝗴𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: `...` At first glance, it looks simple. But depending on where you use it, it completely changes its role. Same syntax. Different behavior. That’s where most developers get tripped up. So I decided to break it down clearly: ✍️ New Blog Published: 𝗦𝗽𝗿𝗲𝗮𝗱 𝘃𝘀 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗘𝘅𝗽𝗮𝗻𝗱 𝗼𝗿 𝗖𝗼𝗹𝗹𝗲𝗰𝘁 𝗟𝗶𝗸𝗲 𝗮 𝗣𝗿𝗼 https://lnkd.in/gFPgrdEv 🔍 What you’ll learn: 🔹 When ... acts as a Spread Operator (expanding data) 🔹 When it becomes a Rest Operator (collecting data) 🔹 Real-world use cases to eliminate confusion Hitesh Choudhary Piyush Garg Chai Aur Code Anirudh J. Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #LearningInPublic #Chaicode #Cohort
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