I would be so thankful if someone explain what the difference is between this function (function(number, value=1) my way that worked the same as the original one) and the original one in this challenge!
Best of lucks
First of all thanks for a quick reply. Secondly, I mean 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 6 original fcc code) vs const increment = function(number, value){ return number + value; };
It works because it’s exactly the same: one is wrapped in a function that executes immediately [for older browsers? For the benefit of the tests? Not sure] but does nothing and one isn’t
could you please explain the marked empty parentheses? what do they do? because when I removed them gave error. And I couldn’t really understood what their job is.
() is how you execute functions in JavaScript - add(1,2) means “execute the add function using the arguments 1 and 2”. If you remove the parentheses, the outer function is just a function definition, it never gets executed. With them there, the function executes immediately, and the code inside the function runs.
@DanCouper 's answer to this question is correct; however, here I have put my understanding of the self-invoking functions in javascript. The internal function “increment” is the return value of the external (function) “increment”. That is, you can name the internal function any name other than the external function name like below.
const myfunc = function() {
"use strict"
return function anyfunc(number, value=1) {
return number + value;
};
};
console.log(myfunc()(5, 2));
console.log(myfunc()(5));
// You may better understand by this nested function
const func1 = function() {
console.log("Inside of func1");
return function func2() {
console.log("Inside of func2");
return function func3() {
console.log("Inside of func3");
}
}
};
console.log("=== Assigning func1()() to myFunc ===");
const myFunc = func1()();
console.log("=== Invoking myFunc ===");
myFunc();
// You amy achieve the same in this way
console.log("=== Another way ===");
const func11 = (function() {
console.log("Inside of func1");
return function func2() {
console.log("Inside of func2");
return function func3() {
console.log("Inside of func3");
}
}
})()();
console.log("===== Finally =====");
func11();
// The output of the above script will look like as below
// 7
// 6
// === Assigning func1()() to myFunc ===
// Inside of func1
// Inside of func2
// === Invoking myFunc ===
// Inside of func3
// === Another way ===
// Inside of func1
// Inside of func2
// ===== Finally =====
// Inside of func3