Not understand the syntax of JavaScript

Not understand the syntax of JavaScript
0.0 0

#1

Tell us what’s happening:
I didn’t understand the syntax here. There are two increment here. The const increment seems to be a function pointer. But the second increment is another function. It seems redundant to me. Also, why there is a () at the end of line 6?

The same code in the following do the same thing. Why not do it this way? (I’m more comfortable with the syntax of Java).

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

console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns NaN

Your code so far


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

Your browser information:

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

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


#2

I assume it needed to be written this way, so the tests behind-the-scenes could validate you used a default value for value.


#3

It seems they may have had to wrap the inner function in a new closure for the sake of “use strict”, but I’m not certain.

The structure here is called an IIFE - Immediately Invoked Function Expression. It is covered in another lesson: Understaand the Immediately Invoked Function Expression (IIFE)


#4

IIFE just means the bit inside the 1st brackets, function, is executed immediately!
( function() {does something} )();

You recognise it by the other brackets at the end. They can have a value to pass to the IIFE inside.
The IIFE is a good pattern because it’s “used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function” (IIFE in wikipedia).

So you don’t HAVE to use it but if you did like OP suggests, your function is hoisted (not bad usually, but can get called before it is defined) and you’ve got a global increment that can be changed somewhere else in the code - so I guess they want you to see good habits.

Oh, I see you’re a Java person, which is cool, me also. Functions in JavaScript have their own scope, so the stuff inside is encapsulated. I find JavaScript is a lot less procedural, the order stuff is evaluated in will catch you out!