10. Global vs Local Functions: Putting the Var in the Function


#1

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

timesTwo(my_number);

console.log("Outside the function my_number is: ")
console.log(my_number);

so my problem in this code is apparently I am not using the var inside of the function. I have tried putting the var in the function unsuccessfully. How does one do this?


#2

Hi you can find the explanation of that in this discussion


#3

Is it possible to get a little bit more specific answer? I have read this discussion but am still confused on what is wrong...


#4

When you begin the lesson your code should be like that

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

yours not working because you change the number 7 and 2


#5

Still says either way that I am not calling the var in the function


#6

can you post your new code?


#7

I just copied and pasted yours above and tried putting in the original numbers in mine and both give me the same error response


#8

I said that your code should be like that and not that it was the right code so like the instruction aske you.. you should add the var to this variable in the function

my_number = number * 2;

#9

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

so now its telling me to make sure that you called timesTwo correctly with its argument as 7


#10

you should add the var to this variable in the function

my_number = number * 2;

so your code shoudl be like that

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

#11

Ah thank you! I did not think to put it in front of the line :cry::sob::laughing:


#12

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