Global vs Local Help


#1

Hi Guys,

Im supposed to change something on line 4 but im not sure what, tried a few different things but nothing is working:

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

Can anyone help me please?


#2

Just run the code observe the output and then add a var before my_number line 4. Run the code again and observe the change. You should notice a different output and I guess the instruction explains it, if not respond again.


#3

Here are the instructions:

Change line 4 to use the var keyword. Notice that the value of my_number in the function is now 14 and outside the function is 7.

Using my_number without the var keyword refers to the global variable that has already been declared outside the function in line 1. However, if you use the var keyword inside a function, it declares a new local variable that only exists within that function.

And at the moment when I run the code without changing anything both numbers are coming up as 14.

Have no idea what I need to change?


#4

Yes currently they are both 14 because the the stuff inside and outside the function writes to the same variable. The arrows are just to emphasize the change no other purpose pls do not copy them.

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

Now by using var you create a second variable with the same name and therefore you no longer change the variable outside of the function by calculating stuff inside the function and therefore you observe a new output.


#5

Thank you very much!