- Named functions may be assigned to a variable
function sayHello() { alert('Hello'); }
var x = sayHello;
x(); // Hello
- Anonymous function can also be assigned
var sayHelloAnonymous = function() { alert('Hello'); }
sayHelloAnonymous(); // Hello
var area = function(width, height) { return width * height; }
x = area(2, 3); // 6
- Anonymous function that executes immediately - Immediately Invoked
Function Expression (IIFE)
(function(name) { alert('Hello, ' + name); }('Bob'));
// or
(function(name) { alert('Hello, ' + name); })('Bob');
- Anonymous functions as function arguments
// Register an event listener
my button = document.getElementById('mybutton');
button.addEventListener('click', function() {
alert('Button was clicked');
});
// Loop through an array
var nums = [2, 4, 6, 8];
nums.forEach(function(element, index, array) {
console.log(index + ' = ' + element);
});