Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

ReferenceError: "x" is not defined

The JavaScript exception "variable is not defined" occurs when there is anon-existent variable referenced somewhere.

Message

ReferenceError: "x" is not defined (V8-based & Firefox)ReferenceError: Can't find variable: x (Safari)

Error type

What went wrong?

There is a non-existent variable referenced somewhere. This variable needs to bedeclared, or you need to make sure it is available in your current script orscope.

Note:When loading a library (such as jQuery), make sure it isloaded before you access library variables, such as "$". Put the<script> element that loads the library before your code that usesit.

Examples

Variable not declared

js
foo.substring(1); // ReferenceError: foo is not defined

The "foo" variable isn't defined anywhere. It needs to be some string, so that theString.prototype.substring() method will work.

js
const foo = "bar";foo.substring(1); // "ar"

Wrong scope

A variable needs to be available in the current context of execution. Variables definedinside afunction cannot beaccessed from anywhere outside the function, because the variable is defined only in thescope of the function

js
function numbers() {  const num1 = 2;  const num2 = 3;  return num1 + num2;}console.log(num1); // ReferenceError num1 is not defined.

However, a function can access all variables and functions defined inside the scope inwhich it is defined. In other words, a function defined in the global scope can accessall variables defined in the global scope.

js
const num1 = 2;const num2 = 3;function numbers() {  return num1 + num2;}console.log(numbers()); // 5

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp