JavaScript Confusing User-Defined Functions

Thank you for reading my response.

See the code below.

const functionName = (function() {

  return function half(argunments) {

    //some code here
  };

})();

I encountered this type of function a lot of time in my lessons
I am confused about what kind of this function is? Why do we use it? Why is the benefit of using this sort of function over other simple functions that we can use like an arrow function:

const functionName=(arguments)=>{
//function body
}

or:

function functionName(arguments){

//function body
}

Thank you for your response in advance.

In pre-ES6 times people worried about global namespace pollution and this was a very popular way to protect it (with IIFE - Immediately Invoked Function Expressions). Consider this example:

const functionName = (function() {

  return function half(argunments) {

    //some code here
  };

})();

console.log(half) // undefined

There are many other use cases for IIFE and this is definitely something you should look at, but in this particular case I think that was the intention

3 Likes

I’ve been finding them more useful lately as I explore more functional and recursive functions. Here is a recursive function I wrote recently that makes an array an object:

function make_object( array = [], index = 0, object = {} ){
  if( index < array.length ){
    return make_object(array, index + 1, (function(a,i,o){ o[a[i][0]] = a[i][1]; return o; })(array, index, object));
  }

  return object;
};

make_object([
  ['key', 'value']
]); // { key: 'value' }

Here, I found the IIFE useful as it allowed me to pass in and return the modified object value in-place. In similar functions I might have just destructured an array with a new value in place such as return make_object(array, index + 1, [...new_array, 'new_value']);, but I could not do that with an object return make_object(array, index + 1, { object, array[index][0]: array[index][1] });; And I did not want to have to write it out as:

  object[array[index][0]] = array[index][1];
  return make_object(array, index + 1, object);

So this is a personal instance I found them useful and continue to find them useful. @snigo proivded a better reason for them, I thought I’d only share a real example I had recently.

1 Like

@Emgo-Dev, this would save you couple lines and couple minutes :slight_smile:

2 Likes

Thanks a lot, both of you. I think it does take some time to grab these concepts and I am just a beginner to these things, that why they are teasing me. Btw, thank you for your response. @Emgo-Dev @snigo

1 Like