Here are 3 code snippet I came up with. Point out which part I got it wrong/right.
function foo(){
var a=1;
console.log(a);
}
var a=2;
function bar(){
var a=3;
console.log(a);
}
foo();
bar();
console.log(a);
Snippet above will give you 1 3 2 as output. Because they execute according to the function declaration and last one is a global variable a
;
function foo(){
var a=1;
console.log(a);
}
var a=2;
function bar(){
var a=3;
}
foo();
bar();
console.log(a);
Code above will give you 1 2 as output cos we did not ask function bar()
to display us anything.
function foo(){
var a=1;
console.log(a);
}
var a=2;
function bar(){
a=3;
}
foo();
bar();
console.log(a);
Then why does this snippet give you the result of 1 3?
Here is what happened as I understand : (because function declaration get hoisted 1st)
function foo(){
var a=1;
console.log(a);
}
function bar(){
a=3;
}
var a=2;
foo();
bar();
console.log(a);
But why the value of a is 3 at the end? What happened?