✅ Logical Operators in JavaScript – Complete Guide with Real Examples

Image
๐Ÿ“Œ Introduction Logical operators help you combine conditions, control flow, and make decisions in JavaScript. In this guide, you’ll learn how to use && , || , and ! effectively with examples and real-world use cases. ๐Ÿ” What Are Logical Operators? Logical operators return a boolean value ( true or false ) and are used to evaluate expressions, especially within conditions like if statements. Operator Name Example Description && Logical AND a && b Returns true if both conditions are true || Logical OR a || b Returns true if either condition is true ! Logical NOT !a Reverses the boolean value ✅ 1. Logical AND ( && ) const age = 25; const isCitizen = true; if (age > 18 && isCitizen) { console.log("You can vote!"); } Short-circuiting: If the first condition is false, the second one isn’t evaluated. ✅ 2. Logi...

๐Ÿง  Understanding filter() as a Higher-Order Function in JavaScript

Understanding filter() as a Higher-Order Function

๐Ÿ“Œ Introduction

JavaScript is a language designed to treat functions as first-class citizens. This means you can pass functions as arguments, return them from other functions, and assign them to variables — opening the door to higher-order functions. One of the most widely used higher-order functions is filter().

In this blog, we'll take a deep dive into:

  • What is a higher-order function in JavaScript?
  • What is filter() and why it's considered a higher-order function?
  • Real-world examples of using filter()
  • Code snippets to boost your learning
  • Q&A to answer common developer queries

๐Ÿ” What is a Higher-Order Function in JavaScript?

A higher-order function is any function that does at least one of the following:

  1. Takes another function as an argument (callback function)
  2. Returns a function as its result

function greetUser(greetingFn) {
  greetingFn();
}

function sayHello() {
  console.log("Hello, Developer!");
}

greetUser(sayHello); // Output: Hello, Developer!
  

๐Ÿงฎ Real-World Analogy: The "Filter Coffee" Machine

Imagine you're in a cafรฉ, and you want your coffee filtered — only what meets the criteria (taste, aroma, strength) passes through. Similarly, the JavaScript filter() method processes elements in an array and filters out the ones that match a given condition.

๐Ÿง  What is filter() in JavaScript?

The filter() method is an array method that creates a new array filled with elements that pass a test (provided by a callback function).

๐Ÿงพ Syntax


array.filter(callbackFunction(element, index, array), thisArg)
  

๐Ÿ”ง Why is filter() a Higher-Order Function?

Because it accepts a callback function as its argument, filter() is a textbook example of a higher-order function.

๐Ÿ“˜ Practical Examples of Using filter() in JavaScript

✅ 1. Filter Even Numbers from an Array


const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
  

✅ 2. Filter Users Above a Certain Age


const users = [
  { name: "Ankur", age: 28 },
  { name: "Rahul", age: 17 },
  { name: "Priya", age: 21 }
];

const adults = users.filter(user => user.age >= 18);
console.log(adults);
  

✅ 3. Conditional Filtering with Function Composition


function isAbove18(user) {
  return user.age > 18;
}

const adultUsers = users.filter(isAbove18);
  

๐Ÿค” Why Should You Use filter()?

Feature Why It Matters
Dynamic behavior Change filter logic on the fly
Modularity Keep filtering logic separate
Reusability Use the same filter function across components
Immutability filter() returns a new array without modifying the original
Clean Syntax Easy to read and expressive

๐Ÿ’ก Advanced Filtering Concepts


const prices = [100, 200, 300, 400];

// Filter and then apply 10% discount
const discountedPrices = prices
  .filter(price => price > 200)
  .map(price => price * 0.9);

console.log(discountedPrices); // [270, 360]
  

๐Ÿง  Related Concepts to Understand

Concept Definition Example
Currying Breaking a function into smaller functions const add = a => b => a + b;
Memoization Caching function results Useful for expensive filters
Callback Function Function passed to another Used in filter()
Function Composition Combining functions to build complex logic filter().map().reduce()

❓ Common Questions (Q&A)

Q1: Can I use filter() on non-array data?

No, but you can convert array-like structures using Array.from().

Q2: Does filter() modify the original array?

No. It returns a new array.

Q3: Is filter() better than for loops?

For readability and clean code, yes. But traditional loops might perform better in edge cases.

Q4: Can I filter based on multiple conditions?


const filtered = numbers.filter(num => num > 10 && num < 50);
  

Q5: Can filter() be used on objects?


const obj = { a: 1, b: 2, c: 3 };

const filteredEntries = Object.entries(obj)
  .filter(([key, value]) => value > 1);

console.log(Object.fromEntries(filteredEntries)); // { b: 2, c: 3 }
  

๐Ÿงพ Final Thoughts

Using filter() as a higher-order function is more than just filtering values — it’s about writing elegant, modular, and reusable code.

๐Ÿ”— Bonus: Learn More on Higher-Order Functions

Check out my in-depth post on useMemo in React for performance optimization.

Enjoyed this post? Share it and follow the blog for more JavaScript tips!

Comments

Popular posts from this blog

How to Fix npx tailwindcss init Error: “Could Not Determine Executable to Run”

๐Ÿš€ “JavaScript Debounce Made Simple + Live Example!”

๐Ÿ› ️ How to Create a React App with Vite and Tailwind (Beginner Guide)