Ошибки TypeError появляются, когда разработчики пытаются выполнить операцию с неправильным типом данных. Давайте разберём несколько примеров: почему появилась ошибка и как её исправить.
TypeError: Cannot read properties of null/undefined
Что означает: вы пытаетесь обратиться к свойству объекта, который имеет значение null или undefined.
Пример: объявим переменную, но не присвоим ей значение. Если вызовем метод toUpperCase() или любой другой на такой переменной, появится ошибка TypeError:
let name;
name.toUpperCase(); // TypeError: Cannot read property 'toUpperCase' of undefined
Что делать: проверить значение переменной, которую вы используете.
TypeError: Cannot convert undefined/null to object
Что означает: вы используете null или undefined в качестве объекта.
Пример: попробуем использовать функцию Object.keys(), чтобы получить массив ключей объекта obj. Но так как переменная obj имеет значение undefined и не является массивом, возникнет ошибка TypeError:
let obj = undefined;
let result = Object.keys(obj); // TypeError: Cannot convert undefined to object
Что делать: убедитесь, что вы не используете переменную со значением null или undefined. Проверьте, что вы присваиваете правильное значение объекту, или используйте условные операторы, чтобы избежать использования null или undefined в неподходящих местах.
TypeError: x is not a function
Что означает: вы неправильно использовали функцию или передали неверные аргументы.
Пример: попытаемся вызвать переменную numbers как функцию. Но так как это обычный массив, мы получим TypeError:
const numbers = [1, 2, 3];
numbers(); // TypeError: numbers is not a function
Что делать: убедитесь, что переменная является функцией или методом объекта. Проверьте, правильно ли объявлена функция или правильно ли вы вызываете метод объекта.
TypeError: x is not iterable
Что означает: вы пытаетесь выполнить итерацию (например, с помощью цикла for...of) по значению, которое не является итерируемым (например, массивом или строкой).
👉 Итерация — это повторное выполнение одного и того же блока кода несколько раз. Самый распространённый способ выполнения итераций в JavaScript — использовать циклы for и while.
Пример: выполним итерацию по значению x. Но так как это число, итерация не может быть выполнена — появится ошибка TypeError:
const x = 123;
for (let item of x) { // TypeError: x is not iterable
console.log(item);
}
Что делать: проверьте тип данных. Возможно, их стоит преобразовать в другой формат.
Как обработать ошибку TypeError. Конструкция try...catch
Ошибки в коде опасны: если их не обработать, интерпретатор не сможет дальше читать код. В результате весь JavaScript, что находится ниже, просто не выполнится.
Чтобы ничего не сломалось, разработчики используют конструкцию try...catch. Она помогает поймать и обработать ошибки и защищает программу от аварийного завершения.
Как использовать конструкцию:
try {
//Место, где может появиться ошибка
let name;
name.toUpperCase(); // TypeError: Cannot read property 'toUpperCase' of undefined
} catch (error) {
// Дополнительные действия для обработки ошибки
console.log("Произошла ошибка:", error.message);
}
Внутри блока try находится код, который может вызвать ошибку. Если что-то пойдёт не так и мы столкнёмся с TypeError, выполнение программы перейдёт в блок catch. Здесь мы можем выполнить любые действия, например, вывести ошибку в консоль или показать пользователю модальное окно с просьбой перезагрузить страницу.
🔥 Конструкция try...catch полезна, когда нужно предусмотреть появление ошибок и добавить альтернативные пути выполнения кода.
Однако конструкция не является универсальным решением для исправления TypeError. Её следует использовать лишь тогда, когда вы знаете, как обработать конкретную ошибку. А чтобы снизить риски появления проблем, следуйте следующим рекомендациям.
Как избежать ошибок типа TypeError
- Перед выполнением операций внимательно проверяйте типы данных переменных.
- Используйте условный оператор
ifдля проверки, определена ли переменная, прежде чем вызывать методы или выполнять операции с ней. - При работе с функциями проверяйте, что передаваемые аргументы имеют правильный тип данных.
- Используйте инструменты разработчика — особенно полезна консоль — чтобы отслеживать и исправлять ошибки типа TypeError.
Следуя этим советам, можно значительно сократить риски появления ошибок TypeError и повысить надёжность и корректность вашего JavaScript-кода.
Материалы по теме
- TypeScript. Зачем он нужен и почему так популярен
- Туториал. Список задач с drag & drop
- 12 полезных книг по JavaScript
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
ТелеграмПодкастБесплатные учебники
Время на прочтение5 мин
Охват и читатели426K
JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!
Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.
Как читать ошибки?
Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.
Типичная ошибка из Chrome выглядит так:
Uncaught TypeError: undefined is not a function
Структура ошибки следующая:
- Uncaught TypeError: эта часть сообщения обычно не особо полезна.
Uncaughtзначит, что ошибка не была перехвачена вcatch, аTypeError— это название ошибки. - undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение
undefinedкак функцию.
Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.
Теперь к самим ошибкам.
Uncaught TypeError: undefined is not a function
Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected
Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:
var foo = undefined;
foo();
Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.
var x = document.getElementByID('foo');
Несуществующие свойства объекта по-умолчанию имеют значение undefined, что приводит к этой ошибке.
Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.
Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.
Uncaught ReferenceError: Invalid left-hand side in assignment
Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’
Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.
Наиболее частый пример этой ошибки — это условие в if:
if(doSomething() = 'somevalue')
В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.
Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this.
Uncaught TypeError: Converting circular structure to JSON
Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported
Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify.
var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);
Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.
Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.
Unexpected token ;
Связанные ошибки: Expected ), missing ) after argument list
Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.
Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected {” или что-то еще.
Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.
Ошибка с [ ] { } ( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.
Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.
Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.
Uncaught SyntaxError: Unexpected token ILLEGAL
Связанные ошибки: Unterminated String Literal, Invalid Line Terminator
В строковом литерале пропущена закрывающая кавычка.
Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.
Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined
Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference
Попытка прочитать null или undefined так, как будто это объект. Например:
var someVal = null;
console.log(someVal.foo);
Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.
Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined
Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference
Попытка записать null или undefined так, как будто это объект. Например:
var someVal = null;
someVal.foo = 1;
Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.
Uncaught RangeError: Maximum call stack size exceeded
Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow
Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.
Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.
Uncaught URIError: URI malformed
Связанные ошибки: URIError: malformed URI sequence
Вызвано некорректным вызовом decodeURIComponent.
Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.
XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource
Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url
Эта проблема всегда связана с использованием XMLHttpRequest.
Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Связанные ошибки: InvalidStateError, DOMException code 11
Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.
var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');
В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open.
Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open).
Заключение
JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.
Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.
P.S. Этот перевод можно улучшить, отправив PR здесь.
Last Updated : 5 Aug, 2025
When working with JavaScript, you may encounter the error message «Cannot read property ‘click’ of null.» This error typically occurs when you try to access a property or call a method on an object that is null or undefined. This error is common when dealing with the DOM elements and event handlers in web development. In this article, we will explore the common causes of this error and provide solutions to fix it.
These are the following topics that we are going to discuss:
Table of Content
- Understanding the Error
- Identifying the Cause
- Implementing the Fix
- Common Issues and Solutions
- Best Practices
Understanding the Error
The error message «Cannot read property ‘click’ of null» indicates that you are trying to access the click property of the variable that is «null». This typically happens when trying to refer to a DOM element that does not exist or has not been properly initialized.
Identifying the Cause
To identify the cause of the error we need to the examine the code that is throwing the error. Look for any instances where you are accessing the click property of the variable or element.
Implementing the Fix
There are some common solutions to fix the «Cannot read property ‘click’ of the null» error:
Check Element Existence
Before accessing the click property of an element ensure that the element exists in the DOM. We can use methods like document.getElementById() or document.querySelector() to retrieve the element and check if it is null before accessing its properties.
const element = document.getElementById('myButton');
if (element !== null) {
element.click();
} else {
console.error("Element not found");
}
Ensure DOM Content is Loaded
If your JavaScript code is executed before the DOM content has fully loaded we may this error. Ensure that your code is executed after the DOM content has loaded by the wrapping it in the DOMContentLoaded event listener.
document.addEventListener('DOMContentLoaded', function () {
const element = document.getElementById('myButton');
if (element !== null) {
element.click();
} else {
console.error("Element not found");
}
});
Check Variable Initialization
If the variable you are accessing is expected to the contain a DOM element, verify that it has been properly initialized. Check for any typos or errors in the variable names or element IDs.
Example: Consider the following example where we attempt to click a button with the ID myButton.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Error Handling</title> </head> <body> <button id="myButton">Click Me</button> <script> document.addEventListener('DOMContentLoaded', function () { const element = document.getElementById('myButton'); if (element !== null) { element.addEventListener('click', function () { alert('Button was clicked!'); }); element.click(); // Simulate a click event } else { console.error("Element not found"); } }); </script> </body> </html>
Output:
Note: If the button with the ID myButton exists it will be clicked when the page loads. Otherwise, an error message will be logged to the console indicating that the element was not found.
Common Issues and Solutions
- Incorrect Element ID: The Double-check the ID of the element you are trying to the access.
- Asynchronous Operations: If your code relies on the asynchronous operations ensure that the DOM elements are available before accessing them.
Best Practices
- Use descriptive variable names to the avoid confusion and typos.
- Encapsulate your JavaScript code in the functions to the improve readability and maintainability.
- Test your code thoroughly especially when interacting with the DOM.
Conclusion
The «Cannot read property ‘click’ of null» error in JavaScript is often caused by the attempting to the access properties of null or undefined variables. By carefully checking element existence ensuring the DOM content is loaded and verifying the variable initialization we can effectively handle and fix this error in the JavaScript applications.
When running JavaScript code, you might encounter an error that says:
Uncaught TypeError: Cannot read properties of null (reading 'x')
This error occurs when you try to read a property of an object, but the object itself is actually null so the property doesn’t exist.
Let me show you an example that causes this error and how I fix it.
How to reproduce this error
Suppose you write some JavaScript code to select an element from the DOM and read its value using the .value property.
You might write code as follows:
let inputEl = document.getElementById("text-input");
let inputVal = inputEl.value;
The code above tries to fetch an element that has an id of text-input. When the element isn’t found, then JavaScript will return null.
In the second line, we tried to read the value property of the inputEl object. If the inputEl object is null, then the error occurs:
Uncaught TypeError: Cannot read properties of null (reading 'value')
Variations of this error might occur depending on what property you’re trying to access.
For example, you can also try to call the addEventListener() method on a button object as follows:
let btnEl = document.getElementById("my-button");
console.log(btnEl); // null
btnEl.addEventListener("click", () => alert("You clicked a button!"));
When the getElementById() method can’t find the button, it returns null, so calling the addEventListener() method generates the error:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
As you can see, calling a property from an element that doesn’t exist will cause this error.
How to fix this error
To resolve this error, you need to make sure that you’re not accessing properties of a null object.
You can do so by adding an if statement before accessing the property. For example:
let inputEl = document.getElementById("text-input");
if (inputEl) {
let inputVal = inputEl.value;
}
The if statement above will check if the variable inputEl is not null before running the code block.
This way, the value property from the inputEl object won’t be called when the inputEl is null.
The same goes for the button element. As an alternative, you can also use the optional chaining operator ?. as follows:
let btnEl = document.getElementById("my-button");
btnEl?.addEventListener("click", () => alert("You clicked a button!"));
This way, the addEventListener() method is only called when the btnEl variable isn’t null.
Sometimes, you also get this error even when the element exists on your page. If this is the case, then you need to make sure that you run the JavaScript code after the page content has been loaded.
Make sure that you place your <script> tag before the closing </body> tag as shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Nathan Sebhastian</title>
</head>
<body>
<button id="btn">Sign up</button>
<!-- ✅ Script is placed before the closing body tag -->
<script>
let btnEl = document.getElementById("my-button");
btnEl?.addEventListener("click", () => alert("You clicked a button!"));
</script>
</body>
</html>
It doesn’t matter whether you have an inline or external script. You need to place it after the HTML elements.
Another way to ensure the script is executed after the content has been loaded is to listen for the DOMContentLoaded event from the document object as shown below:
document.addEventListener('DOMContentLoaded', () => {
let btnEl = document.getElementById("my-button");
btnEl?.addEventListener("click", () => alert("You clicked a button!"));
});
By wrapping your JavaScript code inside the addEventListener() method for the DOMContentLoaded event, you make sure that the code only gets executed after the content is loaded.
And that’s how you fix the TypeError: Cannot read properties of null when running JavaScript code.
I hope this tutorial helps. See you in other tutorials! 👋
In the vast realm of JavaScript, encountering errors is a rite of passage for every developer. One such common error is the notorious TypeError: cannot read properties of null. This error can be a bit perplexing, especially for beginners. But fear not, for we’re here to dissect it and provide you with solutions to tackle it head-on.
graph TD
A[Start]
B{Check if object is null}
C[Access object properties]
D[Error: cannot read properties of null]
E[Handle error]
A —> B
B — Yes —> D
B — No —> C
D —> E
Understanding the Root of the Error
Before diving into the solutions, it’s crucial to understand why this error occurs. The primary reason behind this error is attempting to access a property or invoke a method on a null object. In simpler terms, JavaScript expects an object with properties, but instead, it encounters a null value.
For those using Safari, you might see this error phrased slightly differently: TypeError: null is not an object.
Consider this example:
Java
var myArray = null;
if(myArray.length === null){
console.log("Array is null");
}
In the above code, we’re trying to access the length property of myArray, which is set to null. This will inevitably lead to the error in question.
The Importance of the DOM
A common scenario where this error pops up is when trying to access a DOM element that hasn’t been rendered yet. Remember, JavaScript reads code from top to bottom. If you’re trying to access a DOM element before it’s available, you’ll run into this error.
Debugging Techniques
1. Proper Variable Declaration
Always ensure that your variables are correctly declared and initialized. This practice can prevent a multitude of errors, including the one we’re discussing.
2. Utilize Conditional Statements
You can use conditional statements to check the type of an object before accessing its properties:
JavaScript
if(typeof(obj) !== "null"){
// Access properties or methods
} else {
// Handle the null object
}
3. Embrace Try/Catch Blocks
Another effective method to handle errors is by using try/catch blocks:
JavaScript
try {
// Code that might throw an error
} catch(err) {
// Handle the error gracefully
}
4. Understand the Difference Between null and undefined
It’s essential to remember that null and undefined are distinct in JavaScript. Neither are objects, and attempting to access properties on them will result in errors.
5. Event Listeners to the Rescue
You can also use event listeners to ensure that your code runs only when the DOM is fully loaded:
JavaScript
function init() {
// Your code here
}
document.addEventListener('readystatechange', function() {
if(document.readyState === "complete") {
init();
}
});
Conclusion
Errors are an integral part of a developer’s journey. They’re not just obstacles but learning opportunities. By understanding the root cause of the TypeError: cannot read properties of null and equipping yourself with the debugging techniques mentioned above, you’ll be well on your way to writing more robust and error-free JavaScript code.
Frequently Asked Questions (FAQs)
1. What’s the difference between null and undefined in JavaScript?
In JavaScript, null is an assignment value that represents no value or no object. It’s an intentional absence of any value. On the other hand, undefined means a variable has been declared but hasn’t been assigned a value yet.
2. Why do I get a TypeError when accessing properties on null or undefined?
Both null and undefined are primitive values in JavaScript, and they don’t have properties or methods. When you try to access a property or method on them, JavaScript throws a TypeError because it’s expecting an object but gets a primitive value instead.
3. How can I prevent the TypeError: cannot read properties of null error?
You can prevent this error by:
- Ensuring that variables are properly initialized before accessing their properties or methods.
- Using conditional checks to verify if a variable is not
nullorundefinedbefore accessing its properties. - Utilizing event listeners to ensure DOM elements are fully loaded before accessing them.
4. Is it a good practice to assign null to a variable?
Assigning null to a variable can be a good practice in scenarios where you want to explicitly indicate the absence of a value. It can be useful for garbage collection as it allows the variable’s previous value to be cleared from memory.
5. Can I use try/catch for all errors in JavaScript?
While try/catch is a powerful tool for handling errors, it’s not always the best solution for every error. Overusing try/catch can make your code harder to read and debug. It’s best used in scenarios where errors are expected, like parsing JSON or making API calls.
-
My name is Sachin Gurjar A.K.A Build With Sachin. I am a full stack blockchain developer and currently working remotely.
View all posts
