1 min readMar 22, 2024
The example for so called anonymous functions is not well chosen.
const greetUser = function(name) {
console.log(`Hello, ${name}!`);
}
const fooBar = greetUser;
console.log(greetUser.name); // 'greetUser'
console.log(fooBar.name); // 'greetUser'
In the very moment an unnamed function gets assigned to a variable or constant or even an object’s property this function acquires the name of its assignee (which even works for unnamed class expressions).
// - proofing the statement about unnamed functions assigned
// to object properties acquiring the property's name too.
function createNamedSubClass(className, SuperType = Object) {
return ({
[ className ]: class extends SuperType {
constructor(...args) {
super(...args);
// the extended type's specific implementation.
}
}
})[className];
}
const ObservableType = createNamedSubClass('ObservableType', EventTarget);
console.log(ObservableType.name); // 'ObservableType';
A much better example was the usage of an unnamed function expression as another method’s/function’s callback …
// filtering even number values ...
[1, 2, 3, 4, 5, 6].filter(function (value) { return !(value % 2); });
// ... [2, 4, 6]
… but then again, this it what arrow functions are perfectly suited for …
// filtering odd number values ...
[1, 2, 3, 4, 5, 6].filter(value => !!(value % 2));
// ... [1, 3, 5]