Global vs Local Variables


#1

Hi
Can someone help me understand a little quick easy question. here is the code I need a bit of help understanding. var my_number = 7; //this has global scope

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

timesTwo(8);

console.log("Outside the function my_number is: ")
console.log(my_number);

How does putting in 8 in timesTwo() get used I don't see how it gets linked.


#2

There's a global variable. Yes?

And the function uses that same name.

We don't want the function to modify the global variable, that's not the purpose of the function. So the function should create a local variable that doesn't affect the outside in any way.

The less side effects a function has, the better. If you call a function, add(5, 2) then you'd expect 8 to be returned. It shouldn't also fire off a missile, that's would be a (highly) undesirable side effect.