Global and Local Variables


#1


Exercise 10


In the instructions, it says to add a variable inside the function, but before I did that, I ran the code to see what would come out. It spits out:
Inside the function my_number is:
14
Outside the function my_number is:
14

I understand why the inside of the function number is 14, but I don't get why the outside of function number is 14. Since "var my_number = 7;" is a global variable, shouldn't the outside of the function number be 7? It looks like its pulling the number 14 from inside the function. Is "my_number = number * 2;" from inside the function replacing "var my_number = 7;" from outside the function? I read from another thread saying that writing a variable without the "var" turns it into a global variable. I just wanted to confirm this if it is true.


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

here:

my_number = number * 2

this will update the global my_number variable. If you want my_number to be local in the function you have to use var keyword:

var my_number = number * 2;

and yes, functions can update global variable, and yes, you can have a global and local variable with the same name


#3

Thank you!!! Now it makes more sense.


#4

more sense or completely?


#5

So the my_number = number * 2; replaces the previous global variable which is why the outside the function number equals 14. But if we declare a var inside the function, it'll only be usable within the function (local variable) and not replace the already existing global variable. Hopefully that's correct. :grinning:


#6

i would prefer to use the word update or re-assign not replace. But yes, you are right :slight_smile: Seems you understand perfectly now, well done :slight_smile:


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.