10. Global vs. Local Variables. Help me please


#1

So this is the stock code:

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

It wants me to change line 4 to use the var keyword. These are the only instructions it gave. It said that the inner function should equate to 14 once I add the var keyword. I did this, and it came ut to be 7 instead. I also received an error code, "make sure that timesTwo was called correctly with 7 as the argument." This is really frustrating because the instructions did not say anything about altering that part of the function, meaning that it should be correct as is but the program is finding a problem with it. This section also provided a very poor explanation of what I was supposed to do, especially as global and local variable usage is a completely new concept.

Here is the code I tried and that produced the error code:

var my_number = 7; //this has global scope

var timesTwo = function(number) {
    var localVar = 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);

Please, for the love of God, someone help me lol.


#2

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

the var name/identifier stays the same just put var keyword in-front of my_number on line 4. Without var in-front of it, it is in global scope, it gets its value from

var my_number = 7; //this has global scope

If you put the var keyword in front it is in function scope.

I know, this can be difficult to grasp, but you will learn more about scopes in objects.


#3

As @puristaja said, the task here is really that simple add a var to the fourth line. In your code you changed the variable so localVar has the correct value but you print my_number instead. So as said the task is pretty easy, but what is happening is far from being that easy. So take your time and if necessary ask questions.


#5

please don't post the solution, it is against this forums guidelines.


#6

i'll try that code. if it works, then thanks.


#10

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