10. Global vs Local variables


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("Outside the function my_number is: ")

Hello all,
this is the correct code for 10. Global vs Local Variables.
My problem is, that I do not understand it, WHY this is correct, resulting in a big knot in my brain.
its about:
var my_number = number * 2;
So from my current understanding, the global value of my_number is 7.
But then it goes on with = number *2
Why is the 7 from my_number multiplicated with 2 when it says number * 2?
From my current point of view & understanding, my_number * 2 should give the correct result instead of number because the number value at line 9 comes after the function call (and should be something like "unknown" until there & executed?)

I think my issue is that I still dont get the back and forth inside the code, so if anyone could share some light please I would be really thankful.


see what happens when you remove the var key word from this line:

var my_number = number * 2;

then my_number inside the function is global, and my_number gets updated and is 14 outside the function as well, now it is only inside the function

number is just the function parameter, but the point is to prove that the global variable my_number doesn't get updated if my_number is a local variable inside the function


I'm also having a hard time grasping this. Question: how should I think about this?

So far I have...

the global variable var myNumber = 7; which is OUTSIDE the function does not exist b/c it's not referenced INSIDE the function, and therefore the console.log OUTSIDE the function is only gonna print what the function returns?

why would something inside of the function have to be declared for something outside the function to be recognized?

can someone walk me through the step by step logically here on how to think about this?


functions have access to global variable, so your above statement is false.

the trick here is that you have a global variable:

var my_number = 7; //this has global scope

and a local variable:

var my_number = number * 2;

with the same name, but they can exist along side each other


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