The error will be thrown if you're trying to assign a value to an undeclared variable, or access the value of an undeclared variable, or a variable that is declared, but not within the bounds of the available scope.
Note the difference in the last two code box examples, where we're trying to access a property of an object. If the property doesn't exist the value
undefined is returned, as opposed to throwing the
ReferenceError. If you try to access a property of
undefined, as with
TypeError is thrown, (as opposed to a
ReferenceError), as a variable of type
undefined can't have properties.
Declared, but undefined
ReferenceError error message is slightly confusing in that variables without value have the value
undefined, but this isn't the same as "ReferenceError: x is not defined". As mentioned, the
ReferenceError is thrown when an identifier can't be found in available scope. This is not the same as the variable was declared and found in scope, but has a value of undefined, which is perfectly valid, and won't throw the
Perhaps it's clearer to read the
ReferenceError as "x is not declared", rather than "not defined".
If you're facing a
ReferenceError in your code, look to see if it's declared, and if so, if it's within the available scope of your executing code.
If you have any questions or comments or want to connect, you can follow me on Twitter, or sign up to the newsletter in the footer for front-end articles to your inbox 👇