Anonymous Functions
Anonymous Functions
Section titled “Anonymous Functions”Introduction
Section titled “Introduction”Anonymous functions are functions without a name. They are used as arguments to other functions or assigned to variables.
Example
Section titled “Example”document.addEventListener('click', function() { console.log('Clicked!');});// As callbacks[1, 2, 3].map(function(x) { return x * 2; });
// In IIFE(function() { console.log('Runs immediately');})();
// In event handlersbutton.onclick = function() { alert('Hi!'); };Anonymous vs Named
Section titled “Anonymous vs Named”// Anonymous — stack trace shows 'anonymous'setTimeout(function() { }, 100);
// Named — stack trace shows 'myCallback'setTimeout(function myCallback() { }, 100);Summary
Section titled “Summary”- Functions without a name
- Common as callbacks and IIFEs
- Consider named expressions for better debugging