Объект ReferenceError представляет ошибку, возникающую при обращении к несуществующей переменной.
Синтаксис
new ReferenceError([message[, fileName[, lineNumber]]])
Параметры
message-
Необязательный параметр. Человеко-читаемое описание ошибки
fileName
Non-standard
-
Необязательный параметр. Имя файла, содержащего код, вызвавший исключение
lineNumber
Non-standard
-
Необязательный параметр. Номер строки кода, вызвавшей исключение
Описание
Исключение ReferenceError выбрасывается при попытке обратиться к переменной, которая не была объявлена.
Свойства
ReferenceError.prototype(en-US)-
Позволяет добавлять свойства в объект
ReferenceError.
Методы
Глобальный объект ReferenceError не содержит собственных методов, однако, он наследует некоторые методы из цепочки прототипов.
Экземпляры объекта ReferenceError
Свойства
{{page(‘/ru/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype’, ‘Properties’)}}
Методы
{{page(‘/ru/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype’, ‘Methods’)}}
Примеры
Перехват ReferenceError
try {
var a = undefinedVariable;
} catch (e) {
console.log(e instanceof ReferenceError); // true
console.log(e.message); // "undefinedVariable is not defined"
console.log(e.name); // "ReferenceError"
console.log(e.fileName); // "Scratchpad/1"
console.log(e.lineNumber); // 2
console.log(e.columnNumber); // 6
console.log(e.stack); // "@Scratchpad/2:2:7n"
}
Выбрасывание ReferenceError
try {
throw new ReferenceError('Привет', 'someFile.js', 10);
} catch (e) {
console.log(e instanceof ReferenceError); // true
console.log(e.message); // "Привет"
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:9n"
}
Спецификации
| Specification |
|---|
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-referenceerror |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
The ReferenceError object represents an error when a non-existent variable is referenced.
Syntax
new ReferenceError([message[, fileName[, lineNumber]]])
Parameters
message- Optional. Human-readable description of the error
fileName- Optional. The name of the file containing the code that caused the exception
lineNumber- Optional. The line number of the code that caused the exception
Description
A ReferenceError is thrown when trying to dereference a variable that has not been declared.
Properties
ReferenceError.prototype- Allows the addition of properties to an
ReferenceErrorobject.
Methods
The global ReferenceError contains no methods of its own, however, it does inherit some methods through the prototype chain.
ReferenceError instances
Properties
Methods
Although the ReferenceError prototype object does not contain any methods of its own, ReferenceError instances do inherit some methods through the prototype chain.
Examples
Catching a ReferenceError
try {
var a = undefinedVariable;
} catch (e) {
console.log(e instanceof ReferenceError); // true
console.log(e.message); // "undefinedVariable is not defined"
console.log(e.name); // "ReferenceError"
console.log(e.fileName); // "Scratchpad/1"
console.log(e.lineNumber); // 2
console.log(e.columnNumber); // 6
console.log(e.stack); // "@Scratchpad/2:2:7n"
}
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:9n"
}
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) The definition of ‘ReferenceError’ in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of ‘ReferenceError’ in that specification. |
Standard | |
| ECMAScript Latest Draft (ECMA-262) The definition of ‘ReferenceError’ in that specification. |
Draft |
Browser compatibility
- Desktop
- Mobile
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
See also
ErrorReferenceError.prototype
Document Tags and Contributors
Last updated by:
jameshkramer,
May 18, 2017, 10:16:28 AM
In JavaScript, a reference error is thrown when a code attempts to reference a non-existing variable. In this article, we will dive into the most common types of reference error triggers and how to fix them.
Common Reference Errors
According to JavaScript web docs, there are six different types of reference errors, with variations of each, that may get triggered in our code.This article focuses on five most common reference error examples for new developers.

Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
Undefined variables
Forgetting to define a variable before referencing it may be the most common reference error trigger for new developers. This can also happen if the referenced variable has been commented out.
let firstName = "John" let age = 23 console.log(lastName) // Uncaught ReferenceError: lastName is not defined
let firstName = "John" let lastName = "Smith" let age = 23 console.log(lastName) // returns Smith
Scope
Variables defined inside a function’s scope cannot be accessed outside of it. We can think of scope as laws that govern certain parts of land, let’s say in the United States. A law in the books for the city of San Francisco may not be okay to follow in the city of Miami. Residents of Miami living in Miami must follow Miami laws.
In the function below, we attempt to access the value of a outside of its lexical scope.
function nums() {
numA = 1
numB = 2
return numA + numB
}
console.log(numA);
// Uncaught ReferenceError: numA is not defined
We can fix this by defining our variables in the global scope.
numA = 1
numB = 2
function nums() {
return numA + numB
}
console.log(nums());
// returns 3
Strict Mode
Strict Mode intentionally has a different set of semantics than the regular defaulted, “sloppy mode” JavaScript code. A key thing to remember while coding in strict mode is that it eliminates silent errors by changing them into throw errors. A JavaScript statement will be using strict mode if “use strict”; is invoked before a statement.
function referenceErr(a){
"use strict";
foo = true;
if(a == 0){
return foo
} else {
return !foo
}
}
console.log(referenceErr(1))
// Uncaught ReferenceError: foo is not defined
As JavaScript developers we know to use var, let, or const in order to define a variable, but the above would have been a silent error if strict mode was not invoked.
function referenceErr(a){
"use strict";
let foo = true;
if(a == 0){
return foo
} else {
return !foo
}
}
console.log(referenceErr(1))
// returns false
Redeclarations
Not full understanding how to redeclare variables can also trigger reference errors.
function redeclarations() {
let declare = 1;
if (true) {
let declare = (declare + 1);
}
}
console.log(redeclarations())
// Uncaught ReferenceError: Cannot access 'declare' before initialization
To fix the code above, we must either change “let” to “var” or omit “let” inside our if statement completely.
function redeclarations() {
let declare = 1;
if (true) {
declare = (declare + 1);
}
}
console.log(redeclarations())
Conclusion
In JavaScript a reference error is mainly thrown when a code is attempting to reference a variable that does not exist, but there are many ways we can write our code that may trigger this reference error to be thrown. Making sure the variable referenced is defined and is being called in the correct scope can be an easy fix for the majority of cases for new coders.
The Javascript ReferenceError occurs when referencing a variable that does not exist or has not yet been initialized in the current scope. Reference errors in Javascript are of a few different types, with variations of each, that may get triggered in code. Some of these are discussed below.
What Causes Javascript ReferenceError
The Javascript ReferenceError is thrown when an attempt is made to reference a non-existing or out of scope variable. There are a few types of reference errors in Javascript with different variations of each. Some of these are:
- Undefined variables — Not defining a variable before referencing it is one of the most common triggers for reference errors in Javascript.
- Out of scope variables — Variables defined inside a function’s scope cannot be accessed outside of it. If an attempt is made to reference an out of scope variable, a
ReferenceErroris thrown. - Strict mode — Using strict mode in Javascript can throw a
ReferenceErrorif a variable is not defined using thevar,letorconstkeywords. Here’s an example of such a declaration: foo = true; - Referencing the variable
fooin code would result in aReferenceErrorbeing thrown if using strict mode. The error would not occur if not using strict mode. - Variable redeclarations — Redeclaring variables using the wrong keywords can also throw a
ReferenceError. For example, initially declaring a variable usinglet, and subsequently redeclaring usingletagain throws aReferenceError.
ReferenceError Example
Here’s an example of a Javascript ReferenceError thrown when referencing a variable that is out of scope:
function text() {
var str = "Hello World";
return str;
}
console.log(str);
In the above example, the variable str is defined inside the text() function and referenced outside the function. Since str is defined only in the scope of the function, referencing it from outside the function causes a ReferenceError:
Uncaught ReferenceError: str is not defined
How to Fix ReferenceError
Reference errors in Javascript are mainly thrown when an attempt is made to reference a variable that does not exist or is out of scope. Therefore, in the majority of cases, a ReferenceError can be fixed by making sure that the referenced variable is defined correctly and is being called in the correct scope.
The earlier example can be updated to fix the ReferenceError by defining the str variable in the global scope:
var str = "Hello World";
function text() {
return str;
}
console.log(text());
Since the text() function is defined in the global scope, it can access variables defined in the global scope. Therefore, running the above code produces the correct output as expected:
Hello World
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!
The ReferenceError object represents an error when a variable that doesn’t exist (or hasn’t yet been initialized) in the current scope is referenced.
ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().
Constructor
Instance properties
Examples
Catching a ReferenceError
try { let a = undefinedVariable } catch (e) { console.log(e instanceof ReferenceError) console.log(e.message) console.log(e.name) console.log(e.fileName) console.log(e.lineNumber) console.log(e.columnNumber) console.log(e.stack) }
Creating a ReferenceError
try { throw new ReferenceError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof ReferenceError) console.log(e.message) console.log(e.name) console.log(e.fileName) console.log(e.lineNumber) console.log(e.columnNumber) console.log(e.stack) }
Specifications
Browser compatibility
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
ReferenceError |
1 |
12 |
1 |
5.5 |
5 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |
1.0 |
0.10.0 |
ReferenceError |
1 |
12 |
1 |
5.5 |
5 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |
1.0 |
0.10.0 |
serializable_object |
77 |
79 |
103 [«Version 103 serializable properties: |
No |
64 |
No |
77 |
77 |
103 [«Version 103 serializable properties: |
55 |
No |
12.0 |
No |
No |
See also
Error
JavaScript
-
RangeError
The RangeError object indicates when value is not set of allowed values.
-
RangeError() constructor
The RangeError() constructor creates when value is not in set of allowed values.
-
ReferenceError() constructor
The ReferenceError object represents an when non-existent variable referenced.
-
Reflect
Reflect is a built-in object that provides methods for interceptable JavaScript operations.
Saif Sadiq
Posted On: April 17, 2018
39426 Views
2 Min Read
How does it feel when you go to give a job interview and after reaching the interview location you find out that the company for which you are here doesn’t even exist.
Obviously you got angry and your mind will start throwing negative thoughts.
Exactly same happens with JavaScript too.
When any value is assigned to undeclared variable or assignment without the var keyword or variable is not in your current scope, it might lead to unexpected results and that’s why JavaScript presents a ReferenceError: assignment to undeclared variable "x" in strict mode. And this error causes a problem in execution of functions.
If you’ve begun to try out JavaScript you might have encountered some pretty baffling errors. I know I sure did…
ReferenceError: assignment to undeclared variable “x”
Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.
Code without ‘var’ keyword
|
function foo() { ‘use strict’; bar = true; //variable not declared } foo(); |
What you get after executing above program?? An Error?? 🙁
How do you need to code 🙂
Insert ‘var’ in front of your variable and see your program running
|
function foo() { ‘use strict’; var bar = true; //declared variable here } foo(); |
Likewise there are many scripting factors possible to generate reference error in javascript.
|
ReferenceError: «x» is not defined |
|
ReferenceError: deprecated caller or arguments usage |
|
ReferenceError: can‘t access lexical declaration`X’ before initialization |
|
ReferenceError: reference to undefined property «x» |
|
ReferenceError: invalid assignment left—hand side |
Author’s Profile
Saif Sadiq
Saif Sadiq is a Product Growth specialist at LambdaTest and Growth Marketer.
Got Questions? Drop them on LambdaTest Community. Visit now
Test your websites, web-apps or mobile apps seamlessly with LambdaTest.
- Selenium, Cypress, Playwright & Puppeteer Testing
- Real Devices Cloud
- Native App Testing
- Appium Testing
- Live Interactive Testing
- Smart Visual UI Testing
Book a Demo
Типы ошибок
Последнее обновление: 30.08.2021

В блоке catch мы можем получить информацию об ошибке, которая представляет объект. Все ошибки, которые генерируются интерретатором JavaScript,
предоставляют объект типа Error, который имеет ряд свойств:
-
message: сообщение об ошибке
-
name: тип ошибки
Стоит отметить, что отдельные браузеры поддерживают еще ряд свойств, но их поведение в зависимости от браузера может отличаться:
-
fileName: название файла с кодом JavaScript, где произошла ошибка
-
lineNumber: строка в файле, где произошла ошибка
-
columnNumber: столбец в строке, где произошла ошибка
-
stack: стек ошибки
Получим данные ошибки, например, при вызове несуществующей функции:
try{
callSomeFunc();
}
catch(error){
console.log("Тип ошибки:", error.name);
console.log("Ошибка:", error.message);
}
Консольный вывод:
Тип ошибки: ReferenceError Ошибка: callSomeFunc is not defined
Типы ошибок
Выше мы рассмотрели, что генерируемая интерпретатором ошибка представляет тип Error, однако при вызове несуществующей функции
генерируется ошибка типа ReferenceError. Дело в том, что тип Error представляет общий тип ошибок. В то же время есть конкретные типы ошибок для определенных ситуаций:
-
EvalError: представляет ошибку, которая генерируется при выполнении глобальной функции
eval() -
RangeError: ошибка генерируется, если параметр или переменная, представляют число, которое находится вне некотоого допустимого диапазона
-
ReferenceError: ошибка генерируется при обращении к несуществующей ссылке
-
SyntaxError: представляет ошибку синтаксиса
-
TypeError: ошибка генерируется, если значение переменной или параметра представляют некорректный тип или пр попытке изменить значение, которое нельзя изменять
-
URIError: ошибка генерируется при передаче функциям
encodeURI()иdecodeURI()некорректных значений -
AggregateError: предоставляет ошибку, которая объединяет несколько возникших ошибок
Например, при попытке присвоить константе второй раз значение, генерируется ошибка TypeError:
try{
const num = 9;
num = 7;
}
catch(error){
console.log(error.name); // TypeError
console.log(error.message); // Assignment to constant variable.
}
Применение типов ошибок
При генерации ошибок мы можем использовать встроенные типы ошибок. Например:
class Person{
constructor(name, age){
if(age < 0) throw new Error("Возраст должен быть положительным");
this.name = name;
this.age = age;
}
print(){ console.log(`Name: ${this.name} Age: ${this.age}`);}
}
try{
const tom = new Person("Tom", -45);
tom.print();
}
catch(error){
console.log(error.message); // Возраст должен быть положительным
}
Здесь конструктор класса Person принимает значения для имени и возаста человека. Если передан отрицательный возраст, то генерируем ошибку в виде объекта Error. В качестве параметра в
конструктор Error передается сообщение об ошибке:
if(age < 0) throw new Error("Возраст должен быть положительным");
В итоге при обработке исключения в блоке catch мы сможем получить переданное сообщение об ошибке.
Все остальные типы ошибок в качестве первого параметра в конструкторе также принимают сообщение об ошибке. Так, сгенерируем несколько типов ошибок:
class Person{
constructor(pName, pAge){
const age = parseInt(pAge);
if(isNaN(age)) throw new TypeError("Возраст должен представлять число");
if(age < 0 || age > 120) throw new RangeError("Возраст должен быть больше 0 и меньше 120");
this.name = pName;
this.age = age;
}
print(){ console.log(`Name: ${this.name} Age: ${this.age}`);}
}
Поскольку для возраста можно ередатьне только число, но и вообще какое угодно значение, то вначале мы пытаемся преобразовать это значение в число с помощью
функции parseInt():
const age = parseInt(pAge);
if(isNaN(age)) throw new TypeError("Возраст должен представлять число");
Далее с помощью функции isNaN(age) проверяем, является полученное число числом. Если age — НЕ число, то данная функция возвращает true. Поэтому
генерируется ошибка типа TypeError.
Затем проверяем, что полученное число входит в допустимый диапазон. Если же не входит, генерируем ошибку типа RangeError:
if(age < 0 || age > 120) throw new RangeError("Возраст должен быть больше 0 и меньше 120");
Проверим генерацию исключений:
try{
const tom = new Person("Tom", -45);
}
catch(error){
console.log(error.message); // Возраст должен быть больше 0 и меньше 120
}
try{
const bob = new Person("Bob", "bla bla");
}
catch(error){
console.log(error.message); // Возраст должен представлять число
}
try{
const sam = new Person("Sam", 23);
sam.print(); // Name: Sam Age: 23
}
catch(error){
console.log(error.message);
}
Консольный вывод:
Возраст должен быть больше 0 и меньше 120 Возраст должен представлять число Name: Sam Age: 23
Обработка нескольких типов ошибок
При выполнении одного и то же кода могут генерироваться ошибки разных типов. И иногда бывает необходимо разграничить обработку разных типов.
В этом случае мы можем проверять тип возникшей ошибки. Например, пример выше с классом Person:
class Person{
constructor(pName, pAge){
const age = parseInt(pAge);
if(isNaN(age)) throw new TypeError("Возраст должен представлять число");
if(age < 0 || age > 120) throw new RangeError("Возраст должен быть больше 0 и меньше 120");
this.name = pName;
this.age = age;
}
print(){ console.log(`Name: ${this.name} Age: ${this.age}`);}
}
try{
const tom = new Person("Tom", -45);
const bob = new Person("Bob", "bla bla");
}
catch(error){
if (error instanceof TypeError) {
console.log("Некорректный тип данных.");
} else if (error instanceof RangeError) {
console.log("Недопустимое значение");
}
console.log(error.message);
}
Создание своих типов ошибок
Мы не ограничены встроенными только встроенными типами ошибок и при необходимости можем создавать свои типы ошибок, предназначеные для каких-то конкретных ситуаций.
Например:
class PersonError extends Error {
constructor(value, ...params) {
// остальные параметры передаем в конструктор базового класса
super(...params)
this.name = "PersonError"
this.argument = value;
}
}
class Person{
constructor(pName, pAge){
const age = parseInt(pAge);
if(isNaN(age)) throw new PersonError(pAge, "Возраст должен представлять число");
if(age < 0 || age > 120) throw new PersonError(pAge, "Возраст должен быть больше 0 и меньше 120");
this.name = pName;
this.age = age;
}
print(){ console.log(`Name: ${this.name} Age: ${this.age}`);}
}
try{
//const tom = new Person("Tom", -45);
const bob = new Person("Bob", "bla bla");
}
catch(error){
if (error instanceof PersonError) {
console.log("Ошибка типа Person. Некорректное значение:", error.argument);
}
console.log(error.message);
}
Консольный вывод
Ошибка типа Person. Некорректное значение: bla bla Возраст должен представлять число
Для представления ошибки класса Person здесь определен тип PersonError, который наследуется от класса Error:
class PersonError extends Error {
constructor(value, ...params) {
// остальные параметры передаем в конструктор базового класса
super(...params)
this.name = "PersonError"
this.argument = value;
}
}
В конструкторе мы определяем дополнительное свойство — argument. Оно будет хранить значение, которое вызвало ошибку. С помощью параметра value конструктора
получаем это значение. Кроме того, переопреляем имя типа с помощью свойства this.name.
В классе Person используем этот тип, передавая в конструктор PersonError соответствующие значения:
if(isNaN(age)) throw new PersonError(pAge, "Возраст должен представлять число"); if(age < 0 || age > 120) throw new PersonError(pAge, "Возраст должен быть больше 0 и меньше 120");
Затем при обработки исключения мы можем проверить тип, и если он представляет класс PersonError, то обратиться к его свойству argument:
catch(error){
if (error instanceof PersonError) {
console.log("Ошибка типа Person. Некорректное значение:", error.argument);
}
console.log(error.message);
}
The ReferenceError object represents an error when a variable that doesn’t exist (or hasn’t yet been initialized) in the current scope is referenced.
ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().
Constructor
ReferenceError()-
Creates a new
ReferenceErrorobject.
Instance properties
ReferenceError.prototype.message-
Error message. Inherited from
Error. ReferenceError.prototype.name-
Error name. Inherited from
Error. ReferenceError.prototype.cause-
Error cause. Inherited from
Error. -
ReferenceError.prototype.fileNameNon-standard -
Path to file that raised this error. Inherited from
Error. -
ReferenceError.prototype.lineNumberNon-standard -
Line number in file that raised this error. Inherited from
Error. -
ReferenceError.prototype.columnNumberNon-standard -
Column number in line that raised this error. Inherited from
Error. -
ReferenceError.prototype.stackNon-standard -
Stack trace. Inherited from
Error.
Examples
Catching a ReferenceError
try { let a = undefinedVariable } catch (e) { console.log(e instanceof ReferenceError) console.log(e.message) console.log(e.name) console.log(e.fileName) console.log(e.lineNumber) console.log(e.columnNumber) console.log(e.stack) }
Creating a ReferenceError
try { throw new ReferenceError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof ReferenceError) console.log(e.message) console.log(e.name) console.log(e.fileName) console.log(e.lineNumber) console.log(e.columnNumber) console.log(e.stack) }
Specifications
Browser compatibility
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
ReferenceError |
1 |
12 |
1 |
5.5 |
5 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |
1.0 |
0.10.0 |
ReferenceError |
1 |
12 |
1 |
5.5 |
5 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |
1.0 |
0.10.0 |
serializable_object |
77 |
79 |
103 [«Version 103 serializable properties: |
No |
64 |
No |
77 |
77 |
103 [«Version 103 serializable properties: |
55 |
No |
12.0 |
No |
No |




