Var key word


#1

I cannot figure out what im doing wrong here.

Here is the code:

var my_number = 7; //this has global scope

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

Here is the instruction:

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.

I thought changing what was initially "my_Number" on line 4 to "timesTwo" that that would fix it and set the number inside the function to 14, but they both come out to 7. Can anyone tell me what I'm doing wrong and also explain what a "var keyword" is? Thanks in advance.


#2

Hey @brocktikson! You got it messud up in the function. Your suppose to call your parameters inside the function not the function it self...

So instead of your code:

Do this:

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

#3

From the coding point of view this exercise is pretty simple: press reset and add a var here:

my_number = number * 2; //old
var my_number = number * 2; //new

The interesting part here is not about coding but about understanding what is done here. Formally you had one variable my_number in the whole code so changing it inside the function changed it outside of it as well. But by adding a var inside the function you create a second local variable to the function that happens to have the same name. By doing so the other variable with the same name becomes unaccessible from inside the function, which is called shadowing. Therefore changing the variable inside the function has no effect on the variable outside of it. So again this exercise is not about you doing fancy stuff but about looking closely at the results a small var can have.