JavaScript Callbacks

Paige Miles
1 min readMay 9, 2021

An Intro for Absolute Beginners

Firstly, let's hit a few facts relevant facts about JavaScipt. In JavaScript:

  • JavaScript runs sequentially from top to bottom
  • Functions are objects
  • We can pass objects to other functions as arguments…
  • …and then call the function/argument inside the function to which it was passed. Like so:
function outer(callback) {
callback()
}

So, why?

We can use callbacks to make sure that an outer function doesn’t run until something else happens, in other words: asynchronously. Asynchronous code means that the code doesn’t run sequentially from top to bottom — like usual.

For Example

There is a method in JavaScript called ‘setTimeout,’ which evaluates an expression (calls a function) after a set amount of time has passed.

const eightSecondMessage = function() {
console.log("8 seconds have passed");
}
setTimeout(eightSecondMessage, 8000);

In the above code, the eigthSecondMessage function will be called after 8000 milliseconds have passed. The eightSecondMessage function is a callback function.

--

--

Paige Miles

Full-stack developer. Funny-peculiar. Lover of baking, yoga, and reading (between the lines).