Code layout

I mentioned earlier that white space (spaces, tabs, and so on) does not affect the execution of JavaScript code. The best advice is to use white space to make code more readable. The method I use is to indent code blocks by one tab space (some programmers use three spaces), and to keep statements to one per line as much as possible. Code blocks are indented to separate them from other blocks of code, which becomes particularly important when you have nested blocks. Consider the following example:

var answer=prompt("Is the column helpful?");
if(answer=="yes")
alert("Thank you for your feedback!");
else if (answer =="no")
{if(prompt("Is the course moving too fast?") == "yes")
alert("Thank you for your feedback!");
else alert("Thank you for your feedback!");}
else alert("I'm sorry, but I didn't understand that.");

Following the code is extremely difficult; under what condition will the last else statement be executed? By indenting each code block, the conditions line up vertically. In the case of a conditional statement, if the conditional is false, the else statement is easy to find - it is vertically aligned with the conditional. Properly laid out, the above code is:

var answer=prompt("Is the column helpful?");

if(answer=="yes")
alert("Thank you for your feedback!");
else if (answer =="no)
    {
    if(prompt("Is the course moving too fast?") == "yes")
        alert("Thank you for your feedback!");
    else
        alert("Thank you for your feedback!");
    }
else
    alert("I'm sorry, but I didn't understand that.");

Looking at this layout, it is clearer that the last statement is executed only when the original prompt() method isn't either 'yes' or 'no'.

Finally, if you look at other source codes, you are likely to see another method of layout. Many programmers will place brackets on the line that requires them, such as:

for(x=0; x<10; x++){
	statement_1;
	another_statement;
}
next_statement;

This is done to keep the length of the code shorter to look at. Since spaces have no effect on program size or program execution speed, it is entirely a matter of preference.