What is a callback function in Javascript?Give an example.
What is a callback function in Javascript?Give an example.
Student
I'm a code enthusiastic final year student pursuing B.Tech in ECE currently in final year and final semester.However, I've done relevant internships as well in the domain of software development and content writing.
A callback function is a type of function that is passed being an argument to other function to get executed after the completition of the first task by main function.
This type of function is used to ensure that other code of another function gets executed only after the completion of the first ever task by main function.
The example code of callback function in Javascript is as follows:
Here in the above example, the doHomework() function is used to take two arguments: subject for which a string is used to represent the subject of the homework function and callback refers to a function which will get executed only after the finishing of homework. Then the doHomework() function logs a specific message to console to indicate that it starts the homework and after the execution of homework then the callback function gets executed.
After the execution as starting of homework when the callback function gets executed then the output of the program will be as follows:
Here the callback function gets executed after the homework function which has completed the task of the logging message to console.The example which is used here can be considered as a basic example of callback function in Javascript.