Skip to content

JavaScript ReferenceError

  • by

A ReferenceError in JavaScript is an error that arises when attempting to access a variable or function that is not available. This error can occur due to various reasons such as a typographical error in the variable or function name or accessing a variable or function that is outside the current scope.

There are several reasons why this error can occur, including:

  1. Typographical errors: Misspelling a variable or function name can lead to a ReferenceError when trying to access it.
  2. Variable or function not declared: If a variable or function is not declared before it is accessed, a ReferenceError will be thrown.
  3. Out-of-scope variables or functions: If you try to access a variable or function that is outside the current scope, such as in a nested function or a different module, a ReferenceError can occur.
  4. Using a deleted variable or function: If you try to access a variable or function that has been deleted, a ReferenceError will be thrown.

JavaScript ReferenceError example

Simple example code ReferenceError thrown when referencing a variable that is out of scope:

<!DOCTYPE html>
<html>
<body>
    <script>
    function text() {
            var str = "Hello World";
        return str;
    }

    console.log(str);
    </script>
</body>
</html>

Output:

JavaScript ReferenceError

To Fix it you have to define the str variable in the global scope:

var str = "Hello World";

function text() {
return str;
}

console.log(text());

Catching a ReferenceError

In JavaScript, you can catch a ReferenceError using a try-catch block. The try block contains the code that may throw the ReferenceError, while the catch block handles the error if it occurs.

try {
  console.log(myVar);
} catch (error) {
  console.error('Caught an error:', error);
}

Creating a ReferenceError

try {
  throw new ReferenceError("Hello", "someFile.js", 10);
} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "ReferenceError"
  console.log(e.fileName); // "someFile.js"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // "@Scratchpad/2:2:9\n"
}

To avoid ReferenceErrors, it’s important to ensure that all variables and functions are properly declared and in scope before trying to access them. Additionally, double-checking for typographical errors can help catch any mistakes that could lead to ReferenceErrors.

Do comment if you have any doubts on this Js error topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading