JavaScript
Anonymous functions — what they are and where they shine
JavaScript
Anonymous functions
An anonymous function is just a function literal with no name of its own. You can write one in two ways:
Classic function expression:
JAVASCRIPT
1const myFunc = function () {2 console.log('Hello');3};
Arrow form (ES6):
JAVASCRIPT
1const myFunc = () => {2 console.log('Hello');3};
Where you'll actually use them
As callbacks:
JAVASCRIPT
1setTimeout(function () {2 console.log('This runs after 2 seconds');3}, 2000);45// Or with arrow syntax6setTimeout(() => {7 console.log('This runs after 2 seconds');8}, 2000);
Inside array methods:
JAVASCRIPT
1const numbers = [1, 2, 3, 4];2const doubled = numbers.map((num) => num * 2);
Attached to events:
JAVASCRIPT
1button.addEventListener('click', function (e) {2 console.log('Button clicked!');3});
As an IIFE (Immediately Invoked Function Expression):
JAVASCRIPT
1(function () {2 let privateVar = "I'm private";3 // code here4})();
IIFEs were the pre-ES6 way of creating a private scope; today you'd usually reach for a module or block scope instead.
Related JavaScript interview topics
Continue with nearby questions from the same topic cluster.
What are callback functions?What are the pros and cons of compiling to JavaScript?What are ES2015 classes and how do they differ from ES5 function constructors?Why are functions first-class objects?What are iterators and generators in JavaScript?What are primitive values and reference values in JavaScript?