Functions, Callback, and Anonymous Function in JavaScript
This article teaches you what a function is and how it can be implemented in Javascript.
Target Audience
An article for any more new to programming. Anyone trying to learn or explore functions in Javascript. Also, anyone that wants to know the uses of anonymous and callback functions.
Learning Objectives
After reading this article, you will know how to do the following:
- Identify a function in Javascript.
- Create a function in Javascript.
- How to invoke and use a function.
- Three different ways to create a function.
- How to create and use a callback function.
- How to create and use an anonymous function.
This article will improve your knowledge of how to use functions in Javascript. It won't make you become a pro automatically. It takes lots of practice to become one.
Function
A block of code is designed to perform a specific task.
It reduces code duplication and increases code reuse.
You break each section of your code and logic in form of tasks. You Create each function for each logic.
One function serves a task, another function serves another task, as task after task. Therefore, you create a function by using the word function name()
followed by a name and parenthesis. You also execute a function by calling or invoking its name and parenthesis name()
.
Note: “A specific task”, Your function shouldn’t do more than one thing. It makes it cleaner, easy to read, test, and maintained.
The following are 3 ways of writing a function in JavaScript:
- Function Declaration
- Function Expression
- Arrow Function
Function Declaration
A function declaration is a traditional way of writing a function in Javascript. It's an old way of creating function. We start by declaring using the keyword function
, then we write the function name followed by parameters. For example:
// Function declaration
function add(a, b) {
console.log(a + b);
}
// Calling a function
add(2, 3);
Function Expression
A function expression is another way of creating a function in Javascript. It's no different from function declaration. However, You create a variable first and assign an anonymous function to it. For example:
// Function Expression
const add = function (a, b) {
console.log(a + b);
};
// Calling function or invoking a function
add(2, 3);
The above example executes the function using the variable name add
followed by parenthesis.
Arrow Functions
Arrow functions are newly introduced ways to create functions in Javascript ES6 version.
An easy way to create a function. Very short, concise, and readable. You create a variable and assign an opening and closing parenthesis ()
followed by a greater-than >
and equals-to signs =
before the {}
block. For example:
// Single line of code
let add = (a, b) => a + b;
// Or
let print = (data) => {
console.log(data);
};
console.log(add(3, 2)); // 5
print("hello"); // hello
Anonymous
An anonymous function has no name. It's doesn't stand on it own. This function is mostly passed as a parameter or assigned to an event.
Here are some quick examples:
// traditional method
function (num) {
return num * 2
}
// new arrow method
(num) => num * 2;
This tutorial uses the arrow method of creating functions in Javascript (params) => params
.
The following are uses of anonymous function:
- Defined inside another function call.
- Stored to a variable.
- Assigned to an event.
Defined inside another function call
For example, The next code sample uses an array.Map() function method. Therefore, maps the following list items of numbers ([1, 2, 3, 4, 5, 6, 7, 8, 9]
multiplying each number in the list by 2.
This array.map()
function is often used in functional programming.
let items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newItems = items.map((num) => num * 2);
console.log(newItems);
// [2, 4, 6, 8, 10, 12, 14, 16, 18]
The sample code above returns an array of each item multiplied by 2
.
The items.map()
function passes an anonymous function (num) => num * 2
as it argument.
The .map
array method iterates through each item in the array. This process creates a new array and applies the condition of the anonymous function (num) => num * 2
. This means multiplying each item in the array by 2
then sending it to the new array. And finally, returns a new array.
Another array methods in Javascript that supports this style are array.filter(), array.find(), array.reduce(), array. Etc... You can check Javascript array methods via this link...
Stored to a variable
A variable stores the function like a value. Javascript treats functions like values.
You call the function using the variable name followed by parenthesis name()
.
let printOut = (val) => console.log(val);
printOut("Hello Samuel");
// Hello Samuel
But in this case, an anonymous function is a function without a name. So the above example is not an anonymous function because it's assigned to a variable. But the function itself without a name is an anonymous function.
Assigned to an event
Functions can be assigned to events in Javascript. Functions assigned to events are called event handlers. You create a variable and assigned the event to it.
Here is a quick example:
let handler = () => {
// do something
};
onClick = handler;
Or this could be done directly like this...
onClick = () => {
// do something
};
Callbacks
A callback is a function passed into another function as an argument. Therefore, invoked inside the outer function to complete some kind of routine or action.
Here is a quick example:
function print() {
console.log("hello " + name);
}
function getName(name, callback) {
callback(name);
}
This is a synchronous callback because it’s executed immediately. However, callbacks are often used to continue code execution after an asynchronous operation has been completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a .then()
block chained onto the end of a promise after that promise fulfills or rejects. This structure uses many modern web APIs, such as fetch()
.
A lot of people write codes that run in a synchronous manner. But, because of the nature of Javascript, which is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility. This means it runs one task at a time. It doesn’t get to wait for a request to complete before moving to the next. And finally, it multi-tasks.
The browser engine reads Javascript codes one step at a time. But, don’t wait for a particular thing/request before moving to the next task.
If a supposed API request to another source instead of waiting for the request to return, the browser engine moves to the next tasks, it moves task by task, immediately there is a data returned of the API request sent initially, a function gets triggered.
And that function is a callback()
.
The following example makes a request that lasts for two seconds before returning data.
function printOut(data) {
console.log(data);
}
function fetchData(name, callback) {
setTimeout(
() => callback("hello " + name),
// callback() function
2000
);
}
fetchData("Samuel ", printOut);
// hello Samuel
The printOut()
function is a callback function. This function executes inside the fetchData()
function, after the space of two seconds.
Other options of callback functions in Javascript are the Promises, async, and awaits methods. This is mostly used for an API requests. A callback triggers after the request returns the data.
Conclusion
In conclusion, this article helps you understand functions and how you can implement them in Javascript. As stated above, We have three ways you can create a function in Javascript. And you have learned what anonymous and callback functions are, and their uses. By now, you should be able to create a function that performs a specific task.