The argument passed to this code here is anonymous function:
[/*some data*/].forEach(
(element) => {/*some code*/} // this line is an anonymous (arrow) function, as it has no name
);
You could use a function
instead of the arrow function and it work basically the same, except a few changes made to scoped objects like this
. You can read more about the differences here. Since we aren’t here to talk about the differences, I wont go into it right now
. I will use arrow functions from here on out tho for consistency.
But this:
(() => {/*code here*/})();
Is a different expression that uses an anonymous function, its called an IIFE or Immediately Invoked Function Expression
The idea behind this is you can declare a function, and instantly run it before going onto other code. You could consider it the same as this:
const myFunc = () => {/*code*/};
myFunc();
This is slightly more verbose, and you have to give the function a name, and call it later.
Other use-cases such as leveraging the function scope are very useful. As you may just want to leverage the fact arrow functions/functions provide their own variable scope, so you can prevent polluting the namespace:
(function () {
var aName = "Barry";
})();
// Variable name is not accessible from the outside scope
aName // throws "Uncaught ReferenceError: aName is not defined"
ref from MDN
Finally, you could utilize this pattern to get async/await
in your “top-level” part of your app, where normally you’d need to utilize .then
like in a nodejs script
(async () => {
await someAsyncFunction();
console.log('done!');
});
Generally an IIFE is more of a “top-level” pattern where you will use it to organize/architect your code, and not something you will see or use nearly as much as anonymous functions.