Callbacks in Javascript

Callbacks in Javascript

Here is a simple javascript function that is designed to print its argument in the console:

var myFunction = function(argument){
  console.log(argument)
}

A function can be called using brackets, the latter containing the argument to be passed:

var a = "Hello world"
myFunction(a)

Which would result in the following console output:

Hello world

Argument can be be of any type, number, string, array, etc, including functions:

var myFunction = function(argument){
  console.log(argument)
}

var myOtherFunction = function(){
  console.log('I am myOtherfunction')
}

myFunction(myOtherFunction)

This would output:

[Function: myOtherFunction]

Since MyOtherFunction is passed as argument to myFunction. argument can be called as a function from within myFunction:

var myFunction = function(argument){
  argument()
}

var myOtherFunction = function(){
  console.log('I am myOtherfunction')
}

myFunction(myOtherFunction)

Which outputs:

I am myOtherFunction

Here, myOtherFunction is called a callback function.

myOtherFunction can be defined directly within the myFunction 's call:

var myFunction = function(argument){
  argument()
}

myFunction(function (){
  console.log('I am myOtherfunction')
})