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


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.