Javascript Callback function examples
checkAge
function takes in an age
parameter and a callback
function. When the checkAge
function is called with an age and a callback function (allowAccess
), it checks if the age is greater than or equal to 18. If it is, it calls the callback
function with a value of true
, and if it isn't, it calls the callback
function with a value of false
. The allowAccess
function then logs either "Access granted!" or "Access denied!" to the console depending on the value of the isAllowed
parameter.In the example above, the fetchData
function takes in a callback
function. When the fetchData
function is called with a callback function (displayData
), it simulates an asynchronous operation using setTimeout
to wait for 2 seconds before returning an array of data. When the data is returned, the callback
function is called with the data as a parameter. The displayData
function then logs the fetched data to the console.
In the example above, the numbers
array is mapped to a new array of squared numbers using the map
method, which takes in a callback function that is called for each element of the array. The callback function in this case is an anonymous function that takes in a number
parameter and returns the square of that number. The squaredNumbers
variable then contains the new array of squared numbers, which is logged to the console.
I hope these additional examples help you further understand how callback functions can be used in JavaScript.