🚀 What is filter() in JavaScript? (Complete Guide for Developers) In JavaScript, filter() is a powerful array method used to create a new array by selecting elements that meet a specific condition. It does not modify the original array — instead, it returns a new filtered array. 📌 Syntax: array.filter((element, index, array) => { return condition; }); element → Current item being processed index (optional) → Index of the current element array (optional) → The original array 🔎 Simple Example: const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4, 6] 👉 Here, filter() returns only the numbers divisible by 2. 📦 Real-World Example (Filtering Objects): const users = [ { name: "Ali", active: true }, { name: "Sara", active: false }, { name: "Ahmed", active: true } ]; const activeUsers = users.filter(user => user.active); console.log(activeUsers); ✅ This is commonly used in: Search functionality Product filtering (e-commerce) Dashboard data filtering Status-based filtering 💡 Important Points: ✔ filter() does not change the original array ✔ It always returns a new array ✔ If no element matches → returns an empty array ✔ It works great with arrow functions 🆚 Difference from map() and forEach(): map() → transforms every element filter() → selects elements based on condition forEach() → executes logic but returns nothing 🎯 Why Every Developer Should Master filter(): Because modern web apps rely heavily on dynamic data manipulation — and filter() makes your code cleaner, readable, and functional-programming friendly. Clean code + Functional methods = Better performance & maintainability ✨ Are you using filter() in your projects? Drop your favorite use case below 👇 #JavaScript #FrontendDevelopment #WebDevelopment #Coding #100DaysOfCode
JavaScript filter() Method: Select Elements by Condition
More Relevant Posts
-
𝗛𝗼𝘄 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗪𝗼𝗿𝗸𝘀 𝗢𝗻 𝗕𝗿𝗼𝘄𝘀𝗲𝗿 You want to know how JavaScript works on a browser. Let's break it down. JavaScript is a programming language that makes web pages interactive. It was created to run inside browsers, but now it also runs on servers using environments like Node.js. A web page is made of: - HTML: structure - CSS: styling - JavaScript: behavior When you visit a web page, your browser loads HTML, creates a DOM tree, and downloads CSS to create a CSSOM. These combine to form a Render Tree, which is displayed on the screen. The browser has a rendering engine and a JavaScript engine, like Google's V8. The V8 engine executes JavaScript code, but it does not change the DOM or UI. Instead, it uses browser APIs to do that. Browser APIs include: - document - getElementById - querySelector - createElement - setTimeout - fetch - WebSocket - localStorage - sessionStorage - geolocation - history - navigator The V8 engine's code is written in C++. To understand the event loop, you need to know how JavaScript code executes. JavaScript is a single-threaded language, so every instruction is executed line by line. The JavaScript engine creates a global execution context, which is divided into two sections: - variable environment - execution context When a promise comes, it goes into the microtask queue, and when a timeout is called, it goes into the callback queue. The event loop resolves the microtask queue first, then the callback queue. When you open a website, your browser downloads HTML, creates a DOM tree, and downloads CSS to create a CSSOM. If JavaScript exists, it is sent to the V8 engine, which executes it. If JavaScript modifies the DOM, the browser updates the DOM, and the screen updates. Source: https://lnkd.in/gJirTwcw
To view or add a comment, sign in
-
🚀 JavaScript Developers: Understanding the Difference Between `map()`, `forEach()`, and `for` Loops When working with arrays in JavaScript, there are several ways to iterate over data. The most common ones are `map()`, `forEach()`, and the traditional `for` loop. Although they may look similar, they serve different purposes. --- 📌 for Loop The traditional `for` loop gives you full control over the iteration. • You define the start and end of the loop • You can use `break` or `continue` • Useful for complex logic or performance-sensitive operations Example: const numbers = [1, 2, 3, 4]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } --- 📌 forEach() `forEach()` is used when you want to execute an action for each element in an array. • Runs a function for every element • Does not return a new array • Commonly used for side effects like logging or triggering functions Example: const numbers = [1, 2, 3, 4]; numbers.forEach(num => { console.log(num); }); --- 📌 map() `map()` is used when you want to transform data and return a new array. • Applies a transformation to every element • Returns a new array Example: const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] --- 💡 Simple rule to remember • Use map() when you want a new transformed array • Use forEach() when you want to execute something for each item • Use for loops when you need more control over the loop Understanding these differences helps you write cleaner and more readable JavaScript code. 👨💻 Which one do you use the most in your projects? #JavaScript #WebDevelopment #Frontend #Programming #Developers #ReactJS
To view or add a comment, sign in
-
-
From Confusion to Clarity: My First Real JavaScript “Cart Logic” Breakthrough 🚀 When I started learning JavaScript, I thought the hardest part would be syntax. querySelector() addEventListener() forEach() Turns out… syntax is the easy part. The real challenge is thinking in logic. Recently, while building a small E-commerce product page, I hit a moment where everything started making sense. Here’s what I learned 👇 1️⃣ DOM Events Are Just Signals When a user clicks a button, the DOM doesn't magically know what product to add. You must connect the UI action to your data. Example flow: User clicks Add to Cart ⬇ Get product index from button ⬇ Use that index to access the product from the array ⬇ Update the cart const index = e.target.dataset.index; const product = productsData[index]; That one line made me realize: The UI only triggers events — the real data lives in JavaScript. 2️⃣ Arrays Are the Backbone of Logic Products live inside an array: productsData[index] This simple concept powers almost every frontend application. Once you understand how to access data in arrays, the logic starts to click. 3️⃣ find() vs findIndex() — A Huge Realization While implementing the cart, I learned something important: find() → returns the object findIndex() → returns the position Example: const existingIndex = cartData.findIndex( item => item.productname === product.productname ); We use findIndex because removing an item requires its position in the array. 4️⃣ Cart Logic Is Actually Simple When the user clicks Add to Cart: • If the product already exists → increase quantity • If not → push a new object into the cart When the user clicks Remove: • If quantity > 1 → decrease quantity • If quantity = 1 → remove the item completely This tiny piece of logic is basically how every e-commerce cart works. 5️⃣ One Big Lesson Frontend development is not about writing code. It’s about building clear data flow. UI → Event → Data → Logic → Updated UI Once that mental model clicks, everything becomes easier. This small project taught me more about JavaScript logic than hours of tutorials. Still learning. Still building. But every day the pieces are starting to connect. #JavaScript #WebDevelopment #LearningInPublic #FrontendDevelopment
To view or add a comment, sign in
-
🚀 Just Built a Simple Shopping Cart using JavaScript & LocalStorage! I practiced JavaScript DOM manipulation and LocalStorage by building a small cart system where users can add products with quantities and keep the data saved even after refreshing the page. 💡 Features: • Add product with quantity • Update quantity if product already exists • Store data in LocalStorage • Retrieve stored cart after page reload 🧑💻 Sample Code: const handleAddCart = () => { const productEl = document.getElementById('product') const quantityEl = document.getElementById('quantity') const product = productEl.value; const quantity = parseInt(quantityEl.value); productAddToUl(product, quantity); addToCart(product, quantity) productEl.value = ''; quantityEl.value = ''; } const getCart = () => { let cart = {} const cartJson = localStorage.getItem('cart'); if(cartJson){ cart = JSON.parse(cartJson) } return cart; } const addToCart = (product, quantity) => { const cart = getCart(); if(cart[product]){ cart[product] = cart[product] + quantity; }else{ cart[product] = quantity; } const cartJson = JSON.stringify(cart); localStorage.setItem('cart', cartJson) } #JavaScript #WebDevelopment #FrontendDeveloper #LocalStorage #Coding GitHub Repository:https://lnkd.in/gYrfSkkY
To view or add a comment, sign in
-
💡 JavaScript Concept Every Developer Should Understand — this One concept that often confuses beginners in JavaScript is the this keyword. A simple way to understand it is by remembering 4 basic rules. 🚀 The 4 Rules of this in JavaScript 1️⃣ Global Context Rule If this is used outside any function, it refers to the global object. In browsers, the global object is window. console.log(this); Output: Window {. . .} So here: this → window 2️⃣ Object Method Rule When a function is called using an object, this refers to that object. const person = { name: "Rahul", greet: function() { console.log(this.name); } }; person.greet(); Execution: person.greet() So: this → person Output: Rahul 3️⃣ Normal Function Rule If a function is called normally (not through an object), this refers to the global object (window) in browsers. function show() { console.log(this); } show(); Execution: show() So: this → window 4️⃣ Arrow Function Rule Arrow functions do not create their own this. They inherit this from the surrounding scope. const obj = { value: 10, show: function() { const arrow = () => { console.log(this.value); }; arrow(); } }; obj.show(); Here: this → obj Output: 10 🧠 Simple way to remember GLOBAL SCOPE │ ├── Normal function → this = window │ OBJECT METHOD │ ├── this = object │ ARROW FUNCTION │ └── this = inherited from parent #JavaScript #WebDevelopment #CodingConcepts #FrontendDevelopment #LearnToCode
To view or add a comment, sign in
-
🔥 JavaScript Event Loop Explained (Simply) JavaScript is single-threaded. But then how does this work? 👇 console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Most developers get this wrong in interviews. Let’s break it down properly 👇 🧠 1️⃣ Call Stack Think of the Call Stack as: The place where JavaScript executes code line by line. It follows LIFO (Last In, First Out). console.log("Start") → runs immediately console.log("End") → runs immediately Simple so far. 🌐 2️⃣ Web APIs When JavaScript sees: setTimeout() It sends it to the browser’s Web APIs. Web APIs handle: setTimeout DOM events fetch Geolocation JavaScript doesn’t wait for them. 📦 3️⃣ Callback Queue (Macrotask Queue) After setTimeout finishes, its callback goes into the Callback Queue. But it must wait… Until the Call Stack is empty. ⚡ 4️⃣ Microtask Queue Promises don’t go to the normal queue. They go to the Microtask Queue. And here’s the important rule 👇 Microtasks run BEFORE macrotasks. So the execution order becomes: 1️⃣ Start 2️⃣ End 3️⃣ Promise 4️⃣ Timeout 🎯 Final Output: Start End Promise Timeout 💡 Why This Matters Understanding the Event Loop helps you: ✔ Debug async issues ✔ Write better Angular apps ✔ Avoid race conditions ✔ Pass senior-level interviews Most developers memorize async code. Senior developers understand the Event Loop. Which one are you? 👀 #JavaScript #Angular #Frontend #WebDevelopment #EventLoop #Async
To view or add a comment, sign in
-
-
🚀 Understanding Debounce in JavaScript (Real-World Example) Every time the user typed a character, the application was calling the API. If a user types “javascript”, the API may get called 10 times. This creates unnecessary: • Server load • Network requests • Slow performance To solve this problem, I implemented Debouncing. --- 💡 What is Debouncing? Debouncing ensures that a function runs only after the user stops typing for a specific time. Instead of calling the API on every keystroke, the function waits for a short delay. --- 🧑💻 Simple Debounce Example function debounce(callback, delay) { let timer; return function(value) { clearTimeout(timer); timer = setTimeout(function() { callback(value); }, delay); }; } const search = debounce(function(query) { console.log("API Call for:", query); }, 500); --- ⚙️ How it works 1️⃣ User starts typing in the search input 2️⃣ A timer starts for 500ms 3️⃣ If the user types again, the previous timer is cancelled 4️⃣ The API call happens only when the user stops typing --- 📊 Without Debounce User typing javascript J → API call Ja → API call Jav → API call Java → API call JavaS → API call Multiple unnecessary API requests. --- 📊 With Debounce User typing javascript User keeps typing → timer resets User stops typing → Single API Call --- 📌 Real-World Use Cases • Search suggestions • Input validation • Window resize events • Scroll events • Auto-save features Small optimizations like this can significantly improve application performance and reduce backend load. If you're building modern web applications, understanding patterns like Debounce and Throttle can make your applications more efficient. #javascript #webdevelopment #frontend #nodejs #performance #softwareengineering #backenddeveloper
To view or add a comment, sign in
-
💡 JavaScript Array Methods Every Developer Must Know If you want to write cleaner, shorter, and more readable JavaScript code, mastering array methods is non-negotiable. Array methods not only simplify logic but also help you write functional, scalable, and interview-ready code. 🚀 Here are some essential array methods every developer should master: 🔹 Transformation & Iteration ✅ "map()" → Transform each element ✅ "forEach()" → Iterate without returning a new array ✅ "flatMap()" → Map + flatten in one step 🔹 Filtering & Searching ✅ "filter()" → Get elements based on condition ✅ "find()" → First matching element ✅ "findIndex()" → Index of matching element ✅ "some()" → Check if at least one element matches ✅ "every()" → Check if all elements match 🔹 Aggregation & Utilities ✅ "reduce()" → Powerful method for totals, grouping & complex logic ✅ "sort()" → Sort elements (numbers/strings/custom logic) ✅ "includes()" → Check if value exists ✅ "indexOf()" / "lastIndexOf()" → Find element position 🔹 Modification Methods ✅ "push()" / "pop()" → Add or remove from end ✅ "shift()" / "unshift()" → Add or remove from start ✅ "splice()" → Add/remove elements anywhere ✅ "slice()" → Copy portion of array without mutation 🔥 Why these methods matter 👉 Improve code readability 👉 Reduce loops & boilerplate logic 👉 Essential for React state updates 👉 Frequently asked in JavaScript interviews 👉 Useful in real-world data transformation As a React developer, I use these methods daily for state updates, API data transformation, and UI rendering logic. Consistency in practicing these methods can dramatically level up your problem-solving and coding confidence. 💬 Which array method do you use the most? Comment below 👇 #JavaScript #ArrayMethods #JSBasics #FrontendDevelopment #WebDevelopment #ReactJS #CodingTips #LearnInPublic
To view or add a comment, sign in
-
🚀 map(), filter(), reduce() in JavaScript (with Definitions + Examples) (Part:3) These 3 array methods are must-know if you want to get strong in JavaScript Example array: let arr = [1, 2, 3, 4, 5]; 1️⃣ map() → Transform data Definition: map() creates a new array by applying a function to each element. let result = arr.map((num) => num * 2); console.log(result); // [2, 4, 6, 8, 10] ✔️ Use when you want to modify every element 2️⃣ filter() → Select data Definition: filter() creates a new array with elements that satisfy a condition. let result = arr.filter((num) => num > 2); console.log(result); //[3, 4, 5] ✔️ Use when you want to pick specific values 3️⃣ reduce() → Combine data Definition: reduce() reduces the array to a single value by applying a function. let result = arr.reduce((acc, num) => acc + num, 0); console.log(result); // 15 ✔️ Use for sum, totals, complex calculations Key Differences: >> map → transforms each element >> filter → selects elements >> reduce → combines into one value 🎯 Important Note: >>> These methods do not change the original array (they return a new one) # forEach() vs map() : 1️⃣ forEach() >> Executes a function for each element >> Does NOT return anything let result = arr.forEach((num) => { return num * 2; }); console.log(result); // undefined 2️⃣ map() >> Transforms each element >> Returns a NEW array let result = arr.map((num) => num * 2); console.log(result); // [2, 4, 6] #JavaScript #Frontend #WebDevelopment #Coding #LearnInPublic
To view or add a comment, sign in
-
🚀 Continuing Web Development Basics – JavaScript (Getting Started) After learning HTML and CSS, I started with JavaScript, the language that makes web pages interactive and dynamic. Today I focused on basic JavaScript concepts to build a strong foundation. 🔹 What is JavaScript? JavaScript is used to: • Add interactivity to web pages • Handle user actions (clicks, input) • Update content dynamically 🔹 Basic JavaScript Topics 1️⃣ Variables Used to store data. let name = "John"; let age = 22; 2️⃣ Data Types Common types: • String → "Hello" • Number → 10 • Boolean → true/false 3️⃣ Operators Used to perform operations. let sum = 5 + 3; let isEqual = (5 == 5); 4️⃣ Conditional Statements Used for decision making. let age = 18; if (age >= 18) { console.log("Eligible"); } else { console.log("Not Eligible"); } 5️⃣ Loops Used to repeat tasks. for (let i = 1; i <= 3; i++) { console.log(i); } 6️⃣ Functions Reusable block of code. function greet(name) { console.log("Hello " + name); } greet("John"); 7️⃣ Events (Basic) JavaScript responds to user actions. <button onclick="alert('Button Clicked')">Click Me</button> 🔹 Why Learn JavaScript? • Makes websites interactive • Works with HTML & CSS • Essential for frontend development • Required for full-stack development Starting with basics is important before moving to advanced concepts like DOM, APIs, and frameworks. Next step: Deeper JavaScript concepts and DOM manipulation. #JavaScript #WebDevelopment #DotNetDeveloper #FrontendDevelopment #LearningJourney #FullStackDevelopment
To view or add a comment, sign in
-
More from this author
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