10/13 Global vs Local Variables


#1

So in the instructions it says:

"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."

Well I dont see any "my_number" var in the excercise...

I see this:

// Declare multiplied outside the function on line 3.
// This will mean it has global scope.
var multiplied = 29;

var timesTwo = function(number) {

var multiplied = number * 2;

};

timesTwo(4);

// We cant access the variable multipled!
// Do something so line 15 will work!
console.log(multiplied);

I really don't understand whats the answer to this..

Can someone please explain?, thank you...


#2

Are you looking for some thing like this

var multiplied = 29;

var timesTwo = function(number) {
    multiplied = number * 2;
};

timesTwo(4);

// We cant access the variable multipled! 
// Do something so line 15 will work!
console.log(multiplied);

#3
var my_number = 7; //this has global scope

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

This is the code I used, compare the one you had and compare mine. Hopefully it will help.


#4

I don't think posting the code here makes much sense, in the end you just need to insert one var so here it is not about the code but about seeing what the insertion of this little var changes. And that is interesting as it creates 2 variables with the same name which have no other connection and each of them only exists in it scope (or at least is only accessible there).


#5

My code looks like this and it works now. before I was having problem too.
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);


#6

thanks for the tip, bro.