Functions in JavaScript have really changed over the past ten years or so.
Function Declarations
Defining functions using declarations used to be the the usual way of using functions. Declared functions are not executed immediately. They are executed later when they are invoked.
Example
function myfunction(a, b) {
return a * b;
}
myfunction(2, 3);
Anonymous Functions
You can define a function without a name. Such functions are known as anonymous functions.
Example
You can pass an anonymous function as a parameter in another function call.
setTimeout(function() {
alert('hello');
}, 1000);
Function Expressions
You can also define an anonymous function using an expression, and you can store a function expression in a variable. You invoke the function by stating the variable name followed by a set of parenthesis and a semicolon.
Example
var sayhi = function() {
alert('Hello World!');
}
sayhi();
But what problems do function expressions solve? Why were they added to the JavaScript language?
Closures
When you wrap an anonymous function definition in a set of parenthesis, you can invoke it by appending a set of parenthesis to it, followed by a semicolon.
Example
(function() {
alert('foo');
})();
Lambdas
Lambdas provide a shorthand for creating anonymous functions.
Example
An anonymous function with one argument x that returns x + 1.
x => x + 1
Example
As above, but with a function body.
x => {return x + 1}
Example
A two-argument lambda function.
(x, y) => x + y
Example
Same as above, except with a function body.
(x, y) => {return x + y}