Higher-order functions
Functions that take or return functions.
- A HOF either takes one or more functions as arguments, or returns a function.
- Only possible because JS has first-class functions.
- HOFs power the DRY principle — extract iteration once, pass behaviour as a callback.
- Examples:
map,filter,reduce,sort,forEach,debounce,throttle.
map() — transform every element
New array, same length.
- Callback
(currentValue, index, array)— returns the transformed value for each element. - Always returns a new array of the same length. Original is untouched.
- Chainable because it returns an array.
- map vs forEach: map returns a new array; forEach returns
undefinedand is for side effects only.
filter() — select by condition
New array, ≤ original length.
- Callback returns truthy/falsy — truthy keeps the element.
- Returned array can be shorter or empty.
arr.filter(Boolean)drops all falsy values in one shot.- Chainable — commonly used before
mapto shrink the array first.
reduce() — accumulate to one value
Single result of any type.
- Callback
(accumulator, currentValue, index, array)— return the new accumulator. - Always pass an initial value (
0,[],{}) to avoid edge-case bugs with empty arrays. - Can replicate both
mapandfilter— most flexible of the three. - Great for counting, grouping, building objects, flattening — things map/filter can’t do alone.
Polyfills — interview essentials
Write them from scratch, often asked.
- myMap: loop with
for, pushcallback(this[i], i, this)into a new array, return it. - myFilter: loop, push
this[i]only if the callback returns truthy. - myReduce: handle the optional initial value (default to
this[0], start from index 1), accumulate. - All three live on
Array.prototypeand usethisto access the array they were called on.
Classic gotchas
The ones interviewers love.
["1","2","3"].map(parseInt)→[1, NaN, NaN]— parseInt receives(value, index); index becomes radix.arr.filter(Boolean)— removes all falsy values (0,"",null,undefined,false,NaN).reducewithout initial value on an empty array throwsTypeError.findreturns first match;someis “any?”;everyis “all?” — short-circuit HOFs.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.