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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response