aerialmyth
aerialmyth

Reputation: 13

Anonymous functions in Javascript - why the indirection?

I am going through the freecodecamp Javascript bootcamp. While I know the concept of anonymous functions and have extensively used them in C++, I am not able to understand the difference between the following two cases in Javascript:

Case A - This is how I first wrote an anonymous func in Javascript

const stats = {
  max: 56.78,
  min: -0.75
};

const half = (stats) => {
             return (stats.max + stats.min) / 2.0;
};

console.log(half(stats))

Case B - Freecodecamp has been using the following more extensively

const stats = {
  max: 56.78,
  min: -0.75
};

const half = (function() {
         return function half(stats) {
             return (stats.max + stats.min) / 2.0;
   };
})();

console.log(half(stats))

At first I thought this had something to do with recursion but that doesn't look like being the case.

I have tried both and both return the same result and both have the same call signature. Is there something additional about Case B or any use case where this might be required? Overall, how would I read this function? Like, for Case A, I could simply say that half is a function that takes stats as an input and returns some value

Upvotes: 1

Views: 68

Answers (1)

vaira
vaira

Reputation: 2270

Case B function is known as self-invoking/excuting function.

Here it is serving no purpose. self executing function

Upvotes: 1

Related Questions