In general when you are trying to access a variable it looks for the variables in the current scope first.
If nothing is found the its going to try to look for it in its parents scope and it continiues this process until it reaches global scope.
If it found something on its way then it access that variable in that scope If still nothing it found then it throws an ReferenceError
Example :
At first JAVASCRIPT tries to look for x variable in its local scope (inside function) but because x variable is declared outside and js finds nothing in local scope then it tries to look for it in global scope. finds it and then shows the message in the console.