Anonymous function?

Hello, strangers.
I noticed that the function doesn’t have a const/let/var keyword and there’s no identifier. Does that make it an anonymous function?


let a = 8, b = 6;
(() => {
  "use strict";
  // change code below this line
  [a,b] = [b,a];
  // change code above this line
})();
console.log(a); // should be 6
console.log(b); // should be 8

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays

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 :smile:. 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.

1 Like

Thanks! I’ll read up on IIFE.