Need an explanation! please

can somebody explain to me how does this function work ? i understand the filter() thing but what i cannot get is the e . how does the filter function know if
e is a falsy value or not ?? and what is e .
Here’s the function :

function bouncer(arr) {
  return arr.filter(e => e);
}

e (or the first argument to the callback) is each of the elements in the array iterated by the array method and passed to the callback function. Most array method callbacks take (element, index, originalArray) as their arguments. But there are methods like reduce that is a little different.

[1, 2, 3, 4].forEach((element) => console.log(element)); // 1,2,3,4

Array.prototype.filter()

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

1 Like

i already know that but how did the filter function know that false and null … are falsy values ? i mean we didn’t put any condition inside the function ? i do not understand how it worked

Because they are values that coerce to true. So values where Boolean() would return true, or say an if statement would evaluate to true. If you want to see the actual implementation details of the method you have to look at the runtime environment (like a browser) source code. You can also look at the specs for array.prototype.filter.

It is basically something like this:

loop the array
call the callback function and pass the current array element to it
if the callback function returns a value that coerces to true
add the element to the new array
return the new array

Here is a non prototype version I had laying around (ignore the optionalThisObject for simplicity sake):

const values = [1, 'test', '', null, NaN, true, false, [], {}, undefined];

function filter(array, callback, optionalThisObject) {
  const filteredArray = [];
  let filterCallback = callback;

  if (optionalThisObject) {
    filterCallback = callback.bind(optionalThisObject);
  }

  for (let i = 0; i < array.length; i++) {
    if (filterCallback(array[i], i, array)) {
      filteredArray.push(array[i]);
    }
  }
  return filteredArray;
}

console.log(filter(values, (value) => value)); // [ 1, 'test', true, [], {} ]
1 Like

thank you so much man i appreciate all the help! now i understand :slight_smile: