Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Functions Pass Information Into Functions Variable Scope

Scope

In this video, we wrote the code below to demonstrate how a function can "reach out"/access the global scope.

// Global scope let person = 'Lee';

function greeting() { // Function scope person = 'Meg'; alert(Hi, ${person}!); }

greeting(); alert(Hi, ${person}!); greeting();

Therefore, I decided to just tinker and do the reverse (example below) in order to see what would happen. I expected an error message from the console indicating that the person variable in the global scope was not declared/defined therefore assignment of 'Lee' to it could not occur. Instead, the code ran normally with the alerts: 'Hi, Meg!', 'Hi, Lee!', and 'Hi, Meg!'. What does this mean for the reach of the global scope when a variable that's declared inside a function shares the same name as a variable not declared/only referenced within the global scope? It seems like the variable within the global scope still has no bearing over the variable declared within the function as expected, but somehow it's operating within the global scope without having been declared.

// Global scope person = 'Lee';

function greeting() { // Function scope let person = 'Meg'; alert(Hi, ${person}!); }

greeting(); alert(Hi, ${person}!); greeting();

1 Answer

Steven Parker
Steven Parker
231,275 Points

In the second example, there are two variables name "person", one is in the global scope (and contains "Lee"), the other is in the function scope (and contains "Meg"). The assignment of the one in the function does not affect the vale of the global one, and the output you see indicates this.