Simple callback in javascript

A callback parameter on a Javascript method is essentially passing a reference to the enter function definition into the method so that the method can call that function when it needs to.


//Simple callback in JavaScript

// the function who accepts a function as arguments
function language(name, callback) {
console.log('The language is: ' + name);
callback(name); //the callback function
}

//callback function
var lng = function(lang) {
console.log('You choose: ' + lang);
}

//passing the name and the function callback 🙂
language('JavaScript', lng);


//Another way of doing this is like this:
//the same function as above with the callback in it
function language(name, callback) {
console.log('The language is: ' + name);
callback(name); //the callback function
}

//this time the function is right inside the main function parameter
//same thing different ways of doing it.
language('JavaScript', function(lang)  {
console.log('You choose: ' + lang);
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s