JavaScript: Functions & Functional Programming

function myFunction(inVar){
	return inVar + 1;
}
  • Functions return “undefined” if no explicit return statement
  • Variables can be assigned to a function → let newVar = myFunction; → now newVar(3) returns 4
  • Default parameter values can be assigned: function myFunc(inVar1 = 0, inVar2 = inVar1)
  • Rest Parameters: function myFunc(a, …b) → all parms after first put into array b
  • Spread Parameters are used on calling a function. Contents of array “spread” into individual parameters : myFunc(…myArray) → myFunc( myArray[0], myArray[1]…)

Alternative syntaxes

const myFunc = function(inVar1, inVar2) {return inVar1 + inVar2}
const myFunc = (inVar1, inVar2) => inVar1 + inVar2  // single step – return assumed
const myFunc = (inVar1, inVar2) => {…; return inVar1 + inVar2} // multi-step
const myFunc = inVar1 => inVar1 * 2 // single input var – no brackets needed

Arrow must be on same line as variables otherwise semicolon automatically inserted.

Functional programming

Lets start with an example array.

let myArray = [1,2,3,4];

Take the array and apply some kind of function to each entry:

myArray.map(inVar => inVar + 1);
// → [2,3,4,5], ‘map’ returns the same sized array as input

myArray.forEach(inVar => console.log(inVar) )
// logs each array entry – forEach calls a “consumer” function for each entry, no return

myArray.filter(inVar => inVar % 2 === 0 )
// → [2, 4], filter requires a ‘predicate’ function (which performs some kind of test and returns a boolean) and includes only the items that return true in output

myArray.find(inVar => inVar % 2 === 0 )
// → 2, find also requires a ‘predicate’ function and returns first item to return true

myArray.reduce( (x,y) => x + y )
// → 10, reduce returns a single value. ‘x’ is a ‘running total’ (starting zero) and ‘y’ is each value presented in turn.

Functions can be chained

myArray.map(inVar => inVar + 1)               // [2,3,4,5]
       .map(inVar => inVar + 1)               // [3,4,5,6]
       .filter(inVar => inVar % 2 === 0 )     // [4,6]