Syntax Validation in JavaScript Testing

Exclusive offer: get 50% off this eBook here
JavaScript Testing Beginner's Guide

JavaScript Testing Beginner's Guide — Save 50%

Test and debug JavaScript the easy way.

£16.99    £8.50
by Yuxian Eugene Liang | August 2010 | Beginner's Guides Open Source

In this article, by Liang Yuxian Eugene, author of JavaScript Testing, we shall learn about the following topics:

  • The difference between validating and testing
  • How a good code editor can help you spot validation errors
  • What makes a code quality code
  • Why do we need HTML and CSS to be valid before we start working on JavaScript
  • Why JavaScript embedded in HTML may be reported as invalid
  • Common JavaScript errors that are detected by validating
  • JSLint and JavaScript Lint—how to use it to check your code
  • Valid code constructs that produce validation warnings
  • How to fix validation errors that are spotted by JSLint

(For more resources on JavaScript, see here.)

So without further ado, let us get started with a lighter topic—the difference between validating and testing.

The difference between validating and testing

There's a thin line separating validating and testing. If you have some idea about sets (as in sets from mathematics), I would say that validation can lead to better testing results, while testing does not necessarily lead to a valid code.

Let us consider the scenario—you wrote a JavaScript program and tested it on major browsers such as the Internet Explorer and Firefox; and it worked. In this case, you have tested the code to make sure that it is functional.

However, the same code that you have created may or may not be valid; valid code is akin to writing a code that has the following characteristics:

  • Well formed
  • Has good coding style (such as proper indentation, well-commented code, properly spaced)
  • Meets the specification of the language (in our case, JavaScript)

There may come a point in time where you will notice that good coding style is highly subjective—there are various validators that may have different opinions or standards as to what is known as "good coding style". Therefore, if you do use different validators to validate your code, do not freak out if you see different advice for your coding style.

This does not mean that valid code leads to code that is functional (as you will see later) and that code that is functional leads to validated code as both have different standards for comparison.

However, valid code often leads to less errors, and code that is both functional and valid is often quality code. This is due to the fact that writing a piece of JavaScript code, that is both valid and correct, is much more difficult than just writing a code that is correct.

Testing often means that we are trying to get the code working correctly; while validation is making sure that the code is syntactically correct, with good style and that it meets the specification of the language. While good coding styles may be subjective, there is often a coding style that is accepted by most programmers, such as, making sure that the code is properly commented, indented, and there is no pollution of the global namespace (especially in the case of JavaScript).

To make the case clearer, following are three situations that you can consider:

Code that is valid but wrong–validation doesn't find all the errors

This form of errors would most probably be caused by logic errors in JavaScript. Logic errors can be syntactically correct but they may be logically flawed.

A classic example would be an infinite for loop or infinite while loop.

Code that is invalid but right

This would most probably be the case for most functional code; a piece of JavaScript may be functionally correct and working, but it may be invalid. This may be due to poor coding style or any other characteristics in a valid code that are missing.

Later on in this article, you will see a full working example of a piece of JavaScript code that is right but invalid.

Code that is invalid and wrong–validation finds some errors that might be difficult to spot any other way

In this case, the code error can be caused by all three forms of JavaScript errors that are mentioned in the article such as loading errors, runtime errors, and logic errors. While it is more likely that errors caused by syntax errors might be spotted by good validators, it is also possible that some errors are buried deep inside the code, such that it is difficult to spot them using manual methods.

Now that we have some common understanding as to what validation and testing is about, let us move on to the next section which discusses the issues surrounding quality code.

Code quality

While there are many views as to what is quality code, I personally believe that there are a few agreed standards. Some of the most commonly mentioned standards may include code readability, ease of extension, efficiency, good coding style, and meeting language specifications, and so on.

For our purpose here, we will focus on the factors that make a piece of code valid—coding style and meeting specifications. In general, good coding style almost guarantees that the code is highly readable (even to third parties) and this will help us to spot errors manually.

Most importantly, having a good coding style allows us to quickly understand the code, specially if we need to work in teams or are required to debug the code on our own.

You will notice that we will focus on the importance of code validity for testing purposes in later parts of the article. But now, let us start with the first building block of quality code—valid HTML and CSS.

HTML and CSS needs to be valid before you start on JavaScript

We have a common understanding that JavaScript breathes life into a web page by manipulating the Document Object Model (DOM) of the HTML documents. This means that the DOM must be present in the code before JavaScript can operate on it.

Here's an important fact that is directly related to HTML, CSS, and browsers—browsers are generally forgiving towards invalid HTML and CSS code as compared to compilers for languages like C or Python. This is because, all browsers have to do is parse the HTML and CSS so as to render the web page for its browsers. On the other hand, compilers are generally unforgiving towards invalid code. Any missing tag, declarations, and so on will lead to a compilation error. Therefore, it is ok to write invalid or even buggy HTML and CSS, yet get a "usual" looking web page.

Based on the previous explanation, we should see that we would need to have valid HTML and CSS in order to create quality JavaScript code.

A short list of reasons, based on my personal experience, as to why valid HTML and CSS is an important prerequisite before you start working on JavaScript are as follows:

  • Valid HTML and CSS helps ensure that JavaScript works as intended. For example, consider a situation where you might have two div elements that have the same id , code that is supposed to work on the above mentioned HTML element with the id. This will result in unintended consequences.
  • Valid HTML and CSS helps improve the predictability on how your web page will work; there is no point trying to fi x buggy HTML or CSS using JavaScript. You are most probably better off if you start with valid HTML and CSS, and then apply JavaScript.
  • Invalid HTML and CSS may result in different behaviour in different browsers. For example, an HTML tag that is not enclosed may be rendered differently in different browsers.

In short, one of the most important building blocks of creating quality JavaScript code is to have valid HTML and CSS.

What happens if you don't validate your code

You may disagree with me on the previous section as to why HTML and CSS should be valid. In general, validation helps you to prevent errors that are related to coding style and specifications. However, do take note that using different validators may give you different results since validators might have different standards in terms of code style.

In case you are wondering if invalid code can affect your JavaScript code, I would advise you to make your code as valid as possible; invalid code may lead to sticky issues such as cross-browser incompatibility, difficulty in reading code, and so on.

Invalidated code means that your code may not be foolproof; in the early days of the Internet, there were websites that were dependent on the quirks of the early Netscape browser. Back track to the time where the Internet Explorer 6 was widely used, there were also many websites that worked in quirks mode to support Internet Explorer 6.

Now, most browsers are supporting or are moving towards supporting web standards (though slightly different, they are supporting in subtle manners), writing valid code is one of the best ways to ensure that your website works and appears the way it is intended to.

How validation can simplify testing

While invalid code may not cause your code to be dysfunctional, valid code often simplifies testing. This is due to the focus on coding style and specifications; codes that are valid and have met specifications are typically more likely to be correct and much easier to debug. Consider the following code that is stylistically invalid:

function checkForm(formObj){
alert(formObj.id)
//alert(formObj.text.value);
var totalFormNumber = document.forms.length;
// check if form elements are empty and are digits
var maxCounter = formObj.length; // this is for checking for empty
values
alert(totalFormNumber);
// check if the form is properly filled in order to proceed
if(checkInput(formObj)== false){
alert("Fields cannot be empty and it must be digits!");
// stop executing the code since the input is invalid
return false;
}
else{
;
}
var i = 0;
var formID;
while(i < totalFormNumber){
if(formObj == document.forms[i]){
formID = i;alert(i);
}
i++;
}
if(formID<4){
formID++;
var formToBeChanged = document.forms[formID].id;
// alert(formToBeChanged);
showForm(formToBeChanged);
}
else{
// this else statement deals with the last form
// and we need to manipulate other HTML elements
document.getElementById("formResponse").style.visibility = "visible";
}
return false;
}

The previous code is an extreme example of poor code style, especially in terms of indentation. Imagine if you have to manually debug the second code snippet that you saw earlier! I am pretty sure that you will find it frustrating to check the code, because you will have little visual sense of what is going on.

More importantly, if you are working in a team, you will be required to write legible code; in short, writing valid code typically leads to code that is more legible, easier to follow, and hence, less erroneous.

Validation can help you debug your code

As mentioned in the previous section, browsers are in general forgiving towards invalid HTML and CSS. While this is true, there may be errors that are not caught, or are not rendered correctly or gracefully. This means that while the invalid HTML and CSS code may appear fine on a certain platform or browser, it may not be supported on others.

This means that using valid code (valid code typically means standard code set by international organizations such as W3C) will give you a much greater probability of having your web page rendered correctly on different browsers and platforms.

With valid HTML and CSS, you can safely write your JavaScript code and expect it to work as intended, assuming that your JavaScript code is equally valid and error free.

Validation helps you to code using good practices

Valid code typically requires coding using good practices. As mentioned frequently in this article, good practices include the proper enclosing of tags, suitable indentation to enhance code readability, and so on.

If you need more information about good practi ces when using JavaScript, feel free to check out the creator of JSLint, Douglas Crockford, at http://crockford.com.. Or you can read up John Resigs blog (the creator of JQuery) at http://ejohn.org. Both are great guys who know what great JavaScript is about.

Validation

To summarize the above sections, the DOM is provided by HTML, and both CSS and JavaScript are applied to the DOM. This means that if there is an invalid DOM, there is a chance that the JavaScript that is operating on the DOM (and sometimes the CSS) might result in errors.

With this summary in mind, we'll focus on how you can spot validation errors by using color coding editors.

JavaScript Testing Beginner's Guide Test and debug JavaScript the easy way.
Published: August 2010
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

(For more resources on JavaScript, see here.)

Color-coding editors–how your editor can help you to spot validation errors

If you are an experienced coder, you may skip this section; if not, you might want to understand the value of a good coding editor.

In general, a good editor can help you to prevent validation errors. Based on our understanding of what validati on is, you should understand that your editor should do the following activities:

  • Highlight matching brackets
  • Multiple syntax highlighting
  • Auto indentation after keywords, brackets, and others
  • Auto completion of syntax
  • Auto completion of words that you have already typed

You may have noticed that I have left out a few points, or added a few points, as to what a good editor should do. But in general, the points listed previously are meant to help you prevent validation errors.

As a start, you can consider using Microsoft s SharePoint Designer 2007, a free, feature-rich, HTML, CSS ,and JavaScript editor, which is available at http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=baa3ad86-bfc1-4bd4-9812-d9e710d44f42

For example, highlighting matching brackets is to ensure that your code is properly enclosed with brackets, and auto indentation is to ensure that you are using consistent spacing for your code blocks.

Although JavaScripts code blocks are often denoted by the use of curly brackets, it is important that we use indentation to visually display the structure of the code. Consider the following code snippets:

function submitValues(elementObj){
var digits = /^\d+$/.test(elementObj.value);
var characters = /^[a-zA-Z\s]*$/.test(elementObj.value);
if(elementObj.value==""){
alert("input is empty");
return false;
}
else if(elementObj.name == "enterNumber" && digits == false){
alert("the input must be a digit!");
debuggingMessages(arguments.callee.name, elementObj, "INPUT
must be digit");
return false;
}
else if(elementObj.name == "enterText" && characters == false){
alert("the input must be characters only!");
return false;
}
else{
elementObj.disabled = true;
return true;
}
}

The next code snippet is as follows:

function submitValues(elementObj)
{
var digits = /^\d+$/.test(elementObj.value);
var characters = /^[a-zA-Z\s]*$/.test(elementObj.value);
if(elementObj.value=="")
{alert("input is empty");
return false;
}
else if(elementObj.name == "enterNumber" && digits == false)
{alert("the input must be a digit!");
return false;
}else if(elementObj.name == "enterText" && characters == false)
{alert("the input must be characters only!");
return false;
}
else
{
elementObj.disabled = true;
return true;
}
}

I am quite sure that you would find the second code snippet to be messy, as it has inconsistent indentation, and you may have problems figuring out which statement belongs to which conditional block.

Stylistically speaking, the second code sample is what we call "poor code style". You will be surprised that this might lead to validation errors.

In case you are wondering what /^[a-zA-Z\s]*$/ and /^\d+$/ are, they are actually regular expression objects. Regular expressions originated from Perl (a programing language) and, due to their usefulness, many programing languages now have ther own form of regular expressions. Most of them work in the same way. If you wish to find out more about regular expressions for JavaScript, feel free to visit http://www.w3schools.com/jsref/jsref_obj_regexp.asp for a brief introduction to how regular expressions work.

Common errors in JavaScript that will be picked up by validation

I'll briefly mention some of the most common validation errors that are picked up by validators. Following is a short list of them:

  • Inconsistent spacing or indentation
  • Missing semi colons
  • Missing closing brackets
  • Using a function or variable that is not declared at the point of being called or referenced

You may have noticed that some of the validation errors are not exactly "errors"—as in syntax errors—but rather stylistic ones. As mentioned in the previous sections, differences in coding style do not necessarily lead to functional errors but rather stylistic errors. But the good thing about good coding style is that it often leads to less errors.

At this point, it might be difficult for you to visualize what these common errors actually look like. But don't worry, you will get to see such validati on errors in action when we introduce the JavaScript validation tools.

JSLint–an online validator

JSLint is the first JavaScript validation code that we will focus on. You can access JSLint by visiting this URL: http://www.jslint.com.

Douglas Crockford works at Yahoo! as a JavaScript architect. He is also a member of the committee that designs future versions of JavaScript. His views on JavaScript style and coding practices are generally agreed upon . You can read more about him and his ideas at his website:http://www.crockford.com

In general, JSLint is an online JavaScript validator. It helps to validate your code. At the same time, JSLint is smart enough to detect some forms of code errors, such as infinite loops. The JSLint website is not a particularly large website, but nonetheless, two important links that you must read are as follows:

Time for action – using JSLint to spot validation errors

As mentioned earlier, well test the file named perfect-code-for-JSLint.html. found in the source code folder.The steps are as follows:

  1. Open up your web browser and navigate to http://www.jslint.com. You should see the home page with a huge text area. This is the area where you are going to copy and paste your code.
  2. Go to the source code folder and open the file named getting-values-in-right-places-complete.html. Then, copy and paste the source code into the text area mentioned in step 1.
  3. Now click on the button with the name JSLint.

    Your page should refresh almost immediately, and you will receive some form of feedback. You may have noticed that you received many (yes, a lot of) validation errors. And, most probably, some of them do not make sense to you. However, you should be able to identify that some of the validation errors were introduced in the section on common JavaScript validation errors.

    Now, scroll further down and you should see the following phrase in the feedback area:

    xx % scanned
    too many errors

    This tells you that JSLint has only scanned a part of the code and stopped scanning the code because there were too many errors. What can we do about this? What if there are too many validation errors and you cannot spot all of them in one go? Do not worry, as JSLint is robust and has option settings, which are found at http://www.jslint.com/#JSLINT_OPTIONS (this is actually found at the bottom of the home page of JSLint). One of the options that requires your input is the maximum number of errors. For our purposes, you may want to enter an insanely large number, such as 1,000,000.

  4. After step 3, you have now officially selected the options known as The Good Parts by the author of this tool. This is a setting that automatically sets what the author feels are the most important validation checks.

    These options include: Strict white space, allow one var statement per function, and so on.

  5. Now click on the JSLint button. Your browser will show the new validated result. Now you may take a look at the types of validation errors that have been detected by JSLint.

What just happened?

You have just used JSLint to spot for validation errors. This is a simple process for JSLint: copy and paste your code into the text area and click on JSLint. Do not be surprised that there are so many validation errors; we are just starting out and we will learn how to fix and avoid such validation errors.

You may have noticed that the JavaScript that is embedded in the HTML form results in an error that says missing use strict statement. This error stems from the fact that JSLint believes in the use of the use strict statement, which allows the code to run under strict conditions.

You will continue to see many errors. In my opinion, this is evidence that valid code is not easy to achieve; but this is what we will achieve in the next section.

As you have seen, there are various validation options, and at this stage, it is good enough if we pass the set requirements for The Good Parts. Therefore, well focus on how to fix these validation errors in the next section. But before that, I'll quickly discuss the valid code constructs that produce validation warnings.

JavaScript Testing Beginner's Guide Test and debug JavaScript the easy way.
Published: August 2010
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

(For more resources on JavaScript, see here.)

Valid code constructs that produce validation warnings

You may have noticed that although our code construct is valid, it has produced validation warnings. You may be wondering if you should fix these or not. Here's some basic discussion to help you to decide.

Should you fix valid code constructs that produce validation warnings?

This depends on your objective. A code should at least be correct and work the way that we intend it to. Therefore, if your objective is to just create functionally-correct code, then you might not want to spend the time and effort to correct those validation warnings.

However, it is very likely that you want to learn how to test JavaScript, and validation is an important part of testing JavaScript as you will see later in this article.

What happens if you don't fix them

The main issue with invalidated code is that it will be much more difficult to maintain the code, in terms of readability and scalability. This problem becomes enhanced when you are working in teams and others have to read or maintain your code.

Valid code promotes good coding practices, which will help you to avoid problems down the road.

How to fix validation errors

This section will continue with the errors mentioned in the previous section, and together we'll attempt to fix them. Wherever possible, I'll provide some form of explanation as to why a particular piece of code is rendered as invalid. At the same time, the whole process of writing valid and functionally-code can be cumbersome. Therefore, I'll start off with validation errors that are much easier to fix, before I move on to tougher ones.

As we go along fixing the validation errors that we saw in the previous section, you may realize that fixing validation errors may require some form of compromise as to how you write your code. For example, you will understand that using alert() sparingly in your code is not considered a good coding style, at least according to JSLint. In this case, you will have to consolidate all of your alert() statements and group them into a function, while still maintaining the functionality of your code. More importantly, you will also realize that (perhaps) the best way to write valid code is to start writing valid code right from the first line of the code; you will see that correcting invalid code is an extremely tedious process, and there are times when you can only minimize your validation errors.

Along the way, you will get the chance to practice important JavaScript functions and, at the same time, learn how to code in a better style. Thus, this is probably the most important section of this article and I urge you to get your hands dirty with me. Before I get started on fixing the code, I'll first summarize the types of errors that are spotted by JSLint.

  • Missing "use strict" statement
  • Unexpected use of ++
  • Missing space after ), value, ==, if, else, +
  • Function names (such as debuggingMessages) are not defined or a function was used before it was defined
  • Too many var statements
  • === used instead of ==
  • alert is not defined
  • <\/ used instead of <!--
  • HTML event handlers used

Without further ado, well get started with the first validation error: use strict.

Error—missing "use strict" statement

The "use strict" statement is a relatively new feature in JavaScript that allows our JavaScript to run in a strict environment. In general, it catches little-known errors, and "forces" you to write stricter and valid code. John Resig, an expert in JavaScript, has written a nice summary about this topic, and you can read about it by following this link: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/.

Time for action – fixing "use strict" error

This error is extremely easy to fix. But be careful; enabling use strict may prevent your code from working, if your code is not valid. Here's how we can fix this validation error:

  1. Open up your text editor, copy and paste the same code that we have been using, and append the following code snippet on the first line of your JavaScript code:


    "use strict";

  2. Save your code and test it out on JSLint. You will see that the error is now gone.

You may notice that there is another missing use strict error that is related to your HTML form; do not worry, we will fix that in a later sub-section of this article. Now let us move on to the next error.

Error—unexpected use of ++

There is nothing programmatically wrong with this line of code. What we intend to achieve by using ++ is to increment globalCounter whenever the function addResponseElement() is called.

However, JSLInt believes that there is a problem with using ++. Take the following code snippets as an example:


var testing = globalCounter++ + ++someValues;
var testing2 = ++globalCounter + someValues++;

The previous statements would look confusing to most programmers and hence it is considered bad style. More importantly, both of these statements are programmatically different and produce different results. For these reasons, we need to avoid statements like ++, --, and so on.

Time for action – fixing the error of "Unexpected use of ++"

This error is relatively easy to fix. All we need to do is avoid ++. So navigate to the addResponseElement() function, and look for globalCounter++. Then change globalCounter++ to globalCounter = globalCounter + 1. So, now your function has changed from this:

function addResponseElement(messageValue, idName){
globalCounter++;
var totalInputElements = document.testForm.length;
debuggingMessages(addResponseElement ","empty", "object is a
value");
var container = document.getElementById('formSubmit');
container.innerHTML += "<input type=\"text\" value=\""
+messageValue+ "\"name=\""+idName+"\" /><br>";
if(globalCounter == totalInputElements){
container.innerHTML += "<input type=\"submit\" value=
\"Submit\" />";
}
}

To this:

function addResponseElement(messageValue, idName) {
globalCounter = globalCounter + 1;
debuggingMessages( "addResponseElement ", "empty", "object is a
value");
document.getElementById('formSubmit').innerHTML += "<input
type=\"text\" value=\"" + messageValue + "\"name = \"" + idName + "\"
/><br>";
if (globalCounter === 7) {
document.getElementById('formSubmit').innerHTML += "<input
type=\"submit\" value=\"Submit\" />";
}
}

Compare the highlighted lines, and you will see the change in the code. Now let us move on to the next error.

Error—functions not defined

This error is caused by the way that JavaScript engines and web pages are being rendered by web browsers. Web pages (and JavaScript) are being parsed from top to bottom on the client side. This means that anything that appears at the top will be read first, followed by that at the bottom.

Time for action – fixing the error of "Functions not defined"

  1. Because this error is caused by the incorrect flow of the JavaScript functions, we will need to change the sequence of the functions. What we have done in, is that we wrote the functions that we will be using first. This may be incorrect, as the functions may require data or functions that are only defined in later parts of the JavaScript code. Here's a very simplified example:

    <script>
    function addTWoNumbers() {
    return numberOne() + numberTwo();
    }
    function numberOne(x, y) {
    return x + y;
    }
    function numberTwo(a, b){
    return a + b;
    }
    </script>

  2. Based on the previous code snippet, you will realize that addTwoNumbers() requires data returned from numberOne() and numberTwo(). The issue here is that the JavaScript interpreter will read addTwoNumbers() first before reading numberOne() and numberTwo(). However, both numberOne() and numberTwo() are being called by addTwoNumbers(), resulting in an incorrect flow of code.

    This means that in order for our code to work correctly, we will need to rearrange the order of the functions. Continuing with the previous example, this is what we should do:

    <script>
    function numberOne(x, y) {
    return x + y;
    }
    function numberTwo(a, b){
    return a + b;
    }function addTWoNumbers() {
    return numberOne() + numberTwo();
    }
    </script>

    In the previous code snippet, we have rearranged the sequence of the functions.

  3. Now, we are going to rearrange the function's sequence. For our purposes, all that we need to do is to arrange our functions such that the first function that originally appeared in our code will now be the last, and the last function will be the first. Similarly, the second function that originally appeared in the JavaScript code will now be the second-to-last function. In other words, we will reverse the order of the code.
  4. Once you have reversed the order of the functions, save the file and test the code on JSLint. You should notice that the validation errors relating to functions not being defined are now gone.

Now, let us move on to the next validation error.

Too many var statements

According to JSLint, we have used too many var statements. What does this mean? This means that we have used more than one var statement in each function; in our case we have obviously used more than one var statement in each and every function.

How did this happen? If you scroll down and check the settings of JSLint, you will see a checkbox selected that says Allow one var statement per function. This means that the maximum number of var we can use is one.

Why is this considered to be good style? Although many coders may think that this is cumbersome, the author of JSLint would most probably believe that a good function should do only one thing. This would typically mean operating on only one variable.

There's certainly room for discussion, but as we are all here to learn, let us get our hands dirty by fixing this validation error.

Time for action – fixing the error of using too many var statements

In order to fix this error, we will need to do some form of code refactoring. Although code refactoring typically means consolidating your code for it to become more concise (that is, shorter code), you may realize that refactoring your code to fit validation standards is a lot of work.

  1. What we will do in this section is that we will change (almost) all single var statements that save a value into a function.

    The code that is mainly responsible for this particular validation error is found checkForm function. The statements that we will need to refactor are as follows:

    var totalInputElements = document.testFormResponse.length;
    var nameOfPerson = document.testFormResponse.nameOfPerson.value;
    var birth = document.testFormResponse.birth.value;
    var age = document.testFormResponse.age.value;
    var spending = document.testFormResponse.spending.value;
    var salary = document.testFormResponse.salary.value;
    var retire = document.testFormResponse.retire.value;
    var retirementMoney = document.testFormResponse.retirementMoney.
    value;
    var confirmedSavingsByRetirement;
    var ageDifference = retire - age;
    var salaryPerYear = salary * 12;
    var spendingPerYear = spending * 12;
    var incomeDifference = salaryPerYear - spendingPerYear;

  2. Now we'll start to refactor our code. For each of the variables defined, we need to define a function with the following format:

    function nameOfVariable(){
    return x + y; // x + y represents some form of calculation
    }

    I'll start off with an example. For instance, for totalInputElements this is what I will do:

    function totalInputElements() {
    return document.testFormResponse.length;
    }

  3. Based on the previous code, do something similar to what you are going to see here:

    /* here are the function for all the values */
    function totalInputElements() {
    return document.testFormResponse.length;
    }
    function nameOfPerson() {
    return document.testFormResponse.nameOfPerson.value;
    }
    function birth() {
    return document.testFormResponse.birth.value;
    }
    function age() {
    return document.testFormResponse.age.value;
    }
    function spending() {
    return document.testFormResponse.spending.value;
    }
    function salary() {
    return document.testFormResponse.salary.value;
    }
    function retire() {
    return document.testFormResponse.retire.value;
    }
    function retirementMoney() {
    return document.testFormResponse.retirementMoney.value;
    }
    function salaryPerYear() {
    return salary() * 12;
    }
    function spendingPerYear() {
    return spending() * 12;
    }
    function ageDifference() {
    return retire() - age();
    }
    function incomeDifference() {
    return salaryPerYear() - spendingPerYear();
    }
    function confirmedSavingsByRetirement() {
    return incomeDifference() * ageDifference();
    }
    function shortChange() {
    return retirementMoney() - confirmedSavingsByRetirement();
    }
    function yearsNeeded() {
    return shortChange() / 12;
    }
    function excessMoney() {
    return confirmedSavingsByRetirement() - retirementMoney();
    }

Now, let us move on to the next error.

Expecting <\/ instead of <\

For most of us, this error is probably one of the most intriguing. We have this validation error because the HTML parser is slightly different to the JavaScript interpreter. In general, the extra backslash is being ignored by the JavaScript compiler, but not by the HTML parser.

Such validation errors may appear unnecessary, but Doug Crockford knows that this has some form of impact on our web page. Therefore, let us move on to how to fix this error.

Time for action – fixing the expectation

Although this error is one of the most intriguing, it is one of the easiest to fix. All that we need to do is to find all of the JavaScript statements that contain <!-- and change them to <\/. The function that is mainly responsible for this error is buildFinalResponse().

  1. Scroll down to the function buildFinalResponse(), and change all statements that have </ to <\/. After you are done, you should have the following code:

    function buildFinalResponse(name, retiring, yearsNeeded, retire,
    shortChange) {
    debuggingMessages(buildFinalResponse ", -1, "no messages");
    var element = document.getElementById("finalResponse");
    if (retiring === false) {
    element.innerHTML += "<p>Hi <b>" + name + "<\/b>,<\/p>";

    element.innerHTML += "<p>We've processed your information
    and we have noticed a problem.<\/p>";

    element.innerHTML += "<p>Base on your current spending
    habits, you will not be able to retire by <b>" + retire + " <\/b>
    years old.<\/p>";

    element.innerHTML += "<p>You need to make another <b>" +
    shortChange + "<\/b> dollars before you retire inorder to acheive
    our goal<\/p>";

    element.innerHTML += "<p>You either have to increase your
    income or decrease your spending.<\/p>";
    }
    else {
    // able to retire but....
    //alertMessage("retiring === true");

    element.innerHTML += "<p>Hi <b>" + name + "<\/b>,<\/p>";
    element.innerHTML += "<p>We've processed your information
    and are pleased to announce that you will be able to retire on
    time.<\/p>";
    element.innerHTML += "<p>Base on your current spending
    habits, you will be able to retire by <b>" + retire + "<\/b>years
    old.<\/p>";
    element.innerHTML += "<p>Also, you'll have' <b>" +
    shortChange + "<\/b> amount of excess cash when you retire.<\/p>";
    element.innerHTML += "<p>Congrats!<\/p>";
    }
    }

Notice that all </ have been changed to <\/. You may also want to search through the code and see if any such errors are remaining.

Now, with this error fixed, we can move on to the next validation error.

Expected '===' but found '=='

In JavaScript and in most programing languages, == and === are significantly different. In general, === is stricter than ==.

The key difference between === and == in JavaScript is that === is a strict equal operator and it will return a Boolean true if, and only if, both the operands are equal and of the same type. On the other hand, the == operator returns a Boolean true if both the operands are equal, even if they are of different types.

According to JSList, === should be used when comparing a variable to a truth value, because it is stricter than ==. In terms of code strictness, JSLint is certainly correct in ensuring code quality. Therefore, let us now correct this error.

Summary

In the above article, we have covered the following topics in detail:

  • The difference between validating and testing
  • How a good code editor can help you spot validation errors
  • What makes a code quality code
  • Why do we need HTML and CSS to be valid before we start working on JavaScript
  • Why JavaScript embedded in HTML may be reported as invalid
  • Common JavaScript errors that are detected by validating
  • JSLint and JavaScript Lint—how to use it to check your code
  • Valid code constructs that produce validation warnings
  • How to fix validation errors that are spotted by JSLint

Further resources on this subject:


About the Author :


Yuxian Eugene Liang

Eugene enjoys solving difficult problems creatively in the form of building web applications using Python/Django and JavaScript/JQuery. He also enjoys doing research related to the areas of recommendation algorithms, link analysis, data visualization, data mining, information retrieval, business intelligence, and intelligent user interfaces. He has recently started a personal blog at http://www.liangeugene.com

Books From Packt


JSF 2.0 Cookbook
JSF 2.0 Cookbook

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

YUI 2.8: Learning the Library
YUI 2.8: Learning the Library

Object-Oriented JavaScript
Object-Oriented JavaScript

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

Learning Ext JS 3.0
Learning Ext JS 3.0

JSF 1.2 Components
JSF 1.2 Components

Alfresco 3 Web Content Management
Alfresco 3 Web Content Management


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software