Throughout these articles we have been using variables, we know how to create and assign variables, and we know how to pass them around our code. One thing you may not have realized is that functions are variables as well. We can pass functions as values to objects, and we can even pass functions as arguments to other functions. In this article we will learn how to do that using a concept called
At the end of this article, you should be able to:
- understand and implement callbacks.
- use two basic array methods using callbacks.
Learn to understand and implement callbacks.
cb argument variable as your callback, although as always you are free to name them what you please.
createGreeting we have set the parameter
cb to equal whatever was passed in as the second argument. In the above example we see that in the first
createGreeting call, the function
saysHelloToUser was passed as the second argument. This gives us the ability to call
cb (which is equal to the function
saysHelloToUser) within the
- Note: It is important to NOT call your function when you pass it as a callback. For now, you will never want to include parentheses when passing your function as an argument. If you call your function, whatever the function returns will be passed as an argument (usually breaking your code), NOT the function itself.
Learn to use two basic array methods using callbacks.
Now that we know what callbacks are, and how to use them, lets learn about some helpful array methods that utilize callbacks.
More Array Methods
We already know about array methods and used array methods such as
.length. But there are a lot more methods available to us natively on an array. The methods we are going to talk about here are called higher order methods, because they take callbacks as arguments.
.forEach is a built in for loop on every array.
.forEach takes a callback as its only argument, and iterates over every item in the array and calls the callback on it. The callback can take two arguments, the first is the item itself, the second is the index of the item, this argument is optional.
.map is used when we want to change every item in an array in the same way.
.map takes a callback as its only argument. Like the
.forEach method, the callback has the optional arguments item and index. Unlike
.map will return the entire array.