Local and Global variables

#1

I just copy the script from exercise,

``````var my_number = 7; //this has global scope

var timesTwo = function(number) {
var my_number = number * 2;
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);``````

I cannot distinguish where the local variable and global variable are.
Also, I do not understand why we need to put var before
my_number = number * 2 ;

As far as I have learnt from previous exercise, we can just type the following and the function will run and return 14:

``````var timesTwo = function(number) {
my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);``````

Lesson 10! Global Var vs Local Var (2 variables)
#2

I moved this to a separate topic as it had few to nothing to do with the other topic and is a question on its own.

Well functions have there own scope so inside happens the local stuff like for example the parameter number which only exists in timesTwo and would raise an error if you try to access it from outside and outside is the global stuff like my_number. Therefore when you don't have a var before my_number inside timesTwo then you would access and change this global variable and therefore you see 14 inside of the function and 14 outside of it. One variable that is accessible in two different scopes -> global. Now what happens when you use var before it is that you create another variable in the scope of the function. Now you have 2 one global outside and one local inside and because they share the name you can only reach the local one from within the function. So you cannot get the global variable any longer although it is still global which is called shadowing if you want to google it.

So what happens now is that because you have 2 variables that don't influence each other you get 14 inside of the function and because my_number outside is not influenced by any of this you get 7 outside of it.

That is the whole magic behind this exercise from the coding point it's just adding a var but from the understanding its far from being that trivial.

Hope you can now understand it a little better.