Global vs Local Variables. Why it works?


#1

Hi, i ve just completed lesson 10, Global vs Local Variables. But don't understand why deleting/adding the "var"_ inside_ the function changes the second number(output)? If it is a Local variable, then, it is not supposed to change anything else

var my_number = 7; //this has global scope

var timesTwo = function(number) {
var my_number = number * 2; <<<--- Why this "var" changes this second number?
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number); <<<--- Why is this part affected by Local variable?

Inside the function my_number is: <<<--- i understand this
14
Outside the function my_number is: <<<--- but don't understand this
7


#2

Great question.
It has to do with scope and you will learn more about it in objects.
It isn't a simple subject and I don't want to leave you scratching your head.

I will try to explain and you tell me how I am doing.

Basically there is a local and global scope. Before you put the var keyword inside the var timesTwo = function(number) {}
my_number variable JS interpreter understand that this is not a new value declaration but a reference and it goes to look up its value, it finds the value outside the function scope/local scope box.

But as soon you but var in front of my_number it is a new variable and it is locked into the function scope, you don't have to access it from outside of the function.

Could I help you?


#3

Thanks! it makes more sense now. I tried what you said, but at this point i am not 100% sure that i will be able to use this in real world situations. This is just a matter of practise, i hope....


#4

Finish this course top it up with angular js and I bet everything will make more sense to you :slightly_smiling: