user3210732
user3210732

Reputation: 49

scope in javascript and execution steps

(function() {
            var a = 'g';
            function foo() {
                console.log(a);
                a = 7; //
            }
            console.log(foo(), a);
    }());

Can anybody explain the step by step execution and out put of this code sample. I got the out put as 'g undefined 7'

Upvotes: 3

Views: 86

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

This is an ananymous self-invoked function wich is executed automatically without any call.

And the results/steps of execution are:

  • g is thrown with console.log(a);, because initially we have a="g".

  • undefined 7 is thrown with console.log(foo(), a);:

    1. foo() will return undefined because there's no return statement
    2. and a will return 7, because we did a=7;

Upvotes: 0

codename44
codename44

Reputation: 887

You are creating an anonymous function and executing right away (IIFE)

Then, in this scope function :

  • You declare an a var with value g
  • You declare a function named foo which has visibility on parent function scope (IIFE scope). So it can see the a var. This foofunction is not called right away.
  • In logstatement, foo is executed :
    • a is logged (value g)
    • a var in IIFE scope is changed to value 7
    • foo returns nothing
  • Is then logged :
    • foo returns value which is undefined (no return value)
    • a value, which is 7 after foo is executed.

So you have in your console :

g
undefined 7

Upvotes: 3

WellDone2094
WellDone2094

Reputation: 175

(function() {
    ...
    ...
}());

this is just a way to declare an anonymous function and call it

var a = 'g';
function foo() {
     console.log(a);
     a = 7; //
}
console.log(foo(), a);

here u are declaring a variable a = 'g' in javascript if u declare a variable using the keyword "var" the scope of that variable si the function, that means that inside that function (also in sub function) everyone can use it.

then u are declaring a foo function, the foo function can see the variable a because foo is declared inside the previous function. console.log(a) just print the value of a so it will print 'g' and then change the value of a to 7.

after the declaration u call console.log(foo(), a), this means that u are executing foo and printing the return value of foo that is 'undefined' because there is no return statement, and then printing the value of a that after the execution of foo is become 7.

so the output is:

g
undefined 7

Upvotes: 0

Related Questions