20.1. Basic JavaScript Syntax

JavaScript follows a fairly basic syntax that can be outlined with a few simple rules:

  • All code should appear within appropriate constructs, namely between <script> tags or within event attributes. (Events are discussed in the "Event Handling" section later in this chapter.)

  • With few exceptions, code lines should end with a semicolon (;). Notable exceptions to this rule are lines that end in a block delimiter ({ or }).

  • Blocks of code (usually under control structures such as functions, if statements, and so on) are enclosed in braces ({ and }).

  • Although it is not absolutely necessary, explicit declaration of all variables is a good idea.

  • The use of functions to delimit code fragments is recommended; it increases the ability to execute those fragments independently from one another and encourages reuse of code. (Functions are discussed in the "User-Defined Functions" section later in this chapter.)

  • Comments can be inserted in JavaScript code by prefixing the comment with a double-slash (//) or surrounding the comment with /* and */ pairs. In the former case (//), the comment ends at the next line break. Use the latter case for multiline comments.

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.