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

If addEventListener() is a function then a variable defined inside addEL is available only within that function?

If addEventListener() is a function then a variable defined inside addEventListener is available only within that function? Do global scope apply in this case?

2 Answers

rydavim
rydavim
18,798 Points

JavaScript has function scope, so variables declared within a function become local to that function. A variable declared outside a function would have global scope, and all functions would be able to access it.

// Code here can't use the vorpal variable.
function myFunction() {
  var vorpal = "snicker-snack";
  // Code here can use the vorpal variable.
}

However, if a value is assigned to a variable that has not been declared, it automatically becomes a global variable.

// Code here can use the jabberwocky variable.
function myFunction() {
  jabberwocky = "wonderland";
  // Code here can also use the jabberwocky variable.
}

Hopefully that clears it up, but if you're able to link the specific example you're asking about I can give a more detailed explanation.

Thanks, you are my hero!