Global vs Local variables...can´t understand?


#1

Hi brothers!

I cant understand why before solve the exercise the global variable in line 1, dont affect to line 12. I think that at first time line 12 must be seven because there is a GLOBAL VARIABLE in line 1, must affect to all.

Im a little bit lost with these exercise... I know how to resolve but i cant understand it, speciallay why a global variable (line1) dont affect to other lines (line12)

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(7);

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


#2

Both times should be 14. Because the variable on line 1 is global, every part of the program has access to it. Then, inside the function, you update the global variable my_number, if this variable would have been local (var my_number = number * 2), on line 12, 7 will be printed.


#3

Whenever you declare a variable with the var keyword, the variable is declared within its execution context - that is, where (or which scope) the variable is placed.

var my_number = 7; //this has global scope

As you say, this has a global scope as it is in the top layer, meaning it can also be accessed within a function.

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

Now, when you declare a variable without the var keyword (also known as an undeclared variable), it is also created as a global variable. This means that even within the local scope of a function, an undeclared variable is given a global scope.

timesTwo(7);

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

Now when you log my_number to the console, the reason you're getting 14 is because my_number has been redeclared (as a global variable) within the timesTwo() function.

If you change the line inside your function to var my_number = number * 2; you'll get different results because those changes only occur within the local scope of the function.

I hope this helps!


#4

thanks you nedwards it really helps me!