简体   繁体   中英

Global vs. Local in JavaScript example

I'm trying to learn the basics of JavaScript and ran into something I'm not totally 100% about. Here is the code without declaring the my_number variable inside the function:

 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(6); console.log("Outside the function my_number is: ") console.log(my_number); 

This outputs to: Inside the function my_number is: 12 Outside the function my_number is: 12

First, from what I've read if you don't declare your variable inside a function it will take on the value of a global variable of the same name. My guess as to what's happening here is that when the function call passes the number 6 it passed it to the function, does the multiplication and logs the result (12) to the console. Once the function has ended it keeps that value 12 (essentially overwrites the global value?) and logs the number 12 again to the console.

One the other hand, when I declare the variable inside the function, var my_number = number * 2; it work just like I expect it to and prints out 12 Inside the function and uses the global variable 7 for the last line of code.

  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(6); console.log("Outside the function my_number is: ") console.log(my_number); 

Inside the function my_number is: 12

Outside the function my_number is: 7

Am I understanding this correctly or not? Especially the first snippet of code. I'd like to fully grasp this concept before moving on, it seems important to me.

Your understanding seems to be fine, though I'm not sure of the following statement:

Once the function has ended it keeps that value 12 (essentially overwrites the global value?)

This does have nothing to do with the function ending. As there was no local variable with that name in the function, every occurence of my_number referred directly to the global variable, which was written to in the assignment and read from in the logging statement. The timesTwo functin doesn't have its own copy of the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM