Global vs local functions


#1

var totalarea = function(x,y){
var areaofsquare = function(side){return side*side};
console.log(x + y);
};

areaofsquare(6)

I declared my function areaofsquare within the function totalarea. Shouldn't areaofsquare be a local variable only? Why am I allowed to call this outside the function on a global scale? Please and thank you!

Austin


#2

I think this a codecademy special thing:

I try it out in my browser console:

And than changed your code to:

var totalarea = function(x,y){
         var areaofsquare = function(side){
             return side*side
         };
    console.log(areaofsquare(6));
};
totalarea();

Result:


#3

Thank you for clarifying! It happens to work in code academy's sandbox too, but does not work in my console for chrome. I guess it has to do with codeacademy having to be more lenient on scopes for newer people


#4

Where did you test it and where does it work or not work? And what do you define by working and not working everywhere I tested it I got the expected result that @dookoo_de mentioned.


#5

it works in code academy's console/terminal in it's lessons, but does not work in chrome's console. The local variable areaofsquare should not be able to be called outside the function.

In code academy's console, areaofsquare is able to be called outside the function.

In chrome's console areaofsquare is undefined outside the function.

Hope that helped clarify!
Austin


#6

Sry what do you mean by "code academy's console/terminal in it's lessons" I just tried running the code in the exercise "Global vs Local ..." and got the expected error message. Could you mention where you tried it and maybe attach a screenshot? Did you run the code multiple times? Because if you declare a variable and then run a code where it is used undeclared it might still be declared because there was no reset in the mean time.