Reputation: 49
(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
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);
:
foo()
will return undefined
because there's no return
statementa
will return 7
, because we did a=7
;Upvotes: 0
Reputation: 887
You are creating an anonymous function and executing right away (IIFE)
Then, in this scope function :
a
var with value g
a
var.
This foo
function is not called right away.log
statement, foo
is executed :
a
is logged (value g
)a
var in IIFE scope is changed to value 7
foo
returns nothingfoo
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
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