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

Julian Betancourt
Julian Betancourt
11,466 Points

Problem with function form of "use strict"

Hi guys,

I can't access a variable from the console when using the function form of "use strict":

(function() {
  'use strict';
  var addButton = document.getElementById('add');
}());

Now I write addButton in the console and get this error: Uncaught ReferenceError: addButton is not defined

However if I write:

'use strict';
var addButton = document.getElementById('add');

I will be able to access addButton from the console

I've read that the function form is better so I want to use it, but I'm not being able to use it correctly.

What is the problem ? I must be missing something

Thanks!

2 Answers

huckleberry
huckleberry
14,636 Points

This has to do with scope.

When you're running that function, which is a self executing function, you're creating an immediate local scope. Something that developers will often do JUST so they can create a temporary local scope for some purpose of using a once off variable that automatically gets ditched because of the scope. You'll see it get referred to as 'creating a name space' at times.

ANYWAY... you create and immediately run that function, right? Well it's a function, so it creates a local scope and that variable of addButton there only exists inside of that scope and thus, only exists WHEN that function gets run.

You cannot access a local scope variable from the console because the console only has access to things that exist within the global scope. Variables within the local scope of functions actually technically don't even exist until the function gets run anyway so it makes sense that you couldn't access them from the console.

If you were to do a console.log(addButton); in*side* of that function, you'd see that it would print to the console. But you probably already knew that part and were simply confused as to why you couldn't access the ~addButton~ variable via manual means via the console in the browser.

Anyway, that's why. Learn the hell out of the concept of scope as it's ridiculously important and easily causes confusion if you're not firmly aware of how it operates in all of its nuances.

Cheers,

Huck - :sunglasses: