O'Reilly logo

Learning JavaScript, 2nd Edition by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Operators and Statements

The examples I’ve shown you so far in the book have performed mostly simple tasks: we’ve defined a variable and set its value, printed a value in the page or in an alert box, and modified a variable through addition or multiplication or some other means. All of these examples use JavaScript statements and operators.

JavaScript features a number of different statement types: assignment, function call, conditional, and loop. Each is fairly intuitive, simple to use, and quick to learn. However, in JavaScript, as in other programming languages, although the statements are easy to learn, lining them up one after the other so that they do something useful can be tricky.

The Format of a JavaScript Statement

JavaScript statements usually end with a semicolon, but as I mentioned in earlier chapters, a semicolon is not required. If the application that processes the JavaScript determines that a statement is complete (by whatever criteria exist for each type of statement) and the line ends with a line break, you can omit the semicolon:

var bValue = true
var sValue = "this is also true"

If multiple statements appear on the same line, though, you must use the semicolon to terminate each one:

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. For instance, if you use a tool to compress the whitespace in your JavaScript code, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required