-1

I am reading some question where i find this code, it seems to be easy but i can't understand how this function:(function() {} ()) works.

Please help me to understand that how the value of var foo=6 and bar=9 is only consider in bar=bar+foo

<!DOCTYPE html>
<html>
<body>
    <p id="demo"></p>

    <script>
        var foo = 6;
        bar = 10;
        (function () {
            var foo = 5;
            bar = 9;
        }())
        bar = bar + foo;
        document.getElementById("demo").innerHTML = "Final value is " + bar;
    </script>
</body>
</html>
Andreas
  • 21,535
  • 7
  • 47
  • 56
VipinKundal
  • 442
  • 6
  • 14
  • 1
    It is known as IIFE. Read here. http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – Mr_Green Jul 26 '15 at 12:56

2 Answers2

1

That's a mix of some pretty bad variable usage, particularly the use of "undeclared" bar.

Basically, your global scope has 2 variables, foo & bar. At first they're initialized to 6 & 10 respectively. Then, a function is called that declares it own foo variable and sets that to 5. It also sets the global bar to 9. So now the global values are 6 & 9. The sum of these is then 15.

Amit
  • 45,440
  • 9
  • 78
  • 110
0

Since

var foo = 5;

has the var declaration, it's a local variable. The assignment has no effect on the foo variable outside the function. The global variable continues to have the value 6.

bar = 9;

doesn't have a var declaration, so it's just an assignment. Since the variable isn't declared locally within the function, this assigns the global variable, so the global variable now has the value 9.

When you add the two global variables afterward, you get 9 + 6 = 15.

Barmar
  • 741,623
  • 53
  • 500
  • 612