Skip to main content




Because data is the most important thing, we collect, analyze and classify data 10 errores de JavaScript more important. This gives users a good overview rather than a big overwhelming dump like you would see in a log file.

We focus on the errors that are most likely to affect you and your users. To do this, we classify the errors by the number of projects that experience them in different companies. If we look only at the total number of times each error occurred, then high-volume customers could overwhelm the dataset with errors that are not relevant to most readers.

Here are the top 10 JavaScript errors

Each error has been shortened to make it easier to read. Let's dive into each of them to determine what can cause it and how to avoid creating it.

Undetected error type: Cannot read property

If you are a JavaScript developer, you have probably seen this error more than you would like to admit. This happens in Chrome when you read a property or call a method on an undefined object. You can test it very easily in the Chrome development console.

Esto puede ocurrir por muchas razones, pero una común es la inicialización incorrecta del estado mientras se renderizan los componentes de la user interface.

TypeError: 'undefined' is not an object

This is an error that occurs in Safari when you read a property or call a method on an undefined object. You can test it very easily in the Safari development console. This is essentially the same error as the one above for Chrome, but Safari uses a different error message.

ERROR TYPE: null is not an object

This is an error that occurs in Safari when you read a property or call a method on a null object. You can test it very easily in the Safari development console.

Interestingly, in JavaScript, null and undefined are not the same, which is why we see two different error messages. Undefined is generally a variable that has not been assigned, while null means that the value is blank.

Una forma en que este error puede ocurrir en un ejemplo del mundo real es si intenta usar un elemento DOM en su JavaScript antes de que el elemento be cargado. Esto se debe a que la API DOM devuelve nullpara las referencias de objetos que están en blanco.

Cualquier código JS que ejecute y trate con elementos DOM debe ejecutarse después de que se hayan creado los elementos DOM. El código JS se interpreta de arriba hacia abajo como se indica en el HTML. Por lo tanto, si hay una etiqueta antes de los elementos DOM, el código JS dentro de la etiqueta script se ejecutará cuando el browser analice la página HTML. Obtendrá este error si los elementos DOM no han a sido creados antes de cargar el script.

(unknown): Script error

El error de Script se produce cuando un error de JavaScript no detectado cruza los límites del domain en violación de la política de origen cruzado. Por ejemplo, si aloja tu código JavaScript en una CDN, cualquier error no detectado (errores que burbujean hasta el manejador de errores window.onerror, instead of being caught in it try-catch) it will be reported as simply a "script error" instead of containing useful information. This is a browser security measure designed to prevent the passage of data through domains that would not otherwise be able to communicate.

TypeError: Object doesn't support property

This is an error that occurs in IE when an undefined method is called. You can test it in the IE Developer Console.

Esto es equivalente al error «TypeError: ‘undefined’ is not a function» en Chrome. Sí, diferentes browsers pueden tener diferentes mensajes de error para el mismo error lógico.

Este es un problema común para IE en aplicaciones Web que emplean espaciado de nombres JavaScript. Cuando este es el caso, el problema del 99,9% de las veces es la incapacidad de IE para enlazar métodos dentro del espacio de nombres actual con esta keyword. Por ejemplo, si tiene el espacio de nombres JS Rollbar con el método isAwesome.

TypeError: 'undefined' is not a function

Este es un error que se produce en Chrome cuando se llama a una función indefinida. Puede probarlo en la consola de desarrollo Chrome y en la consola de desarrollo Mozilla Firefox.

As JavaScript coding techniques and design patterns have become increasingly sophisticated over the years, there has been a corresponding increase in the proliferation of self-referencing scopes within callbacks and closures, which they are a fairly common source of this or that confusion.

Uncaught RangeError

This is an error that occurs in Chrome under a couple of circumstances. One is when a recursive function is called that does not terminate. You can test it in the Chrome development console.

It can also occur if a value is passed to a function that is out of range. Many functions accept only a specific range of numbers for their input values. For example, Number.toExponential (digits) and Number.toFixed (digits) accept digits from 0 to 100, and Number.toPrecision (digits) accept digits from 1 to 100.

TypeError: Cannot read property 'length'

This is an error that occurs in Chrome due to the read length property of an undefined variable. You can test it in the Chrome development console.

Normally the defined length is found in an array, but you may run into this error if the array is not initialized or if the variable name is hidden in another context. Let's understand this error with the following example.

Uncaught TypeError: Cannot set property

When we try to access an undefined variable it always returns undefined and we cannot get or set any property of undefined. In that case, an application will throw "Uncaught TypeError cannot set property of undefined".

ReferenceError: event is not defined

Este error se produce cuando se intenta acceder a una variable que está indefinida o fuera del scope actual. Puedes probarlo muy fácilmente en el navegador Chrome.

Si obtiene este error al utilizar el sistema de gestión de eventos, asegúrese de utilizar el objeto de event pasado como parámetro. Los navegadores más antiguos como IE ofrecen un evento de variable global, y Chrome automáticamente adjunta la variable de evento al handler. Firefox no lo añadirá automáticamente. Las bibliotecas como jQuery intentan normalizar este comportamiento. Sin embargo, es una buena práctica usar la que se ha pasado a la función del manejador de eventos.

conclusion

It turns out that many of these are null or undefined errors. A good static type checking system like Typescript podría ayudarte a evitarlos si utilizas la opción del compiler estricto. Puede advertirte si se espera un tipo pero no se ha definido. Incluso sin Typescript, it is useful to use protection clauses to check if objects are undefined before using them.

We hope you have learned something new and can avoid mistakes in the future, or that this guide has helped you solve a head scratch. However, even with best practices, unexpected errors appear in production. It is important to have visibility of the errors that affect users and to have good tools to solve them quickly.