Matrimony OTT-Platforms Jobs Coupons Business

Javascript Callback function examples

function checkAge(age, callback) {
  if (age >= 18) {
    callback(true);
  } else {
    callback(false);
  }
}

function allowAccess(isAllowed) {
  if (isAllowed) {
    console.log('Access granted!');
  } else {
    console.log('Access denied!');
  }
}

checkAge(21, allowAccess);

In the example above, the 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.


function fetchData(callback) { setTimeout(function() { let data = ['apple', 'banana', 'orange']; callback(data); }, 2000); } function displayData(data) { console.log('Fetched data: ' + data.join(', ')); } fetchData(displayData);

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.



let numbers = [1, 2, 3, 4, 5];

let squaredNumbers = numbers.map(function(number) {
  return number * number;
});

console.log(squaredNumbers);

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.

    Next Post Previous Post
    No Comment
    Add Comment
    comment url
    We detected that you're using an AdBlocker. Please disable it and refresh to continue using our website.
    Ad