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
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.
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
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.
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.