Top 10 JavaScript errors from 1000+ projects (and how to avoid them)
To give back to our community of developers, we looked at our database of thousands of projects and found the top 10 errors in JavaScript. We’re going to show you what causes them and how to prevent them from happening. If you avoid these «gotchas,» it’ll make you a better developer.
Because data is king, we collected, analyzed, and ranked the top 10 JavaScript errors. Rollbar collects all the errors for each project and summarizes how many times each one occurred. We do this by grouping errors according to their fingerprints. Basically, we group two errors if the second one is just a repeat of the first. This gives users a nice overview instead of an overwhelming big dump like you’d see in a log file.
We focused on the errors most likely to affect you and your users. To do this, we ranked errors by the number of projects experiencing them across different companies. If we looked only at the total number of times each error occurred, then high-volume customers could overwhelm the data set with errors that are not relevant to most readers.
Here are the top 10 JavaScript errors:
Each error has been shortened for easier readability. Let’s dive deeper into each one to determine what can cause it and how you can avoid creating it.
1. Uncaught TypeError: Cannot read property
If you’re a JavaScript developer, you’ve probably seen this error more than you care to admit. This one occurs in Chrome when you read a property or call a method on an undefined object. You can test this very easily in the Chrome Developer Console.

Uncaught TypeError: Cannot read property can occur for many reasons, but a common one is improper initialization of state while rendering the UI components. Let’s look at an example of how this can occur in a real-world app. We’ll pick React, but the same principles of improper initialization also apply to Angular, Vue or any other framework.
There are two important things realize here:
- A component’s state (e.g. this.state ) begins life as undefined .
- When you fetch data asynchronously, the component will render at least once before the data is loaded – regardless of whether it’s fetched in the constructor, componentWillMount or componentDidMount . When Quiz first renders, this.state.items is undefined. This, in turn, means ItemList gets items as undefined, and you get an error – «Uncaught TypeError: Cannot read property ‘map’ of undefined» in the console.
This is easy to fix. The simplest way: Initialize state with reasonable default values in the constructor.
The exact code in your app might be different, but we hope we’ve given you enough of a clue to either fix or avoid this problem in your app. If not, keep reading because we’ll cover more examples for related errors below.
2. TypeError: ‘undefined’ is not an object (evaluating
This is an error that occurs in Safari when you read a property or call a method on an undefined object. You can test this very easily in the Safari Developer Console. This is essentially the same as the above error for Chrome, but Safari uses a different error message.

3. TypeError: null is not an object (evaluating
This is an error that occurs in Safari when you read a property or call a method on a null object. You can test this very easily in the Safari Developer Console.

Interestingly, in JavaScript, null and undefined are not the same, which is why we see two different error messages. Undefined is usually a variable that has not been assigned, while null means the value is blank. To verify they are not equal, try using the strict equality operator:

One way this error might occur in a real world example is if you try using a DOM element in your JavaScript before the element is loaded. That’s because the DOM API returns null for object references that are blank.
Any JS code that executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as laid out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page. You will get this error if the DOM elements have not been created before loading the script.
In this example, we can resolve the issue by adding an event listener that will notify us when the page is ready. Once the addEventListener is fired, the init() method can make use of the DOM elements.
4. (unknown): Script error
The (unknown): Script error occurs when an uncaught JavaScript error crosses domain boundaries in violation of the cross-origin policy. For example, if you host your JavaScript code on a CDN, any uncaught errors (errors that bubble up to the window.onerror handler, instead of being caught in try-catch) will get reported as simply «Script error» instead of containing useful information. This is a browser security measure intended to prevent passing data across domains that otherwise wouldn’t be allowed to communicate.
To get the real error messages, do the following:
1. Send the Access-Control-Allow-Origin header
Setting the Access-Control-Allow-Origin header to signifies that the resource can be accessed properly from any domain. You can replace with your domain if necessary: for example, Access-Control-Allow-Origin: www.example.com . However, handling multiple domains gets tricky, and may not be worth the effort if you’re using a CDN due to caching issues that may arise. See more here.
Here are some examples on how to set this header in various environments:
Apache
In the folders where your JavaScript files will be served from, create an .htaccess file with the following contents:
Header add Access-Control-Allow-Origin "*"
Nginx
Add the add_header directive to the location block that serves your JavaScript files:
location ~ ^/assets/
HAProxy
Add the following to your asset backend where JavaScript files are served from:
rspadd Access-Control-Allow-Origin:\ *
2. Set crossorigin=»anonymous» on the script tag
In your HTML source, for each of the scripts that you’ve set the Access-Control-Allow-Origin header for, set crossorigin=»anonymous» on the SCRIPT tag. Make sure you verify that the header is being sent for the script file before adding the crossorigin property on the script tag. In Firefox, if the crossorigin attribute is present but the Access-Control-Allow-Origin header is not, the script won’t be executed.
5. TypeError: Object doesn’t support property
This is an error that occurs in IE when you call an undefined method. You can test this in the IE Developer Console.

This is equivalent to the error «TypeError: ‘undefined’ is not a function» in Chrome. Yes, different browsers can have different error messages for the same logical error.
This is a common problem for IE in web applications that employ JavaScript namespacing. When this is the case, the problem 99.9% of the time is IE’s inability to bind methods within the current namespace to the this keyword. For example, if you have the JS namespace Rollbar with the method isAwesome. Normally, if you are within the Rollbar namespace you can invoke the isAwesome method with the following syntax:
this.isAwesome();
Chrome, Firefox and Opera will happily accept this syntax. IE, on the other hand, will not. Thus, the safest bet when using JS namespacing is to always prefix with the actual namespace.
Rollbar.isAwesome();
6. TypeError: ‘undefined’ is not a function
This is an error that occurs in Chrome when you call an undefined function. You can test this in the Chrome Developer Console and Mozilla Firefox Developer Console.

As JavaScript coding techniques and design patterns have become increasingly sophisticated over the years, there’s been a corresponding increase in the proliferation of self-referencing scopes within callbacks and closures, which are a fairly common source of this/that confusion.
Consider this example code snippet:
function clearBoard() < alert("Cleared"); >document.addEventListener("click", function()< this.clearBoard(); // what is “this” ? >);
If you execute the above code and then click on the page, it results in the following error «Uncaught TypeError: this.clearBoard is not a function». The reason is that the anonymous function being executed is in the context of the document, whereas clearBoard is defined on the window.
A traditional, old-browser-compliant solution is to simply save your reference to this in a variable that can then be inherited by the closure. For example:
var self=this; // save reference to 'this', while it's still this! document.addEventListener("click", function()< self.clearBoard(); >);
Alternatively, in the newer browsers, you can use the bind() method to pass the proper reference:
document.addEventListener("click",this.clearBoard.bind(this));
7. Uncaught RangeError
This is an error that occurs in Chrome under a couple of circumstances. One is when you call a recursive function that does not terminate. You can test this in the Chrome Developer Console.

It may also happen if you pass a value 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) accepts digits from 1 to 100.
var a = new Array(4294967295); //OK var b = new Array(-1); //range error var num = 2.555555; document.writeln(num.toExponential(4)); //OK document.writeln(num.toExponential(-2)); //range error! num = 2.9999; document.writeln(num.toFixed(2)); //OK document.writeln(num.toFixed(105)); //range error! num = 2.3456; document.writeln(num.toPrecision(1)); //OK document.writeln(num.toPrecision(0)); //range error!
8. TypeError: Cannot read property ‘length’
This is an error that occurs in Chrome because of reading length property for an undefined variable. You can test this in the Chrome Developer Console.

You normally find length defined on an array, but you might 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.
var testArray= ["Test"]; function testFunction(testArray) < for (var i = 0; i < testArray.length; i++) < console.log(testArray[i]); >> testFunction();
When you declare a function with parameters, these parameters become local ones. This means that even if you have variables with names testArray , parameters with the same names within a function will still be treated as local.
You have two ways to resolve your issue:
-
Remove parameters in the function declaration statement (it turns out you want to access those variables that are declared outside of the function, so you don’t need parameters for your function):
var testArray = ["Test"]; /* Precondition: defined testArray outside of a function */ function testFunction(/* No params */) < for (var i = 0; i < testArray.length; i++) < console.log(testArray[i]); >> testFunction();
var testArray = ["Test"]; function testFunction(testArray) < for (var i = 0; i < testArray.length; i++) < console.log(testArray[i]); >> testFunction(testArray);
9. 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.”
For example, in the Chrome browser:

If the test object does not exist, error will throw “Uncaught TypeError cannot set property of undefined.”
10. ReferenceError: event is not defined
This error is thrown when you try to access a variable that is undefined or is outside the current scope. You can test it very easily in Chrome browser.

If you’re getting this error when using the event handling system, make sure you use the event object passed in as a parameter. Older browsers like IE offer a global variable event, and Chrome automatically attaches the event variable to the handler. Firefox will not automatically add it. Libraries like jQuery attempt to normalize this behavior. Nevertheless, it’s best practice to use the one passed into your event handler function.
document.addEventListener("mousemove", function (event) < console.log(event); >)
Conclusion
It turns out a lot of these are null or undefined errors. A good static type checking system like Typescript could help you avoid them if you use the strict compiler option. It can warn you if a type is expected but has not been defined. Even without Typescript, it helps to use guard clauses to check whether objects are undefined before using them.
We hope you learned something new and can avoid errors in the future, or that this guide helped you solve a head scratcher. Nevertheless, even with the best practices, unexpected errors do pop up in production. It’s important to have visibility into errors that affect your users, and to have good tools to solve them quickly.
Rollbar gives you visibility to production JavaScript errors and gives you more context to solve them quickly. For example, it offers additional debugging features like telemetry which tells you what happened on the user’s browser leading up to the error. That’s insight you don’t have outside of your local developer console. Learn more in Rollbar’s full list of features for JavaScript applications.
If you haven’t already, signup for a 14-day free trial of Rollbar and let us help you take control of impactful JavaScript errors.
«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»
What went wrong? Troubleshooting JavaScript
When you built up the «Guess the number» game in the previous article, you may have found that it didn’t work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in JavaScript programs.
| Prerequisites: | Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is. |
|---|---|
| Objective: | To gain the ability and confidence to start fixing problems in your own code. |
Types of error
Generally speaking, when you do something wrong in code, there are two main types of error that you’ll come across:
- Syntax errors: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!
- Logic errors: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn’t an error message to direct you to the source of the error.
Okay, so it’s not quite that simple — there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We’ll look at both of these types going forward.
An erroneous example
To get started, let’s return to our number guessing game — except this time we’ll be exploring a version that has some deliberate errors introduced. Go to GitHub and make yourself a local copy of number-game-errors.html (see it running live here).
- To get started, open the local copy inside your favorite text editor, and your browser.
- Try playing the game — you’ll notice that when you press the «Submit guess» button, it doesn’t work!
Note: You might well have your own version of the game example that doesn’t work, which you might want to fix! We’d still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.
At this point, let’s consult the developer console to see if it reports any syntax errors, then try to fix them. You’ll learn how below.
Fixing syntax errors
Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (if you can’t remember how to open this in your browser, follow the previous link to find out how). What’s even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser’s JavaScript engine. Now let’s go hunting.

- Go to the tab that you’ve got number-game-errors.html open in, and open your JavaScript console. You should see an error message along the following lines:
- The first line of the error message is:
Uncaught TypeError: guessSubmit.addeventListener is not a function number-game-errors.html:86:15
- The first part, Uncaught TypeError: guessSubmit.addeventListener is not a function , is telling us something about what went wrong.
- The second part, number-game-errors.html:86:15 , is telling us where in the code the error came from: line 86, character 15 of the file «number-game-errors.html».
Warning: Error message may not be on line 86. If you are using any code editor with an extension that launches a live server on your local machine, this will cause extra code to be injected. Because of this, the developer tools will list the error as occurring on a line that is not 86.
.addeventListener("click", checkGuess);
Note: See our TypeError: «x» is not a function reference page for more details about this error.
Syntax errors round two

- Save your page and refresh, and you should see the error has gone.
- Now if you try to enter a guess and press the Submit guess button, you’ll see another error!
- This time the error being reported is:
Uncaught TypeError: can't access property "textContent", lowOrHi is null
Depending on the browser you are using, you might see a different message here. The message above is what Firefox will show you, but Chrome, for example, will show you this:
Uncaught TypeError: Cannot set properties of null (setting 'textContent')
It’s the same error, but different browsers describe it in a different way.
Note: This error didn’t come up as soon as the page was loaded because this error occurred inside a function (inside the checkGuess() < >block). As you’ll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the checkGuess() function was run by line 86.
.textContent = "Last guess was too high!";
const lowOrHi = document.querySelector("lowOrHi");
.log(lowOrHi);

This code will print the value of lowOrHi to the console after we tried to set it in line 49. See console.log() for more information.
p class="lowOrHi">p>
Note: See our TypeError: «x» is (not) «y» reference page for more details about this error.
Syntax errors round three
- Now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses.
- At that point, the game fails again, and the same error is spat out that we got at the beginning — «TypeError: resetButton.addeventListener is not a function»! However, this time it’s listed as coming from line 94.
- Looking at line number 94, it is easy to see that we’ve made the same mistake here. We again just need to change addeventListener to addEventListener . Do this now.
A logic error
At this point, the game should play through fine, however after playing through a few times you’ll undoubtedly notice that the game always chooses 1 as the «random» number you’ve got to guess. Definitely not quite how we want the game to play out!
There’s definitely a problem in the game logic somewhere — the game is not returning an error; it just isn’t playing right.
-
Search for the randomNumber variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 45:
let randomNumber = Math.floor(Math.random()) + 1;
= Math.floor(Math.random()) + 1;
.log(randomNumber);
Working through the logic
To fix this, let’s consider how this line is working. First, we invoke Math.random() , which generates a random decimal number between 0 and 1, e.g. 0.5675493843.
.random();
Next, we pass the result of invoking Math.random() through Math.floor() , which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:
.floor(Math.random()) + 1;
Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:
.floor(Math.random() * 100);
Hence us wanting to add 1, to give us a random number between 1 and 100:
.floor(Math.random() * 100) + 1;
Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!
Other common errors
There are other common errors you’ll come across in your code. This section highlights most of them.
SyntaxError: missing ; before statement
This error generally means that you have missed a semicolon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the checkGuess() function:
const userGuess = Number(guessField.value);
const userGuess === Number(guessField.value);
It throws this error because it thinks you are trying to do something different. You should make sure that you don’t mix up the assignment operator ( = ) — which sets a variable to be equal to a value — with the strict equality operator ( === ), which tests whether one value is equal to another, and returns a true / false result.
Note: See our SyntaxError: missing ; before statement reference page for more details about this error.
The program always says you’ve won, regardless of the guess you enter
This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside checkGuess() :
if (userGuess === randomNumber)
if (userGuess = randomNumber)
the test would always return true , causing the program to report that the game has been won. Be careful!
SyntaxError: missing ) after argument list
This one is pretty simple — it generally means that you’ve missed the closing parenthesis at the end of a function/method call.
Note: See our SyntaxError: missing ) after argument list reference page for more details about this error.
SyntaxError: missing : after property id
This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing
function checkGuess()
function checkGuess(
This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!
SyntaxError: missing > after function body
This is easy — it generally means that you’ve missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the checkGuess() function.
SyntaxError: expected expression, got ‘string‘ or SyntaxError: unterminated string literal
These errors generally mean that you’ve left off a string value’s opening or closing quote mark. In the first error above, string would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.
For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what’s wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!
Note: See our SyntaxError: Unexpected token and SyntaxError: unterminated string literal reference pages for more details about these errors.
Summary
So there we have it, the basics of figuring out errors in simple JavaScript programs. It won’t always be that simple to work out what’s wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don’t turn out right, especially in the earlier stages of your learning journey.
See also
- There are many other types of errors that aren’t listed here; we are compiling a reference that explains what they mean in detail — see the JavaScript error reference.
- If you come across any errors in your code that you aren’t sure how to fix after reading this article, you can get help! Ask for help on the communication channels. Tell us what your error is, and we’ll try to help you. A listing of your code would be useful as well.
- Previous
- Overview: First steps
- Next
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Jul 3, 2023 by MDN contributors.
Your blueprint for a better internet.
Что значит JavaScript Error: учимся дебажить JavaScript на примерах
![]()
«JavaScript error, что это значит?» — именно такой вопрос задают многие пользователи операционной системы Windows, так как это одна из самых известных проблем с несовместимостью в этой ОС. Данная ошибка оповещает пользователя, что произошел какой-то сбой в определенном программном обеспечении. Многие проблемы подобного рода можно исправить самостоятельно, но некоторые из них могут исправить только квалифицированные специалисты.
JavaScript error, что это значит
- нарушение в каких-либо процессах приложения ;
- повреждение системных файлов;
- отключение какой-либо службы;
- и др.
Как исправить JavaScript error (ява скрипт эррор)?
- Первое , что необходимо выполнить , — это проверить компьютер на предмет заражения вирусом, потому что вирусы очень часто провоцируют подобные ошибки. А спонсором данного материала является сайт Уфавип, на котором размещены анкеты всех шлюх в Уфе из Черниковки. На нем вы непременно сможете подобрать проститутку, подходящую вам как в плане цены, так и в плане предоставляемых ею услуг. Если антивирус обнаружил вирус, то исключите его и попробуйте заново запустить приложение, которое вызвало проблему «JavaScript error».
- Нужно обновить программное обеспечение, которое вызвало ошибку , и саму операционную систему. Из-за отсутствия обновлений возникают подобные проблемы. А иногда ошибка может возникнуть из-за того , ч то один компонент обновился, а другой — нет : например, программу вы обновили, а ОС — нет. В результате выл езает «JavaScript error», а вы бежите в и нтернет узнавать, что это значит.
- Еще одним популярным решением является полный «снос» проблемного ПО, а потом его переустановка.
- Также при ошибке «JavaScript error» может помочь восстановление операционной системы до той даты, когда она функционировала нормально.
Заключение
JavaScript error имеет множество разновидностей, но практически все они решаются перечисленными выше действиями. Если ни один из способов вам не помог — это значит, что самое время обратиться в специализированный сервис, потому как есть шанс, что проблема расположена намного «глубже», чем может достать обычный пользователь.
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
How to Fix JavaScript Errors

My computer programming teacher had always told me that 10% of our time is spent developing 90% of our application, and the other 90% of our time finishing the last 10% of our project. Even with a good project plan and a concept that makes logical sense, most of our time will be consumed with fixing errors. Moreover, with JavaScript, our application can run without obvious errors preventing it from being run, so we have to employ several techniques to make sure everything is running smoothly.
Understanding both the syntax and how JavaScript works will eliminate most of our JavaScript errors in our web applications. Furthermore, there are many online services that can help us catch them all.
Starting from basic to advanced, here are some methods to fix JavaScript errors in our applications.
Know the Different Types of JavaScript Errors
We need to know what type of error we’re receiving to know what we need to do to fix it. Namely, with JavaScript, most of our errors fit into two categories: syntax errors and runtime errors.
A syntax error is a problem with the grammar in our code. Syntax errors mostly come in the form of misspelled keywords, missing or open brackets, or missing parentheses or punctuation. Certainly, through time, our syntax errors will become fewer as we become experts in JavaScript, but simple mistakes do happen a lot.
A runtime error prevents our application from actually running. Sometimes there’s a problem with our logic flow and our program breaks, like calling strings that aren’t there. Other times, our program can run but the result isn’t as we planned it. Consequently, runtime errors can be a bit trickier to fix than syntax errors.
Since we know the two main types of JavaScript errors, we can swiftly move on to fixing them.
When in Doubt, Reload
Sometimes the simplest thing we can do is reload the web page. It’s the classic IT crowd solution to everything—turn it on and off again. Maybe we already solved this error and the file hasn’t uploaded yet or some data was missing. It may also help to delete your browser history and cache in case your browser is saving a bad version of your website or application.
Google Chrome sometimes displays an “Aw, Snap!” error when it has difficulty running our web page. This may or may not be caused by a JavaScript error—either way, don’t panic and just reload the page.
Then we can move on to checking for JavaScript errors in further detail.
Check If JavaScript Is Turned On
We must keep in mind that JavaScript is set differently for each browser. Furthermore, JavaScript reacts differently depending on each browser and how each user’s settings are set for their browsers. For example, JavaScript has some security holes, and hackers may put malicious code in some JavaScript; thus, for safety reasons, JavaScript is often turned off in some browsers. So we must check our browser settings to see if JavaScript is turned on.
Cross-site scripting (XSS) is one vulnerability in JavaScript that allows hackers to inject malicious code into legitimate websites. For example, Twitter was injected by malware called the “StalkDaily” worm. That doesn’t sound good, does it? Hence, turning JavaScript off avoids security issues but will obviously cause errors when you’re running an application with JavaScript.
If you’re not sure, you can quickly check here to see if your browser’s JavaScript is turned on.
Similarly, we can check whether we have a pop-up blocker enabled that’s preventing parts of our JavaScript from working, such as our use of alert boxes. We can enable or disable pop-up boxes from either our browser settings or an add-on that we’re using.
Now that we’ve covered the basics, let’s move on to some things that are more advanced.
Use In-Browser Developer Tools
By far the most useful tools at our disposal for fixing JavaScript errors are the in-browser developer tools. Previously, when I was a young developer, I would use Firefox separately to browse the web projects that I was developing. Now I use whichever browser suits my needs at the moment—Firefox, Chrome, Safari, Microsoft Edge, Opera, or Brave.
In 2019, Firefox and Chrome were the two most popular browsers with developers.
To get started, just open up your favorite browser with developer tools, then find the developer tools in the browser menu. Begin looking at the various elements or console tools to find some errors to fix.
Some developer tools also let us check if our web design is responsive to mobile devices.
Developer tools are useful for checking JavaScript errors as well as:
- Currently loaded HTML and CSS
- DOM explorer
- Layout
- Animations
- Memory use
- Console logs
- Debugger
- File list
- Source code
And many more, depending on the in-browser developer tool.
Check Cross-Browser Compatibility
As I said before, each browser responds to JavaScript differently. This means that our application may not be compatible with all browsers, and we’ll have errors to fix. Unfortunately, it’s not reasonable to prompt a pop-up box to encourage users to download. Because of this, we have to double- and triple-check that our websites are compatible with all internet browsers.
JavaScript cross-browser compatibility issues usually revolve around modern core JavaScript features and some libraries that are either from third parties or native to JavaScript.
So, either download each of the major browsers and individually test for browser compatibility, or try out a range of different software that can test cross-browser compatibility.
Browsera is one tool that not only tests for cross-browser compatibility but also detects JavaScript errors as well.
Use Console.log() to Display Anticipated Results
Console.log() is a function that allows us to display messages in our browser console. Moreover, we also print strings and other variables so we can see their values. This is indeed useful for us to check if our functions are displaying the desired results.
These types of errors may not stop our applications from running, but at the same time, they’re functional errors for us to fix.
For example, we can create an event listener that checks if a particular button is clicked on. When the onClick event is triggered, a message confirming that our function works appears in our console.
Ideally, we should use these tests only during the development stage of our web project, and we should remove these console.log() events from our final product.
document.addEventListener('buttonClick', function (event) < console.log("Button Clicked!"); >, false);
Likewise, we can use JavaScript alert boxes with a similar method.
document.addEventListener('buttonClick', function (event) < alert("I am in a box with a " str + "!"); >, false);
In the End
Our basic knowledge of how JavaScript works and some simple coding practices should be enough to fix our JavaScript errors. In addition to these skills, we have hundreds of online services to choose from that can help us catch those trickier errors.
Hopefully, through time, less than 90% of our time will be used up fixing JavaScript if we use the above methods.
Check out Retrace real user monitoring. It can monitor everything about your JavaScript applications to catch errors and accelerate web performance, including the following:
- Integrate errors and logs
- Consolidate alerts and notifications
- Customize dashboards
- Monitor JavaScript files and functions
- Accelerate page load times
- Improve user experience
- Monitor front-end and back-end code together
- Accurately locate and resolve bottlenecks faster
Improve Your Code with Retrace APM
Stackify’s APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace’s product features to learn more.
