hiorders

higher-order javascript functions

by jonchius

HTML

<div>

</div>

CSS

@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700');

* { 
  font-family: 'Source Sans Pro', 'Lucida Grande', Verdana;
  background: #fff;
  color: #000;
}

small { 
  font-size: 0.5em;
}

JavaScript

/*
[hiorders]
outlinging higher-order functions (javascript)
concepts go beyond javascript

===============

.map() function 

* takes each element's value of an array
* passes it into an anonymous function argument as a parameter (val, in the case below) 
* returns its processed value (val * 3) into the corresponding element inside a *new* array 
* the old array does not change

*** handy for "transforming" an old array into a new array if we want to change every element of the old array

*/

var beforeMap = [1,2,3,4,5];

var afterMap = beforeMap.map(function(val) {
  return val * 3; 
});

// display in result
$("div").append("<h1>map <small>handy for 'transforming' arrays</small></h1>");
$("div").append("<p><strong>beforeMap</strong>: " + beforeMap.join(" ") + "</p>");
$("div").append("<p><strong>afterMap <em>(all beforeMap values times 3)</em></strong>: " + afterMap.join(" ") + "</p>");

/*

.reduce() function

* takes each element's value of an array ("beforeReduce")
* passes it into an anonymous function argument (function(preVal, currentVal)) 
* performs an operation based on an accumulation (preVal) and its current "focus" value (currentVal)

	e.g. 1*2=2, then 2*3=6, then 6*4=24, then 24*5; 
  
* the old array does not change 

*** handy for "accumulating" operations such as finding a total value of all elements in an array

*/

var beforeReduce = [1, 2, 3, 4, 5];

var afterReduceSum = beforeReduce.reduce(function(preVal, currentVal) {
	return preVal + currentVal;
});

var afterReduceProduct = beforeReduce.reduce(function(preVal, currentVal) { 
	return preVal * currentVal;
});

var afterReduceQuotient = beforeReduce.reduce(function(preVal, currentVal) { 
	return preVal / currentVal;
});

// display in result
$("div").append("<h1>reduce <small>handy for 'accumulating' arrays into single-values</small></h1>");
$("div").append("<p><strong>beforeReduce</strong>: " + beforeReduce.join(" ") + "</p>");
$("div").append("<p><strong>afterReduceSum...