+ 3

Please explain these JavaScript functions

These have come up in the challenges. I don't know how to google for the information because I don't know what this kind of function is called. There are parentheses around the function. Thanks in advance for explaining these to me. //Example 1 var a = 1; var b = 2; (function() { var b = 3; a += b; })(); alert(a + b); ?Example 2 var x = 5; var x = (function(){ var x = 0; return function (){ return ++x; }(); }()); alert(x);

8th Jun 2019, 2:45 AM
Heather
Heather - avatar
2 Answers
+ 4
It's a function that is called as soon as it is defined. The proper term is "IIFE", or "immediately invoked function expression". Take this piece of code: function f() { return 4; } In javascript, we can also define the same function differently: let f = function() { return 4; }; Now of course we can call `f` and it returns `4`, like so: let x = f(); But instead of going through the trouble of putting the function in a variable, we can do it in one step, like this: let x = function(){ return 4; }(); // x is also 4 here. So we define a function and immediately call it. For clarity we usually add another pair of parentheses like this: let x = (function() { return 4; })(); But they are not strictly necessary.
8th Jun 2019, 2:52 AM
Schindlabua
Schindlabua - avatar
+ 3
Perfect explanation. Thanks so much!
8th Jun 2019, 2:56 AM
Heather
Heather - avatar