Callback Functions in JavaScript

0.0% Acceptance

In this lab, you'll be working with callback functions in JavaScript. Callback functions are generally functions that are passed as arguments to other functions and executed at a later time, usually after a particular event occurs. These are indispensable in JavaScript for handling asynchronous operations, like working with AJAX or handling user events.

Throughout the lab, you'll learn about the fundamentals of callback functions by creating simple examples and improving your understanding of their usage in practice. The lab consists of the following challenges:

  1. Create a function foo that accepts a callback function as an argument and executes it after a delay using setTimeout.
  2. Create a function bar that will be passed as a callback to foo. bar should display an alert with the message 'Hello, callback!' when it's called.
  3. Modify the foo function to handle a scenario where the callback passed is not a function. It should throw an error with the message 'Callback must be a function'.
  4. Create a custom myForEach function that emulates the behavior of the native JavaScript Array.prototype.forEach method. It should accept an array and a callback function, iterating through each element and invoking the callback with the current element as its argument.
  5. Use myForEach to iterate through an array of numbers and log each number to the console.