Now we'll see partially-correct JavaScript code in action and its implications.
Note
The completed source code for this example can be found in the source code folder, with the file name Chapter1-loading-errors-modified.html
.
Open your text editor, create a new document, and enter the following code into your document:
<html> <head><title>JavaScript Errors - Loading Errors</title></head> <body> <script type="text/javascript">/* 1. Loading Errors - modified */ // this is correct code var tests = "This is a CORRECT test"; document.write(tests); // this is incorrect code. The variable name referred is incorrect var Messsage = "This is a FIRSTtest"; document.write(Message); // this is correct code var testing = "this is a SECOND test"; document.write(testing); </script> </body> </html>
Now save your document and load your document in your web browser. You should see the text This is a test in your browser.
If you trace the code, you should see that the JavaScript executes from top to bottom. It stops executing when it encounters an error where an incorrect variable name is referenced by document.write()
. Because it stops executing when it encounters an error, the remaining JavaScript code will not be executed.
Things are slightly different if your JavaScript code is organized in terms of functions. In this situation, functions that have incorrect syntax will fail to execute, whereas syntactically-correct functions will continue to work, regardless of its order in the code.
By now, you should have a brief understanding of loading errors and how to prevent them by making sure that your code is syntactically correct.
Now let us move on to the next form of error—runtime errors.
Do you remember how JavaScript is loaded together with the web document into the browser? After the web document is loaded completely into the web browser, it is ready for various events, which leads to execution of JavaScript code.
Runtime errors occur during execution; for instance, consider an HTML button that has a JavaScript event attached to it. Assuming that a JavaScript function is assigned to an event, then if the JavaScript function has an error, that function will not be executed when the user clicks on the HTML button.
Other forms of runtime error occur when you misapply an object, variable, or method, or when you reference objects or variables that do not exist yet.