Need help with this

const increment = (function() {
  "use strict";
  return function increment(number, value) {
    return number + value;
  };
}) ();
console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns NaN

What is use of small brackets before ending my increment function.

This is usually referred to as an Immediately Invoked Function Expression (or IIFE). If you were to google that, there’s all sorts of explanations and stuff given, but I’ll try for a short(-ish) description.

So the key part is here:

(function() {
  "use strict"; 
  return function increment(number, value) {
    return number + value;
  };
})();

Because of the trailing parentheses, this is immediately executed. It runs right off, and passes back a return value. That return value is a function, though it could be pretty much anything. In this case, we use a function, which executes immediately, to return a function that we assign to increment.

If I remember right, this has been updated on Github, as it isn’t really necessary in this particular case.

A more common use for this would be to use the IIFE to create an object, and assign that object to a variable. Doing so is usually referred to as the ‘module pattern’, a very common design pattern in javascript. When that happens, what gets passed back to the variable (like increment) would be a means of accessing the inner workings of that object.

It’s confusing, ish, but the short answer is: the trailing parentheses cause the function itself to be immediately executed, and its return value assigned to increment.

1 Like

Thanks, GreatHelp…!