Hoisting in JS and code snippet comparison

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?

In the last example, the var a = 2; declared an a variable globally. Inside the bar function, you assign a the value of 3. Since there is no local declaration of a inside bar, JS looks at the next level up (global scope) and finds a variable a there and then assigns it the value of 3. That is why 3 is printed at the end.

Thanks!!! :grinning: