Functions - patrickcole/learning GitHub Wiki

Functions

  • In JavaScript, functions are objects with the ability to pass data to them via parameters or arguments
  • Inside a function's arguments, a function can be provided to be executed later inside the main function, effectively passing a callback function.

function endOfPrint() {
  console.log("I'm done printing!");
}

function print(callback) {
  callback();
}

print(endOfPrint);

Callback Functions

  • Code is executed top to bottom in JavaScript synchronously
  • Sometimes code will need to be executed asynchronously, and a callback function represents a moment where code might not be called in order from top to bottom.
  • A simple example is using setTimeout:
const message = function() {
  console.log("This message is shown after 3 seconds");
}
 
setTimeout(message, 3000);

The code found in message is not immediately executed. Only after 3000ms or 3 seconds has elapsed, then the console displays the message.

Callback functions can also be anonymous (or not be assigned to a variable):

setTimeout(function() {
  console.log("This message is shown after 3 seconds");
}, 3000);

The console.log statement is only available inside the scope of the setTimeout, nowhere else.

An arrow function can also be used:

setTimeout(() => {
  console.log("This message is shown after 3 seconds");
}, 3000);

Callbacks are essential for responding to Events being triggered on a webpage.

Functions Responding to Events

When an event is triggered, an EventListener can be setup to respond to that event's trigger. Part of setting up an EventListener is to provide a callback function that will be executed when the event is triggered:

const sampleBtn = document.queryselector("#callback-btn");
sampleBtn.addEventListener("click", function() {
  console.log("User has clicked on the button!");
});

Once again, an anonymous function has been provided as the callback for the button being clicked.

A named function can also be used in this example:

const onButtonClicked = (event) => console.log("User has clicked the button");
const sampleBtn = document.queryselector("#callback-btn");
sampleBtn.addEventListener("click", onButtonClicked);

More concise and now this callback function could be applied to other event listeners as it is available in the global scope.


Sources