JavaScript higher-order functions

Notes about couple higher-order functions for strings and arrays.

String.prototype.trim()

Removes whitespace from both sides of the string. Can also be used to remove newlines.


String.prototype.split([separator], [limit])

Returns an array of string values. String values are original value's pieces split with the value of separator parameter. If separator is not specified, an array with the original string is returned.

  • separator: Specifies the separator value. String or regexp.
  • limit: Specifies how many split pieces are added to array. Values after this number are not added to returned array.

Array.prototype.map(function(currentValue, [index], [arr]), [thisValue])

Creates a new array with values returned from callback function.

  • currentValue: Current value / row in array.
  • index: Array index of current element.
  • arr: The array object the current element belongs to
  • thisValue: Value used instead as a this value.

Array.prototype.reduce(function(total, currentValue, [currentIndex], [arr]), [initValue])

Reduces array to a single value. Goes trough array values. In first run initValue is the start value. Use total to get that and return it for next run.

  • total: Returned value from last run or if not yet initialised, then initValue.
  • currentValue: Current array value.
  • currentIndex: Current array value index.
  • arr: The array object the current element belongs to
  • initValue: Starting value.