1

from MDN, just wondering why the () around the function, why the extra () after it, and why the var b inside the function doesn't replace the value of the first var b, given it doesn't use the keyword let, which would keep b local to that function, thanks

var a = 1;
var b = 2;

(function() {
  var b = 3;
  a += b;
})();

a; // 4
b; // 2
daveasdf
  • 83
  • 1
  • 12

3 Answers3

0

When you write var b inside a function, the var keyword makes it a local variable. So, var b inside the function is a local variable and var b at the top which is outside the function is in global scope. You can read more about scoping in MDN. Also, the () after the function is called immediate function invocation which means that the function is given a call soon after it is defined. Also, since a inside the function has no var before its declaration, it will take the global a which is 1 and add 3, local variable b's value it.

Araknid
  • 476
  • 4
  • 10
0

The function is simply called immediately. That’s what the last parentheses are for. The extra parentheses around the function declaration are because

function() {
  var b = 3;
  a += b;
}();

would create a syntax error as the function keyword would not be interpreted as an expression here.

and why the var b inside the function doesn't replace the value of the first var b, given it doesn't use the keyword let, which would keep b local to that function,

You may have heard that the special thing about let is that it is block-scoped. That’s true. But var has always been scoped to the function and since the second var b is inside its own function it’s scoped to that function and does not affect the b from the top scope here.

idmean
  • 14,540
  • 9
  • 54
  • 83
0

The template

(function(){})();

Is a template of an anonymous function.
To explain it, let's create a function x() that alerts 'hello':

function x() {
    alert('hello');
}

To call x, we will:

x();

Now, it's clear that if we replace an object's name with it's value, the statememt will stay the same (take for example var k = 5; alert(k); alert(5) - the two alerts are the same because variable's name was replaced with it's value).

In our case, x's value is: function () { alert('hello'); }

So if we replace x with it's value in the statement x(); ->

(function () {
    alert('hello');
})();

And that's the source of the syntax. The result of that will be an immediate call to the specified function. Of course, this syntax works also for functions with parameters and functions with return types.

Yotam Salmon
  • 2,400
  • 22
  • 36