Skip to content

Instantly share code, notes, and snippets.

@gcrev93
Created December 14, 2020 22:59
Show Gist options
  • Save gcrev93/090d94797958c1f1e4b83f448e55fa90 to your computer and use it in GitHub Desktop.
Save gcrev93/090d94797958c1f1e4b83f448e55fa90 to your computer and use it in GitHub Desktop.

Callback Functions in JavaScript

In this lesson, we are going to cover callback functions in JavaScript and why they may be useful. We will review some basic concepts that will be needed for the proper understanding of callbacks and then transition into the lesson

Concept Reviews

Variables

A variable is a named item used to store data. In JavaScript, variables are not strongly typed. They can be declared and used globally, within a block of code, within a function and passed from to functions.

Common data types that variables hold are:

  1. Strings
  2. Numbers
  3. Booleans
  4. Objects
  5. Arrays
const name = "Gabrielle";
let age = 27;
var favoriteGames = ['Tomb Raider', 'Halo', 'Gears of War']; 

Functions

A function is a block of code created to perform a task. Functions execute when they are called.

const meetAndGreet = (name, age) => {
    return `Hey everyone! I'm ${name} and I am ${age} years old!`
}

They can be called in the global scope or they can be called within another function.

They can be created with parameters and when you call them you pass in arguments.

Arguments passed into functions can be any valid function types such as those we discussed earlier.

Now I question I want to explore is would you consider a function a data type? You can:

  1. Set them as a variable
  2. You can use them as object properties
  3. Store them in arrays
  4. Pass them as arguments to other functions

Just like the other data types. Now ask yourself again are functions a data type?

YES! But lets focus on passing functions as arguments to other functions

Todays Lesson: Callback Functions

Lets start with this code example:

function firstFunction(){
    console.log("I am the first")
}

function secondFunction(){
    console.log("I am the second and I should run after the first")
}

How can you call these functions to be sure they run in the proper order? In most cases, you could simply do this:

function firstFunction(){
    console.log("I am the first")
}

function secondFunction(){
    console.log("I am the second and I should run after the first")
}

firstFunction()
secondFunction()

But now what if the code changed a bit and looked like this:

function firstFunction(){
    console.log("I am the first")
}

function secondFunction(){
    console.log("I am the second and I should run after the first")
}

setTimeout(firstFunction, 2000)
secondFunction()

(Im using the setTimeout to mimic a function that may take awhile to execute!)

How can we be sure that second will ALWAYS execute after the first? We can use a callback function.

What exactly is callback function?: A callback function is a function passed as an argument to another function. The argument can then be called within the function. Lets edit our code to use callbacks

function firstFunction(callback){
   console.log("I am the first")
   callback()
}

function secondFunction(){
    console.log("I am the second and I should run after the first")
}

firstFunction(secondFunction)

Things to note:

  1. A function that takes another function as a parameter is called a high-order function
  2. You can pass parameters to callback functions
  3. Callback functions can be passed as a parameter to arrow functions as well

Now you maybe thinking.. why didnt we just do something like this:

function firstFunction(){
   console.log("I am the first")
   secondFunction()
}

function secondFunction(){
    console.log("I am the second and I should run after the first")
}

firstFunction()

And we absolutely couldve but in cases when your code is running asyncronously or you have a complicated application, this method may not work. Lets look at one final example to tie it all together:

const twoNumberCalculator = (num1, num2, callback) => {
	return callback(num1, num2);
}

const add = (a, b) => {
	return a + b;
}

const divide = (first, second) => {
	return first/second;
}

console.log(twoNumberCalculator(10, 2, add)); // 12

console.log(twoNumberCalculator(10, 2, divide)); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment