Find errors in javascript code

Ошибки в JavaScript и как их исправить

JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!

Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.

Как читать ошибки?

Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.

Типичная ошибка из Chrome выглядит так:

Uncaught TypeError: undefined is not a function 
  1. Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch , а TypeError — это название ошибки.
  2. undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.

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 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:

В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.

Читайте также:  Html точка или стрелка

Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову 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

Читайте также:  Bitrix nginx urlrewrite php

Эта проблема всегда связана с использованием 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 здесь.

Источник

Mastering Debugging Techniques: Tips and Tricks to Effectively Find and Fix Errors in Your Code in Javascript

Mastering Debugging Techniques: Tips and Tricks to Effectively Find and Fix Errors in Your Code in Javascript

As an experienced web developer, I’ve had my fair share of debugging challenges. Debugging is an essential skill for any programmer, and it can often be the difference between a successful project and a complete failure. In this blog, I’ll share some tips and tricks I’ve learned over the years to effectively find and fix errors in your code using JavaScript. image source

1. Use a Debugger

Debuggers are essential tools for finding and fixing errors in your code. JavaScript comes with a built-in debugger that allows you to step through your code line by line and track the values of variables and expressions as they change. Most modern web browsers also come with a debugger that you can use to debug your code in real-time. Here’s an example of how to use the debugger in JavaScript:

function multiply(a, b)  let result = a * b; debugger; return result; > let x = multiply(2, 3); console.log(x); 

In this example, we’re using the built-in debugger to stop the code at a specific point and inspect the value of the result variable. This can help us identify any issues in the code and fix them accordingly.

2. Understand Error Messages

Error messages are your best friend when it comes to debugging. They provide valuable information about what went wrong in your code and where the error occurred. It’s essential to read error messages carefully and try to understand what they’re telling you. Let’s take a look at an example error message in JavaScript:

Uncaught TypeError: Cannot read property 'length' of undefined at foo (index.js:4) at index.js:8 

In this error message, we can see that there’s a TypeError in our code. We’re trying to read the length property of an undefined variable. The error occurred on line 4 of our foo function and was called from line 8 of our code.

3. Use Print Statements

Print statements are an effective way to debug your code. By inserting console.log statements throughout your code, you can see the values of variables and expressions at various points in the program’s execution. This can help you identify where the code is going wrong. Here’s an example of how to use console.log in JavaScript:

function multiply(a, b)  let result = a * b; console.log(result); return result; > let x = multiply(2, 3); 

In this example, we’re using console.log to print the value of the result variable to the console. This can help us identify any issues in the code and fix them accordingly.

4. Simplify Your Code

If you’re having trouble finding an error in your code, try simplifying it. Remove any unnecessary code or complexity and focus on the specific part of the code where the error is occurring. This can make it easier to identify and fix the problem. Let’s take a look at an example:

function foo(bar)  let result = bar * 2; return result; > let x = foo(2); console.log(x); 

In this example, we’re calling a simple function that multiplies a number by 2. By simplifying our code, we can easily identify any issues and fix them accordingly.

5. Take Breaks

Debugging can be a frustrating and time-consuming process. If you’re struggling to find an error, take a break and come back to it later with fresh eyes. Sometimes, stepping away from the code for a while can help you see the problem more clearly.

6. Use Version Control

Version control tools like Git can be incredibly helpful for debugging. By tracking changes to your code over time, you can easily identify when a bug was introduced and trace it back to its source.

7. Ask for help

Don’t be afraid to ask for help if you’re stuck. Reach out to your colleagues or the programming community for assistance. Sometimes, a fresh perspective can help you see the problem in a new light.

Conclusion:

Debugging is an essential skill for any developer, and mastering it takes time and practice. By using a debugger, understanding error messages, using print statements, simplifying your code, taking breaks, using version control, and asking for help, you can effectively find and fix errors in your code. Remember, debugging can be a frustrating and time-consuming process, but don’t get discouraged. Even experienced developers face bugs in their code. The key is to stay patient, persistent, and use the techniques and tools at your disposal to solve the problem. As a developer with over eight years of experience in web development, I can attest to the importance of these debugging techniques. While there’s no one-size-fits-all approach to debugging, using a combination of these techniques can help you become a more efficient and effective developer. So keep practicing and happy debugging!

Источник

Оцените статью