Trying to Comprehend


#1


So, I'm somewhat understanding the point that is trying to be made, but I was under the impression that local variables could not be used outside of their functions. So, why is it that putting or not putting var before my_number within the function on line 4 would have any effect on the last line if the last line is outside the function and is therefore global? Shouldn't the last line be taking from the global variable in line 1 regardless?


https://www.codecademy.com/en/courses/javascript-beginner-en-6LzGd/2/2?curriculum_id=506324b3a7dffd00020bf661


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


#2

if you don't use a var keyword on this line:

var my_number = number * 2;

you would update the global variable my_number. then the my_number inside the function is no longer local, it is global


#3

So what exactly makes it local? The fact that it's within curly braces? I still don't understand why the global variable would be updated if you are typing within local restrictions.


#4

the var keyword makes the variable inside the function local, if you don't use the var keyword the global variable get updated (yes, you can have a global and local variable with the same name)


#5

Interesting and a bit confusing. I guess practice will help me realize this. Thanks!


#6

yes, it is confusing. But you understand?


#7

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