0

In the following code:

const names = 'Harry Trump  ;Fred Barney; Helen Rigby ;  ;   ; Bill Abel ;Chris Hand '
let re = /\s*(?:;|$)\s*/;
console.log(names.split(re));
console.log(names.split(re).filter((e) => {return e}));

The second log statement filters out the empty strings. Why is that so, as I would expect a filter that 'returns itself' to basically do nothing, but it seems to evaluate the truthiness of the expression.

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 2
    Empty strings are *falsy*. Soft duplicate of of [All falsey values in JavaScript](https://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript) – esqew Feb 17 '22 at 22:09
  • 3
    "_returns itself_" would make sense for `.map() `. Not for `.filter()`. – Ivar Feb 17 '22 at 22:11
  • 2
    @Ivar oh got it, filter just is looking for a True/False evaluation. – samuelbrody1249 Feb 17 '22 at 22:12
  • 2
    _"it seems to evaluate the truthiness of the expression"_... that's literally what [.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#parameters) does with the return value ~ _Function is a predicate, to test each element of the array. Return a value that coerces to `true` to keep the element, or to `false` otherwise._ – Phil Feb 17 '22 at 22:12
  • `it seems to evaluate the truthiness of the expression`. Not sure why this is a surprise: `filter` evaluates the function you pass it on each element of the array, and *keeps the original element if the result is truthy* [EDIT: beaten to it by @Phil !] – Robin Zigmond Feb 17 '22 at 22:12
  • the `.filter()` takes a *predicate*. Simple as that. – Ergis Feb 17 '22 at 22:15

0 Answers0