week 3

functions and an introduction to higher-order functions
Functions Review
Introduction to Higher Order Functions
Overview


Functions
function declaration, function expression and Anonymous Functions

function declaration
function square (x) {
return x * x;
};A Function Declaration defines a named function without requiring var keyword

function expression
var square = function (x) {
return x * x;
};A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment )

Anonymous Functions
function (num1, num2) {
return num1 + num2;
};The function name. Can be omitted, in which case the function is anonymous.

Anonymous Functions
(function (num1, num2) {
return num1 + num2;
})();Invocation: wrap your function in an IIFE (immediately invoked function EXPRESSION)

Anonymous Functions
(function (num1, num2) {
return num1 + num2;
})();Usage: anonymous functions can only be called once

Anonymous Functions
(function (num1, num2) {
return num1 + num2;
})();Would this ever be helpful?

Higher Order Functions
Definition:
A function that takes another function
in as a PARAMETER
The function passed in as a parameter is called a CALLBACK

Higher Order Functions
each
//loops through an array
//and invokes a callback on each element
function each (arr, callback){
for(var i = 0: i < arr.length; i++){
callback(arr[i]);
}
};
Higher Order Functions
Example: each
function each (arr, callback){
for (var i = 0; i < arr.length; i++){
callback(arr[i]);
}
};
// prints an element to the console
var print = function(element){
console.log(element);
};
Higher Order Functions
Identifying the Callback
var arr = ['hi', 'my', 'name', 'is', 'albrey'];
each(arr, print);
// hi
// my
// name
// is
// albreycallback!
higher order function

Higher Order Functions
Converting to an Anonymous Function
var arr = ['hi', 'my', 'name', 'is', 'albrey'];
each(arr, function(element) {
console.log(element);
});
// hi
// my
// name
// is
// albreycallback!
higher order function
anonymous functions, intro to HOF and testing
By telegraphprep
anonymous functions, intro to HOF and testing
An introduction to functional programming
- 945