Callbacks and Functions

Ian McKenzie
2 min readJul 8, 2020

--

In keeping with last week’s topic of breaking down the confusion within code. We are now discussing a subtopic: Callbacks and Promises: What are the differences between these two agents of change in the JavaScript programming language and how they may be useful in coding.

According to the Mozilla Developer Network website, the definition of a callback is one function, utilizing another function as its argument, which is then invoked from the outer function after any given event has occurred. This is what is known as a higher-order function (HOF), which, according to Wikipedia is also known as a First-Class Function, functions that can be passed around as values.

The above example is a synchronous callback, as it is executed immediately.

A more definitive example would be the following, which is an example of an asynchronous callback, which occurs when another event takes place…

In the JavaScript fashion of writing code, it is a standard approach to have an anonymous function — a function that does not have a name — set the action time in motion at the time the function passes through the outer function. In this case, line three directs the function with a setTimeout method request to have its information console.logged out (write a message) to the console at the three-second mark. Note that the callback was executed in 3.2 seconds (see lower left of screenshot), because line three instructed the program to “callback” at that moment.

One of the major drawbacks to using callbacks is what is known as callback hell. This is when a program has multiple asynchronous operations within one program, which results in extremely complex coding situations…

Um…..Nah, no, thank you, no.

Event Listeners are where JavaScript Callbacks shine, in terms of their usefulness, as demonstrated by the example below.

A promise is an object that represents an action that hasn’t finished yet.

s are central in Asynchronous JavaScript

--

--

Ian McKenzie
Ian McKenzie

Written by Ian McKenzie

JavaScript, Python, Django, and React, are beginning to become my friends. Maybe I can introduce them to some other new friends.

No responses yet