skip to Main Content

I was learning filter method, but is filter method similar to if else or are there any differences?
I am expecting that there might be some difference between them.
And is it necessary to create a new variable whenever we are using filter method().
like let us say

const numbers = [1,2,3,4,5,6,7,8]
const odd = nums.filter(n => {
     return num % 2 === 1;
}

I can also implement the above code using if/else but why filter method?

2

Answers


  1. The filter method and if-else statements serve different purposes and have distinct use cases in JavaScript.

    • filter is used for filtering elements in an array based on a condition, whereas if-else is used for controlling the flow of your program based on a condition.

    • filter returns a new array containing the elements that meet the condition, while if-else statements execute different code blocks based on the condition.

    • They have different use cases: filter is ideal for selecting elements from an array, while if-else is used for making decisions and controlling program flow.

    const numbers = [1, 2, 3, 4, 5];
    const evenNumbers = numbers.filter((number) => number % 2 === 0);
    // evenNumbers will contain [2, 4]
    
    Login or Signup to reply.
  2. Let understand what is filter in JavaScript

    Filter as name suggested it’s filter you array or object as your requirement.

    The different between if-else and filter is that
    if else is condition that use inside filter ( map, for, for-each ) loop.

    If-else is conditions
    filter is loop

    Remember that filter is always return new array. it not change original array.
    It’s make separate space in memory of you computer.

    let’s understand with example

    let assume you have to available you game for person who above 18
    and not more than 40 year then you use if-else-else

    if (age < 18) {
      return false;
    } else if (age > 40) {
       return false;
    } else {
     return true;
    }
    

    This way filter is work and return true false based on conditions.

    And for filter let assumed you have one array of object which have games name with age restriction.

    const games = [
         { name: "game 1", age: 25 },
         { name: "game a", age: 8 },
         { name: "game b", age: 48 },
         { name: "game 2", age: 20 },
     ];
    
     const filterGame = games.filter((game) => game.age < 40 && game.age > 18);
     console.log(filterGame);
    

    Here is this example we are filtering game where age group are between 18 to 40.
    And remembers , there is no compulsory so store filter data into new var. you can maintain that array or object as you requirement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search