Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Functions Pass Information Into Functions Variable 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
217,573 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.