Callbacks

Callback Functions

abel sanchez, abel@mit.edu, and john williams, jrw@mit.edu

Callback Pattern

A callback is a function that is passed as an argument to other code. The receiving code is expected to call back (execute) the argument when needed.

var list = [5,8,9,2,7,6,3,1,4];

function callback(list){
	// --- Your Code ---
}

function filter(list,callback){
	// --- Your Code ---
}

var filtered = filter(list, callback);

Filter Callback

Applying a filter creates a new array with all elements that pass your function. The method takes a callback function.

var numbers = [56, 23, 99, 12, 49, 31];

function callback(){
	// --- Your Code ---
}

numbers.filter(callback)

ForEach()

The forEach() method executes a provided function, a callback, once for each array element.

function logArrayElements(element, index, array) {
  // --- Your Code ----
}

// log array contents
[2, 7, 5, 3].forEach(logArrayElements);

THE END