// There are several definitions
// Non-anonymous, you name it
function hello() { /* code */ }
// Call as usual
hello()
// The myriad of anonymous functions
// This is actually anonymous
// It is simply stored in a variable
var hello = function() { /* code */ }
// It is called the same way
hello()
// You will usually find them as callbacks
setTimeout(function(){ /* code */ }, 1000)
// jQuery
$('.some-element').each(function(index){ /* code */ })
// Or a self firing-closue
(function(){ /* code */ })()
/*
Anonymous function = a function that doesn't need a name, you only need it for the
purpose of a single callback
*/
// e.g.
const arr = [1,2,3,4]
arr.map(function square(num){
return num * 2
})
// the 'square' function is only used within .map here. So it can be treated as an
// anonymous function. Short hand for an anonymous function can look like this:
arr.map(function(num){
return num * 2
})
// Or using arrow notation it can look like this:
arr.map((num) => {
return num * 2
})
//Anonymous function; It's not assigned to an indentifier
Array.forEach((arguments) => {
//This is an anonymous function
})
function forEach(arguments) {
//This is NOT an anonymous function
}
//! Button Click Event
//! regular function
document.querySelector("button").addEventListener('click', handlClick);
function handlClick() {
alert("I got clicked!")//just to show it works
//what to do when click detected
}
//!anonymous function
document.querySelector("button").addEventListener('click',function handlClick() {
alert("I got clicked!")//just to show it works
//what to do when click detected
});