1

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

4
  • 3
    That indeed looks uselessly redundant. Commented Sep 6, 2021 at 5:53
  • 1
    The second one is an IIFE used just to create the function. It doesn’t change the resulting function. Commented Sep 6, 2021 at 5:54
  • Case B is return a function and execute it immediately with IIFE Commented Sep 6, 2021 at 5:55
  • Wanted to make sure that apart from the self-executing purpose, if there was anything else I was missing. Thanks for clarifying the details Commented Sep 6, 2021 at 6:11

1 Answer 1

1

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

Here it is serving no purpose. self executing function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.