If variable in not found in current scope, JS engine looks for parent score until it reaches global scope.
Now, in browser if I try below
console.log(someRandomVariable);
// This throws ReferenceError as someRandomVariable is Not found on Global/Window scope.
But when I call it explicitly on window object, it shows undefined.
console.log(window.someRandomVariable)
As per my understanding, the former is also searching on window object only as it's not inside any function scope.
Why is it having 2 different behavior?
console.log(someRandomVariable);
Javascript looks up the someRandomVariable
, can not find it in any scope and throws the exception you are seeing. You are correct in saying that the window scope is searched - but you don't have this variable defined in the window (or any) scope. So it fails.
console.log(window.someRandomVariable)
Javascript looks up the window
variable. It succeeds, then moves on to the someRandomVariable
attribute. This is not defined, and so you get undefined
.
It's probably worth noting that if you attempted to access an attribute of an undefined variable you would also get an error. Ie, try window.someRandomVariable.someRandomVariable
.
The difference is that one is a variable lookup, and the other is an attribute access.