This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Introduction to Functions in JS Forum

View Course » View Exercise

91 points
280af5f5f32e6010fc2b1c96acf7a690?s=140&d=retro
Submitted by
hossluge
over 4 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!


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.

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
Picture
Submitted by
Alex J
over 4 years ago

11 Comments

578fbbbbe92d411b3f000155_559156986 Nitin Kumar over 4 years ago

thnx

513c003ea6f1d4517a0046d1_809760095 Mike H about 4 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?

Picture Mitchell Dyer about 4 years ago

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

51bd4ce152f86372d8017b3d_235142746 Murph Murphy about 4 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.

Picture James Brazil over 3 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!

Picture NYJY85 almost 3 years ago

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

195cab058a7a2d75d6cd33d99a61b0c6?s=140&d=retro drovid almost 3 years ago

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

5539f1a795e378ced9000526_627705406 flaviobarel about 2 years ago

I LOVE SAUSAGES

260d988d8c391d55ed9773bed02c2987?s=140&d=retro swali1 about 2 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

260d988d8c391d55ed9773bed02c2987?s=140&d=retro swali1 about 2 years ago

can somebody please explain nested scopes part

5620c2e186f5529461000667_689552006 Syed Kazmi almost 2 years ago

kn


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

737 points
C3f91a551fee2e4981a64e1628fcb93a?s=140&d=retro
Submitted by
dellanderson
about 4 years ago

5 Comments

D3337f829903d3fa82f706dc50cd8ea1?s=140&d=retro Rungus almost 4 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.

52dab80e8c1ccc5d3e002b14_255071164 Dan Piggott over 3 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).

52adf3a5631fe994650099a1_669008157 SHA2nk_mish over 3 years ago

osm explanatn!

Picture Katherine Copas about 3 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.

53f6a061631fe9ae75001168_215536890 Zombie Priest almost 3 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.


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
Ba5a0ee9179010d4eef40d0ae71b33fb?s=140&d=retro
Submitted by
James Murphy
about 2 years ago

3 Comments

C2593c36088e2c11360f42117feca998?s=140&d=retro w jones about 2 years ago

thanks

56634d0eb6254887090002f3_351170585 MrJLopez almost 2 years ago

THANK YOU

56634d0eb6254887090002f3_351170585 MrJLopez almost 2 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


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
519d58e58fb34624c3001998_77744573
Submitted by
Erik
about 4 years ago


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

the question isn't clear, because they named as mynumber like the same function but it isn't. One is a global fonction (mynumber), 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
52dc518f7c82ca7b50004709_737890467
Submitted by
Pauline Péo
over 3 years ago

2 Comments

54678a6552f863ff3300264a_929757575 MT head almost 3 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

530ce445481961a987f0f4f0ea91c271?s=140&d=retro Dmitruk Sergiy over 2 years ago

Thank you!


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
55cc70c593767642930001b5_171830996
Submitted by
MD Mostofa
almost 2 years ago


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 "mynumber". 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 "mynumber", 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
Fdace654d711b051a3467aeacd62c1cd?s=140&d=retro
Submitted by
preda_ciprian
over 2 years ago

1 Comment

552839b586f552286e0001ba_408808871 Sprint Runner about 2 years ago

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


0 votes

permalink

The first problem of the set is written horribly.

254 points
514d07cec6118e60e9000103_529488515
Submitted by
Todd Smith
about 2 years ago


-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
92d7e3281c24d3927e827dd6d24e5cea?s=140&d=retro
Submitted by
bobo1234567
over 2 years ago


-3 votes

permalink

ALEC

var nameString = function (name) {

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

};

console.log(nameString("Susie"));

90 points
C1fcdbc7ef99ab28b6421b495f5ffe7b?s=140&d=retro
Submitted by
alec ward
over 2 years ago


-3 votes

permalink

var my_number = 7; //this has global scope

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

timesTwo(7);

console.log("Outside the function mynumber is: ");
console.log(my
number);

151 points
F3a633785de766195c1423e839bb0aba?s=140&d=retro
Submitted by
dlawhorn1
over 2 years ago


-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
D2cddb93f97ccb9f48eb9a91c9205f49?s=140&d=retro
Submitted by
nishaira
about 3 years ago


-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
5c378c79f569ee016f8ced6ba41ba9d7?s=140&d=retro
Submitted by
Mugsymo2k
almost 3 years ago


-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 mynumber = number *2" specifies a new value for mynumber within the function - however I don't understand how/why anyone would use "mynumber = number *2" and how that somehow the lack of "var" makes the definition of mynumber be recognized globally (ie - override the previous my_number definition outside of the function).

101 points
52797f90abf82196e3001e9b_997421667
Submitted by
Karen Santos Da Silva
over 3 years ago


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

737 points
C3f91a551fee2e4981a64e1628fcb93a?s=140&d=retro
Submitted by
dellanderson
over 3 years ago

1 Comment

52797f90abf82196e3001e9b_997421667 Karen Santos Da Silva over 3 years ago

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!


-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
F80a19584d5f801c64320fd32f310a84?s=140&d=retro
Submitted by
Scott West
about 4 years ago

2 Comments

528e510080ff3303b0000d2b_550164241 treywhite713 over 3 years ago

it dont work

54fef03795e3784eb6001871_491090970 Kevin Kilic over 2 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'.