Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 728
user3210732 Avatar asked Jul 11 '26 06:07

user3210732


1 Answers

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
like image 132
codename44 Avatar answered Jul 14 '26 02:07

codename44



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!