Chapter 3. Operators and Statements

The examples in the book so far have performed mostly simple tasks: a variable has been defined and its value set; a value is printed out in the page or in an alert window; a variable is modified through addition or multiplication or some other means. These all use JavaScript statements and operators.

There are a number of different types of statements in JavaScript: assignment, function call, conditional, and loops. Each is fairly intuitive, simple to use, and quick to learn. A snap, really. As with with most programming languages, in JavaScript the statements are easy to learn; the tricky part is lining them up, one after the other, so they do something useful.

This chapter takes a closer look at statements and operators, what they share, and how they differ.

Format of a JavaScript Statement

JavaScript 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 ...

Get Learning JavaScript 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.