function myFunction() {
alert('hello');
}
myFunction();
// calls the function once
Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.
More complexly put: In JavaScript, functions are objects. Because of this, functions
can take
functions as arguments, and can be returned by other functions.
Functions that do this are called higher-order
functions. Any function that is passed as an argument is called a callback function.
let numbers = [1, 2, 4, 7, 3, 5, 6];
function isOddNumber(number) {
return number % 2;
}
const oddNumbers = numbers.filter(isOddNumber);
console.log(oddNumbers); // [ 1, 7, 3, 5 ]
You are probably clear on this by now, but just in case ... to actually use a function after it has been defined,
you've got to run — or invoke — it. This is done by including the name of the
function in the code somewhere, followed by parentheses.
function myFunction() {
alert('hello');
}
myFunction();
// calls the function once
function doHomework(subject) {
alert(`Starting my ${subject} homework.`);
}
doHomework('math');
// Alerts: Starting my math homework.
JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.
This example will end up displaying "Goodbye":
w3 Function Sequence
function myFirst() {
alert("Hello");
}
function mySecond() {
alert("Goodbye");
}
myFirst();
mySecond();
Synchronous callback functions
If your code executes sequentially from top to bottom, it is synchronous.
The isOddNumber() function is an example of
a synchronous callback function.
In the following example, the arrow function is a callback used in a synchronous function.
The sort() method completes first before the console.log() executes:
let numbers = [1, 2, 4, 7, 3, 5, 6];
numbers.sort((a, b) => a - b);
console.log(numbers); // [ 1, 2, 3, 4, 5, 6, 7 ]
Where callbacks really shine are in asynchronous functions,
where one function has to wait for another function (like waiting for a file to load).
let show = function () {
console.log('Anonymous function');
};
show();
var func = function (param) {
return param;
}
document.body.innerHTML += func("Did I just call a variable? Yep!");
IIFE is instantiated by a set of brackets and invoked by another set of brackets next to it in order to run the function immediately.
immediately invoked function expression
// IIFE
(function(){
const sayHello = 'Hello';
console.log(sayHello);
})();
However, there is another way you can implement an IIFE (shown below). This way was suggested by Douglas Crockford as a more legible choice than the first way. Both of them work in the same manner; so, it’s up to your preference.
(function(greeting){
console.log(greeting);
}('hey'))
Friday November 19 2021 0724 AM
Friday November 05 2021 0753 AM
Friday October 29 2021 0755 AM
Friday October 22 2021 0752 AM
Friday October 08 2021
Friday September 24 2021 0718 AM
Friday September 17 2021