JavaScript Callbacks, also known as callback functions are functions passed into another one as an argument. This technique normally allows a function to call another function. The callback functions can run after another function has finished depending on how they are called. This is because JavaScript functions are normally executed in the order in which they are being called and not in the sequence they are defined. Let us take an example to illustrate the concept of callbacks.
We need to first of all define the function we are going to be using as our callback function. Consider the lines of code below:
function displayMessage(message){
alert(message);}
This function alerts any message sent to it as an argument. Let’s take for example; I you pass in the string “Hello World”, it is going to alert the message. Let us see how JavaScript does it.
You see the output right? Clean and clear as we earlier expected. Let us proceed in demonstrating the concept of callbacks. We need to define another function and pass this our first function as an argument to our second function. Consider the lines of code below.
function myMessage(){
displayMessage(“I am coding in JavaScript.”);}
The above lines of code makes use of the function “displayMessage( )”. Hence, the function “displayMessage( )” is our callback function since it is being called to action by another function. Let us see how these all play out:
Wow! Take a look at how the code works beautifully. This is so perfect and exciting.
Let us play around with it by using different functions to implement this concept. Consider the following lines of code:
function displayAnswer(ans){
alert(ans);}function add(a,b){sum = a+b;displayAnswer(sum)}add(4,7);
Let us see if our code works…
There you have it. It works.
Now we have come to the end of this lesson. Hope you learnt a lot while going through it? For more lessons, stay tuned, and also, don’t forget to subscribe to our YouTube channel. We are here to provide the best. Wishing you the best, and less bugs as you code.
Comments
Post a Comment
Please do not enter any spam link in the comment box.