
Callbacks in JavaScript: Why They Exist
In JavaScript function are treated as values just like normal (numbers , string and arrays etc). That means you can : 1. You can store a function in a variable. 2. You can pass it as an argument to another function. 3. You can return a function from another function. What is Callback? : A callback is a function that is passed to another function as an argument and is executed later. It is used to delay the execution of a function. function greet ( name , callback ) { console . log ( " Hello " + name ); callback (); // calling the callback } function sayBye () { console . log ( " Bye " ); } greet ( " John " , sayBye ); Output : Hello John Bye Why callbacks are used in asynchronous programming : Callbacks are used to delay the execution of a function. Scenario: Food Order System : You order food and it takes time to prepare. You give phone number -> call me when ready (callback). Code Example : function orderFood ( callback ) { console . log ( " Order placed... " ); setTimeout ( function
Continue reading on Dev.to Webdev
Opens in a new tab




