Get to know MDN better
The JavaScript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere.
There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope.
Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as "$". Put the <script> element that loads the library before your code that uses it.
The "foo" variable isn't defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work.
A variable needs to be available in the current context of execution. Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function
However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.
This page was last modified on Jul 8, 2025 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.