How can a function return a function itself, if there is no need to do it ? What are round brackets at end of outer function?

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 6

It looks like it’s done to scope strict mode for some unnecessary reason

if it’s removed, console.log logs entire function on screen instead of result…

Hi again Manav. This is the firs time I heard of strict mode and after a bit of googling I found that it is used for older javascript versions. https://www.w3schools.com/js/js_strict.asp

It says there…

All modern browsers support “use strict” except Internet Explorer 9 and lower:

So it seems to me that unless you are using an older version of javascript, it shouldn’t be required.

1 Like

The last brackets are to immediately call the function that the outer function is returning. Those last brackets are mainly used when returning a function.

The reason why it is useful to return functions is because of the concept of closures. To put it simply, closures are variable environments that a returned functions carries over from an inner execution context to an outer one (i.e. this is special because it goes against the typical scope rules in JS). Here is a link to a summary I made a while back https://drive.google.com/open?id=1GLw4c0LGBiZsO1xE3DfGqTFVGPNR8hnP. I hope it helps.

Use Strict - JS is a “loose language” because it is weakly typed:

  1. You can change the type of the value a variable holds multiple times
  2. When you are comparing values of different type (e.g. string and number), the JS engine implicitly changes one of the types, so that it can compare them.
    Because of those things and some other things, the JS engine rarely throws errors. Use strict makes the language tighter (makes the JS engine impose more rules when interpreting your code)
    @CaraLagumen is correct that use strict is used mostly in older browsers. However, it has its uses even in newer ones.