forEach()
is an abstraction for For each element in the array, do something. They makes code shorter, cleaner and easier to interpret.map()
is a higher-order function. It takes as arguments a function f and a list of elements, and as the result, returns a new list with f applied to each element from the list.forEach
to do something with each element in an array, [filter
](link to the .filter tldrdevnote) to build a new array with some elements filtered out, map
to build a new array where each element has been put through a function, and reduce
to combine all an array’s elements into a single value.apply
method that can be used to call them with an array specifying their arguments. They also have a bind
method, which is used to create a partially applied version of the function.here’s a traditional self-contained function
1var total = 0, count = 1
2while (count <= 10) {
3 total += count
4 count += 1
5}
6console.log(total) // 55
here’s the same as a higher order function relying on two external functions
1console.log(sum(range(1, 10))) // 55
A higher-order function is a function that does at least one of the following:
All other functions are first order functions. [1]
Unlike many other languages with imperative features, JavaScript allows you to utilize higher-order functions because it has “first-class functions”. This means functions can be treated just like any other value in JavaScript: just like Strings or Numbers, Function values can be stored as variables, properties on objects or passed to other functions as arguments. Function values are actually Objects (inheriting from Function.prototype) so you can even add properties and store values on them, just like any regular Object.
The key difference between Functions and other value types in JavaScript is the call syntax: if a reference to a function is followed by parenthesis and some optional comma-separated values: someFunctionValue(arg1, arg2, etc), then the function body will be executed with the supplied arguments (if any).