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

Why does calling window.myVariable get me undefined when the variable hasn't been declared yet?

If I console.log(myVariable) before declaring it, I will get an Uncaught ReferenceError because myVariable is not yet defined. But when I console.log(window.myVariable), I get the value undefined, as if myVariable already has a memory space. What gives? Why don't I get a Uncaught ReferenceError?

1 Answer

Hi Ryan,

I wasn't sure about this myself so I did some research on it.

I came across this blog post which I think explains the results you're getting: https://javascriptweblog.wordpress.com/2010/08/09/variables-vs-properties-in-javascript/

I would have a look at that. In particular, the section "What is a variable?" and the sub-section "hoisting".

From "What is a variable?" 3rd paragraph:

"Already we can see the essential difference emerging. Properties belong to objects; Variables belong to contexts (and context happens to have an object representation – the VariableObject)."

From "hoisting" note 2):

"2) We could have avoided the ReferenceError by simply accessing b by property syntax window.b. When confronted with b without an object qualifier JavaScript assumes we are referencing a variable and so checks its VariableObject (which has no property named b) When an identifier is not found in the VariableObject we get a ReferenceError. Conversely simple property accessors will return the result of a hash lookup on the parent object (in this case the value undefined). More on ReferenceErrors in my next post."

Thanks, Jason! Sounds like good stuff. I'll have a look at it.