3.1. Format of a JavaScript StatementJavaScript statements terminate with a semicolon, though not all statements need the terminator expressly given. If the JavaScript engine determines that a statement is complete (whatever that is for each type of statement), and the line ends with a new line character, the semicolon can be omitted: var bValue = true var sValue = "this is also true" If multiple statements are on the same line, though, the semicolon must be used to terminate each: var bValue = true; var sValue = "this is also true" However, not explicitly terminating each JavaScript statement is a bad habit to get into, and one that can result in unexpected consequences. As such, the use of the semicolon to terminate JavaScript statements is a JavaScript best practice.
The use of whitespace in JS has little impact on the code. For instance, the following two lines of code are interpreted exactly the same: var firstName = 'Shelley' ; var firstName = 'Shelley'; Other than to delimit words within quotes or to terminate statements, extra whitespacesuch as tabs, spaces, and new linesis disregarded. In the following code, the variable assignment completes successfully, even though there is a line terminator separating the statement: var firstName = 'Shelley'; alert(firstName); The engine didn't interpret the end-of-line character as a statement terminator in this instance because it evaluated the code and determined that it was incomplete. The JavaScript engine continues to process what it finds until either the semicolon is reached or until a statement is completed. In the case of the assignment statement, this state is reached when the right-side expression of the statement is provided. Deciding whether to interpret an end-of-line terminator as a statement terminator is all a part of JavaScript's forgiving nature: JavaScript works on the side of successfully processing the code and does whatever is needed to facilitate this. Well, unless doing so introduces confusion. In the following code: var firstName = var lastName = 'Powers'; The JavaScript engine returns an error because the second line doesn't evaluate to a correct right-side assignment. Returning to the discussion of whitespace, indentation is used throughout the book to make the examples more readable, but there's no programmatic reason to indent a line with a tab or spaces. The same holds true for whitespace surrounding operators such as assignment (=) or one of the math operators (such as +). Whitespace isn't necessary. Whitespace and comments, as well as meaningful identifiers, are there to make the code easier to maintain.
Figure 3-1. Packer, a JavaScript compression service |