This forum is now read-only. Please use our new forums! Go to forums
define global and local scope?
when i saw the definitions, i was clueless. can someone please give me a clearer definition of these 2 items? thanks in advance!
Answer 5149ee5c8613d3c2530000a7
Hm, I think what Leng wrote here is pretty clear:
Variables defined outside a function are […] called global variables. Variables defined within a function are local variables.
“Scope” is just a technical term for the parts of your code that have access to a variable.
In the picture below, the scope of the local
variable is highlighted blue – it’s the function where that var was defined. Any code inside that function can access (read and change) this variable. Any code outside it can’t. It’s local, so it’s invisible from outside.
Variables defined in the white area are global. Their scope is the entire script. Which means that you can read and change them anywhere in your code.
Here’s an example of nested scopes:
var g = 100;
function outer() {
var x = 99;
function inner() {
var y = 77;
}
}
Here the code inside the inner
function has access to all three variables. The code inside outer
can only access g
and x
, and the code outside of the outer
function can only see g
.
Put in terms of scope, g
is global, x
is local to outer
(or, equivalently, the scope of x
is the outer
function), and y
is local to inner
(i.e. its scope is inner
).
Answer 51ac0957c59be92fd10016ae
I’m learning too, but here’s how I think about it (someone correct me if I’m wrong):
The inner function has access to all three variables because all three variables exist while the inner function is running.
The reason the outer code cannot access variables inside inner functions is that those functions aren’t running (they don’t exist on the stack or whatever it is called) until these inner functions are called in the code. And then they exist only for the time necessary for the length of time necessary to do their work.
If we assume that the example code is in a ‘main()’ function: While ‘main()’ is running, it’s the only code running. While ‘outer()’ is running, only outer() and the main() code exist. While ‘inner()’ is running, inner(), outer() and the main() code are in memory or running.
The functions finish in the reverse order that they started. Last function to start is first to finish. In other words, as each function terminates, the ‘onion’ is unwrapped the the computer can ‘see’ the original values for X
Even if we were to assume that the computer knew that the innermost variables were going to exist at some time in the future, it would be too confusing to sort out which variables were visible and which were not.
Bottom line: Think of inner functions as being lazy –their default behavior is to use the outermost (global) variable if one exists by the same name. Functions only bother to create a new variable inside if prodded to do so by the “var” keyword, and then this inner function is too tired and worn out from making that new variable to look any further outside for any other variables by the same name. The inner function will just use whatever is closest to it.
For example:
var X = 100;
function outer() {
var X = 99;
function inner() {
var X = 98;
}
}
At the start of the code block above, X === 100 While outer() function is running, a different X === 99 // unless we omit the ‘var’ While inner() function is running, yet another X === 98 // unless we omit the ‘var’ After inner() function finishes, the outer() function sees the second X === 99 After outer() function finishes, the global X === 100
If we had forgotten to use the ‘var’ keyword in either outer() or inner() functions, we would have accidentally (or on purpose) overwritten the value of X in the layer of the function onion immediately outside. That’s called a ‘side effect’.
5 comments
That makes a lot more sense than the lesson on its own, because I struggled to learn what I was supposed to learn without knowing WHY it would be useful.
Thanks for this explanation; I now understand what the ‘var’ keyword in the function is for (it wasn’t clear why we were doing it in the exercise).
osm explanatn!
This is probably the best explanation I have seen for explaining the ‘Logic’ of how the computer is thinking when it is accessing these variables. Kudos to you! :) I’m going to use this explanation in my tutoring sessions.
Good explanation, I believe inner functions work secluded, or in particular, so it matters not to outter functions whatever they’re doing, about being comprehensive.
Answer 553fa8cb76b8fe04f1000489
var my_number = 7; //this has global scope
var timesTwo = function(number) { var mynumber = number * 2; console.log(“Inside the function mynumber is: “); console.log(mynumber); };
timesTwo(7);
console.log(“Outside the function mynumber is: “) console.log(my_number);
Answer 51a675abebe18e8a05001da6
Yes, very nice explanation, but the excercise went a long, long, long way to explain what global and local scope means. It was a very confusing exercise and could have been done in a lot less time. I’m still kind of confused as to what Leng was trying to illustrate..
Answer 52fe01da282ae3aef9001a9f
var my_number = 7; //this has global scope
var timesTwo = function(number) { keyword = number * 2; console.log(“Inside the function my_number is: “); console.log(keyword); };
timesTwo(7);
console.log(“Outside the function my_number is: “) console.log(my_number);
the question isn’t clear, because they named as my_number like the same function but it isn’t. One is a global fonction (my_number), because it’s defined outside of a function -it’s free- and the other is a local function (keyword) because it’s defined and used into the function timesTwo.
Am I right?
Thank you!
2 comments
Instead of mynumber put my_number on the bottom line, i might be wrong, i program for apple using Objective-c and Swift not JavaScript but i am just trying to help so don’t scream at me saying i have done something frightfully wrong
Thank you!
Answer 55d16ed49376760e930002f1
var my_number = 7; //this has global scope
var timesTwo = function(number) { keyword = number * 2; console.log(“Inside the function my_number is: “); console.log(keyword); };
timesTwo(7);
console.log(“Outside the function mynumber is: “) console.log(my_number);
Answer 546b108a52f863f3af0010fb
For me was the same as Karen Santos. Did not get why the results are “inside 14” and “outside 14” when we do not put “var” in front of “my_number”. After a short recap, I saw on lesson 26 from the chapter “Getting started with programming” how easy it is to change the value of a variable already defined. var myAge = “Thirty”; myAge = “Thirty-one”; So in this case the function “timesTwo” actually change the value of the variable “my_number” and that is way we have both results (inside & outside) 14. In case we put “var” in front of “my_number”, even it has the same name as the global one, we practically define a new variable that has a local scope (it does not get outside the function). Only the return value of the function goes outside and that’s why we have in this case the results: “inside 14” - the result of the function timesTwo(7) = 7 * 2 “outside 7” - the value given to the global variable var my_number = 7 This is how I see the logic and if I’m not right please correct me. Hope this helps.
1 comments
Very nice answer. It helped me to understand. I just don’t get where all the negative votes are coming from.
Answer 553c1cb4d3292feb03000334
The first problem of the set is written horribly.
Answer 54e27f3676b8fe071f000bab
var variable=14;
var global=function(number){
var variable = number+1;
console.log(variable);
}
//this is an example of a local variable”variable” as you call it only in the function
global(variable);
//and this is a example of a global variable you can use its value any where
console.log(variable);
//this shouldn’t be an issue anyways since you can solve the problem of this ever happening by simply capitalizing the global s first letter and lower-casing the locals
// ps the console will state 15,14
Answer 54edeb949113cba0a500049e
Answer 54ee0e179113cb0116000d84
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);
Answer 53976374548c35e8b60002ae
Answer 53ea927e631fe9433b00021c
Thankyou for all the useful tips everyone, I struggled on this one but now I understand it and not I feel like a complete idiot not figuring it out sooner.
I was going to post the solution to this comment but I think you learn better when you have to research the problem. Goodluck (>^-^)>
Answer 5277c9cfabf8213384005b4f
What I find very confusing is the line of code we are supposed to change, BEFORE we change it:
var timesTwo = function(number) {
my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
I get that changing it to “var my_number = number *2” specifies a new value for my_number within the function - however I don’t understand how/why anyone would use “my_number = number *2” and how that somehow the lack of “var” makes the definition of my_number be recognized globally (ie - override the previous my_number definition outside of the function).
Answer 527814fdabf821ee94008b6c
I don’t understand how/why anyone would use “mynumber = number *2”
They might not, but the beautiful thing about programming is that it allows the flexibility needed for unique situations where you might want to modify a global variable using a function for example.
how that somehow the lack of “var” makes the definition of mynumber be recognized globally
It’s just a convention, the grammar of the language. There are probably other ways the syntax could have been designed, but that’s just the way the language developers chose. We have to accept it. Personally, I think it is the simplest and most elegant way to clearly minimize confusion, but others might not agree. For example, there could have been a rule that the same variable name ALWAYS referred to the same data and you could never use that name within a function. That would be maximally clear, but it would limit your flexibility in naming things within functions in a large program…You might run out of variable names.
1 comments
Thanks dellanderson - I actually was able to understand it when I moved on to the next lesson that asked us to locally modify the worth of a global value in a for loop - I don’t know why it didn’t click until then!
Answer 51c39f728c1ccc61ac007b71
this might help you to understand if you can see the result of what the global and local variables are doing.
var multiplied = 5
var timesTwo = function(number) {
var multiplied = number * 2;
console.log('function answer, or local variable ' + multiplied);
};
timesTwo(4);
console.log('global variable ' + multiplied);
2 comments
it dont work
I’m learning too, but here’s how I think about it (someone correct me if I’m wrong):
The inner function has access to all three variables because all three variables exist while the inner function is running.
The reason the outer code cannot access variables inside inner functions is that those functions aren’t running (they don’t exist on the stack or whatever it is called) until these inner functions are called in the code. And then they exist only for the time necessary for the length of time necessary to do their work.
If we assume that the example code is in a ‘main()’ function: While ‘main()’ is running, it’s the only code running. While ‘outer()’ is running, only outer() and the main() code exist. While ‘inner()’ is running, inner(), outer() and the main() code are in memory or running.
The functions finish in the reverse order that they started. Last function to start is first to finish. In other words, as each function terminates, the ‘onion’ is unwrapped the the computer can ‘see’ the original values for X
Even if we were to assume that the computer knew that the innermost variables were going to exist at some time in the future, it would be too confusing to sort out which variables were visible and which were not.
Bottom line: Think of inner functions as being lazy –their default behavior is to use the outermost (global) variable if one exists by the same name. Functions only bother to create a new variable inside if prodded to do so by the “var” keyword, and then this inner function is too tired and worn out from making that new variable to look any further outside for any other variables by the same name. The inner function will just use whatever is closest to it.
For example:
var X = 100;
function outer() { var X = 99;
function inner() {
var X = 98;
}
} At the start of the code block above, X === 100 While outer() function is running, a different X === 99 // unless we omit the ‘var’ While inner() function is running, yet another X === 98 // unless we omit the ‘var’ After inner() function finishes, the outer() function sees the second X === 99 After outer() function finishes, the global X === 100
If we had forgotten to use the ‘var’ keyword in either outer() or inner() functions, we would have accidentally (or on purpose) overwritten the value of X in the layer of the function onion immediately outside. That’s called a ‘side effect’.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
11 comments
thnx
Very nice and detailed explanation, Alex. It still leaves me with some questions, however. Why can inner access all three variables, but outer can only accesss g and x?
I’m with Mike, I’m confused by that. Wouldn’t functions deeper down the nest have less access?
g is global, and can be accessed by everything on it’s level and below (the whole program). x is local, and since it’s declared in outer, its accessible by everything within outer and below. y is local, and declared in inner, so it’s accessible by everything in inner and below. If there was code in outer after inner was created such as: var sum = x + y; it wouldn’t work, because y isn’t declared in that scope.
Hope that answers your questions Mitchell and Mike.
@Mike @ Mitchell I just started this today, so I may be totally incorrect! I believe it all matters on the perspective, or order, you are viewing the “code” you create. I like to think of the inner most bracket as basically the epicenter of a big explosion(I studied physics in college so I picture an explosion!) and with each additional ‘bracket’, the energy dissipates and since the energy from the ‘explosion’ can not travel backwards, you are unable to view the previous wave/bracket. I hope this helped, and most of all I hope I am correct!
this explanation and James’ analogy has finally made me clearly understand how global and local scopes work. Thank you guys!
PLEASE help me i really want to use a variable i declared inside a function globally, but i dont know how…
I LOVE SAUSAGES
Here’s an example of nested scopes:
`var g = 100;
function outer() { var x = 99;
} Here the code inside the inner function has access to all three variables. The code inside outer can only access g and x, and the code outside of the outer function can only see g.
Put in terms of scope, g is global, x is local to outer (or, equivalently, the scope of x is the outer function), and y is local to inner (i.e. its scope is inner).` im dint understand this part
can somebody please explain nested scopes part
kn