javascript callbacks explained code example

Example 1: javascript callback

/*
A callback function is a function passed into another function
as an argument, which is then invoked inside the outer function
to complete some kind of routine or action. 
*/
function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);
// The above example is a synchronous callback, as it is executed immediately.

Example 2: javascript callback

// Create a callback in the probs, in this case we call it 'callback'
function newCallback(callback) {
  callback('This can be any value you want to return')
}

// Do something with callback (in this case, we console log it)
function actionAferCallback (callbackData) {
  console.log(callbackData)
}

// Function that asks for a callback from the newCallback function, then parses the value to actionAferCallback
function requestCallback() {
  newCallback(actionAferCallback)
}

Example 3: what are callbacks

/*
tl;dr: Callbacks are a way to force one function to complete,
before running another. Used for asynchronus programming.
*/

// Consider this example:
  
names = ['Anthony', 'Betty', 'Camie']

function addName(name, callback){
	setTimeout(function(){
    	names.append(name)
      	callback()
    }, 200)
}

function getNames(){
	setTimeout(function(){
    	console.log(names)
    }, 100)
}

addName('Daniel', getNames)
/* 
addName('Daniel', getNames) is saying:
'finish the function addName() BEFORE running the function getNames()'

> 'getNames()' here is the callback

Without the call back in this example, getNames would finish 
before addName. (setTimeout is used to force one function to go slower)

Callbacks are given as arguments to other functions

*/

Example 4: javascript callback function

// Callback Example 1: note, fn=function
/* 
In JavaScript, callback fn is:

- a function based into another functions as an argument to be
	executed LATER
- would be a Synchronous OR Asynchronous callback.
- hint: 

	Synchronous: processing from top to bottom, 
	stop until current code finished.
        
	Asynchronous: no wait, process the next block if there
    
*/

let numbers = [1, 2, 4, 7, 3, 5, 6];

/* To find all the odd numbers in the array, 
you can use the filter() method of the Array object.
- The filter() method creates a new array with the elements that
pass the test implemented by a fn.
- The following test fn returns true if a number is an odd
number:   */


function isOddNumber(number) { //to be the callback fn
    return number % 2;
}

// callback fn passed into another fn by its reference, No ()
const oddNumbers = numbers.filter(isOddNumber);
console.log(oddNumbers); // [ 1, 7, 3, 5 ]