Can any one explain the code of this challenge

Tell us what’s happening:
Can any one explain the code of this challenge - already passed the challenge - but why he put two parenthesis at the end of the function and why he put the function in parenthesis?

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions

It’s an IIFE

1 Like

The pattern is called an Immediately Invoked Function Expression https://developer.mozilla.org/en-US/docs/Glossary/IIFE.

As to why the author chose to use one here, I would speculate it has to do with wanting to have strict mode on. There is a rule in many browsers that would prevent you from enabling strict mode in a function with non simple parameters (value=1 in this case). By nesting the increment function one level down they avoid that issue.

Personally I think it overcomplicates things and it would be better written as:

function increment(number, value = 1) {
    return number + value;
};
1 Like