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

Piotr Manczak
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Piotr Manczak
Front End Web Development Techdegree Graduate 28,940 Points

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