Summary
The article explains the e ⇒ e syntax in JavaScript filter callbacks, the common misconception around null/NaN handling, and why senior engineers handle this elegantly.
Root Cause
- Misunderstanding of arrow functions:
e => eis a concise arrow function that returns the argument unchanged. - Filter logic error:
Array.prototype.filterexpects a boolean return; non‑truthy values (null,NaN,undefined) are removed. - Naming confusion: Using
efor both element and function name can mislead readers.
Why This Happens in Real Systems
- Sparse data sources: APIs often return
nullorundefinedplaceholders. - Default value handling: Developers use filter to remove falsy items, unintentionally stripping valid
0or''. - Legacy code: Older codebases adopt terse styles, obscuring intent.
Real-World Impact
- Data loss: Removing legitimate zero values or empty strings in financial calculations.
- Runtime bugs: Functions expecting non‑falsy items crash when encountering filtered‑out entries.
- Regression risk: Minor refactors unintentionally alter filter behavior.
Example or Code (if necessary and relevant)
// Intent: keep only truthy values
const filterTruthy = arr => arr.filter(e => e);
console.log(filterTruthy([null, NaN, 0, 1, undefined])); // [1]
How Senior Engineers Fix It
- Use descriptive arrow functions:
const filterOutInvalid = arr => arr.filter(item => item !== null && item !== undefined); - Add explicit checks for NaN:
const filterOutInvalid = arr => arr.filter(item => !isNaN(item)); - Leverage utility libraries (Lodash, Ramda) that offer robust predicates.
- Write unit tests for edge cases (0, ”, NaN, objects).
- Document intent in comments to prevent future confusion.
Why Juniors Miss It
- They assume
filterkeeps everything unless told otherwise. - They miss the subtlety that the arrow function’s parameter name hides the returned value.
- They overlook falsy values beyond
null/undefined. - They lack exposure to test‑driven development that catches these regressions.