An anonymous function is a function without a name (usually stored in a variable or passed as a callback); an arrow function is the shorter ES6 syntax (params) => expression, which also takes this from the surrounding code.
Anonymous functions
// stored in a variable (function expression)
const greet = function (name) {
return "Hello " + name;
};
console.log(greet("Riya")); // Hello Riya
// as a callback
setTimeout(function () {
console.log("Runs after 1 second");
}, 1000);
// immediately invoked function expression (IIFE)
(function () {
console.log("Runs immediately");
})();
Arrow functions (ES6)
const add = (a, b) => a + b; // implicit return
const square = x => x * x; // one parameter, no ()
const sayHi = () => console.log("Hi"); // no parameters
const makeUser = (n, a) => ({ name: n, age: a }); // return object
const nums = [1, 2, 3, 4];
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]
const sum = (a, b) => { // block body needs return
const s = a + b;
return s;
};
Arrow functions and this
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // 'this' is timer (lexical)
}, 1000);
}
};
With a normal function inside setInterval, this would not refer to timer.
Differences to remember: arrow functions have no own this or arguments, cannot be used as constructors with new, and are not suitable as object methods that need their own this. Arrow functions are themselves anonymous; they get a name only through the variable they are assigned to.