Is filter(x => !!x)
the same as filter(x => !!x && x)
? In both cases the method returns the same thing but I want to know the theories of the answer.
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
Let’s run some tests and see what different values output for each of those. This will show you what happens for each value
Yes, it is the same.
According to MDN
filter
is A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise"truthy" means the value is true when converted to a boolean, i.e.,
!!x
. Otherwise is "falsy". Note thatfilter
doesn’t change the passed valuex
itself.!!x && x
evaluates tox
when!!x
is true, andfalse
when!!x
is false. MDN says "the operator && returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy."So
are all equivalent.