In today's lecture we talked about how functions work. There are a couple of ways to create functions in JavaScript.
Function Declaration works through using the function
keyword and declaring a function with a name:
function add(a, b) {
return a + b;
}
N.B. With function declaration, the entire function is hoisted to the top of the scope in which it's declared. This means we can call a function before it's been declared in code.
Instead of creating a function using just the function
keyword, we can instead create functions by assigning an anonymous function to a variable.
An anonymous function is simply a function without a name.
var add = function(a, b) {
return a + b;
};
Now when we use a function expression, only the var
is hoisted to the top of the scope, this will prevent us from being able to call the function before it's declared as if we do, we'll get an error:
TypeError: add is not a function
In JavaScript, functions are values just like anything else we declare. This means that they can be reassigned or even passed around to other functions.
var add = function(a, b) {
return a + b;
};
console.log(add(2, 2)); // prints 4
// Create another variable and assign it the value of add (the add function)
var anotherAdd = add;
console.log(anotherAdd(4, 4)); // prints 8
There is a difference between add
and add(2, 2)
. In the first example, we are referencing the function directly. In the second example we are actually invoking the function (i.e. executing the function) by using the parentheses to pass arguments to the function.
From the MDN:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
Since functions can be passed around as values, this provides a nice mechanism to allow us to generalize functions and allow the calling function to customize a part of how the function works.
We looked at this today by re-implementing the Array.prototype.forEach
function in JavaScript:
var forEach = function(array, callback) {
// Basic C-style loop
for (var i = 0; i < array.length; i++) {
// Invoking the callback function, passing each value of the array to the function as a parameter.
callback(array[i]);
}
};
var data = [1, 2, 3, 4];
forEach(data, function(val) {
console.log(val);
});
In this simple example we use the forEach
function to handle just the looping requirement, while using the callback to customize what happens with each value.