Functions do things. Variables hold values (data).
A function can accept data as arguments. A function can also return data, but does not have to. Consider this function which just adds two numbers together:
function addNumbers(numberA, numberB) {
var total = numberA + numberB;
console.log(total);
}
This is a function which accepts two arguments. Within the function's code block, those arguments' values are assigned to the variables numberA
and numberB
. The function's code creates another variable, total
, and assigns the value of numberA
added to the value of numberB
. The function then calls another function, console.log
, with the value of total
passed in as an argument.
Now, the function can also return values. Let's modify this function a bit:
function addNumbers(numberA, numberB) {
var total = numberA + numberB;
return total;
}
If you were to call this function now, you get back the value of total
. If I were to run this:
console.log(addNumbers(5, 5));
You would see 10
in the console. My number literal values were passed as arguments to addNumbers
. The function did its work and returned to me the value of its total
variable. This value is now passed in as an argument to console.log
.
If that isn't crystal clear yet, then please read other tutorials online before continuing.
Now, in JavaScript functions are just like anything else. You can assign them to variables as well!
var newAddNumbers = addNumbers;
console.log(newAddNumbers(5, 5)); // Also returns 10 in the console
When you type:
function someFunction () {
This is no different than:
var someFunction = function () {
The function itself is assigned to the variable someFunction
. In our original example, the function itself was assigned to addNumbers
. So yes, function is a type just like number, object, boolean, etc.