How to code JavaScript statements
The syntax of JavaScript refers to the rules that you must follow as you code JavaScript statements. If you don't adhere to one or more of these rules, your web browser won't be able to interpret and execute your statements. These rules are summarized in figure 2-5.
The first syntax rule is that JavaScript is case-sensitive. This means that uppercase and lowercase letters are treated as different letters. For example, the names salestax and salesTax are treated as different words.
The second syntax rule is that JavaScript statements must end with a semicolon. If you don't end each statement with a semicolon, JavaScript won't be able to tell where one statement ends and the next one begins.
The third syntax rule is that JavaScript ignores extra whitespace in statements. Whitespace includes spaces, tabs, and new line characters. This lets you break long statements into multiple lines so they're easier to read. As far as JavaScript is concerned, your entire program could be written on one line and it would still work. However, that would result in code that would be extremely difficult for humans to read.
The last two syntax rules are that single-line comments can be added with two forward slashes and multi-line comments can be added between the /* and */ characters. Comments let you add descriptive notes to your code that are ignored by the JavaScript engine. Later on, these comments can help you or someone else understand the code if it needs to be updated.
Although semicolons are required at the end of a statement, JavaScript will try to help you out if you forget one. For instance, JavaScript will automatically add a semicolon at the end of a line if doing so will create a valid statement. Unfortunately, this usually causes more problems than it solves.
The problem usually occurs when you split a long statement are two lines in the wrong location. The result is that one statement is treated as two shorter statements that produce the wrong results. However, you can avoid this type of problem by following the guidelines in this figure for splitting a long statement.
This problem is illustrated by the two examples in this figure. In the first one, JavaScript will add a semicolon after the word return, which will cause an error. In the second one, because the statement is split after an assignment operator, JavaScript won't add a semicolon so the statement will work correctly.
The basic syntax rules for JavaScript
A single-line comment
nextYear = thisYear + 1; // Determine what the next year is
A multi-line comment
/* The following line determines what thenext year is by adding 1 to the current year*/nextYear = thisYear + 1;
How to split a statement across multiple lines
A split statement that results in an error
return"Hello";
A split statement that works correctly
nextYear =thisYear + 1;
Description
Figure 2-5 How to code JavaScript statements