Delete Icon
This forum is now read-only. Please use our new forums at discuss.codecademy.com.
0 points
Submitted by hossluge
8 years ago

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

97 votes

Permalink

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.

alt

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

3117 points
Submitted by Alex J
8 years ago

11 comments

Nitin K 7 years ago

thnx

Mike H 7 years ago

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?

Mitchell Dyer 7 years ago

I’m with Mike, I’m confused by that. Wouldn’t functions deeper down the nest have less access?

Murph Murphy 7 years ago

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.

James Brazil 7 years ago

@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!

NYJY85 6 years ago

this explanation and James’ analogy has finally made me clearly understand how global and local scopes work. Thank you guys!

drovid 6 years ago

PLEASE help me i really want to use a variable i declared inside a function globally, but i dont know how…

flaviobarel 5 years ago

I LOVE SAUSAGES

swali1 5 years ago

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).` im dint understand this part

swali1 5 years ago

can somebody please explain nested scopes part

Syed Kazmi 5 years ago

kn

Answer 51ac0957c59be92fd10016ae

18 votes

Permalink

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

893 points
Submitted by dellanderson
7 years ago

5 comments

Rungus 7 years ago

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.

Dan Piggott 7 years ago

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

SHA2nk_mish 7 years ago

osm explanatn!

Katherine Copas 6 years ago

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.

Zombie Priest 6 years ago

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

9 votes

Permalink

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

91 points
Submitted by James Murphy
5 years ago

3 comments

w jones 5 years ago

thanks

MrJLopez 5 years ago

THANK YOU

MrJLopez 5 years ago

seriously like some kind of twisted riddle I have read multiple explanations and all you have to do is type var before my_number on line 2

Answer 51a675abebe18e8a05001da6

1 vote

Permalink

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

206 points
Submitted by Erik
7 years ago

Answer 52fe01da282ae3aef9001a9f

1 vote

Permalink

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!

508 points
Submitted by Pauline Péo
7 years ago

2 comments

MT head 6 years ago

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

Dmitruk Sergiy 6 years ago

Thank you!

Answer 55d16ed49376760e930002f1

1 vote

Permalink

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

231 points
Submitted by MD Mostofa
5 years ago

Answer 546b108a52f863f3af0010fb

0 votes

Permalink

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.

270 points
Submitted by preda_ciprian
6 years ago

1 comments

Sprint Runner 5 years ago

Very nice answer. It helped me to understand. I just don’t get where all the negative votes are coming from.

Answer 553c1cb4d3292feb03000334

0 votes

Permalink

The first problem of the set is written horribly.

254 points
Submitted by Todd Smith
5 years ago

Answer 54e27f3676b8fe071f000bab

-2 votes

Permalink

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

144 points
Submitted by bobo1234567
6 years ago

Answer 54edeb949113cba0a500049e

-3 votes

Permalink

ALEC

var nameString = function (name) {

return "Hi, I am" + " " + name;

};

console.log(nameString("Susie"));
90 points
Submitted by alec ward
6 years ago

Answer 54ee0e179113cb0116000d84

-3 votes

Permalink

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

151 points
Submitted by dlawhorn1
6 years ago

Answer 53976374548c35e8b60002ae

-4 votes

Permalink

Variables defined outside a function They are called global variables and their scope is global. Variables defined inside a function are local variables.

106 points
Submitted by nishaira
6 years ago

Answer 53ea927e631fe9433b00021c

-4 votes

Permalink

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 (>^-^)>

47 points
Submitted by Mugsymo2k
6 years ago

Answer 5277c9cfabf8213384005b4f

-10 votes

Permalink

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

101 points
7 years ago

Answer 527814fdabf821ee94008b6c

-12 votes

Permalink

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.

893 points
Submitted by dellanderson
7 years ago

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

-19 votes

Permalink

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);
739 points
Submitted by Scott West
7 years ago

2 comments

treywhite713 7 years ago

it dont work

Kevin Kilic 6 years ago

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