Expressions and Statements in JavaScript

In Chapter 1, we made values and applied operators to them to get new values. Creating values like this is the main substance of any JavaScript pro­gram. But that substance has to be framed in a larger structure to be useful. So that’s what we’ll cover next.

A fragment of code that produces a value is called an expression. Every value that is written literally (such as 22 or “psychoanalysis”) is an expression. An expression between parentheses is also an expression, as is a binary oper­ator applied to two expressions or a unary operator applied to one.

This shows part of the beauty of a language-based interface. Expres­sions can contain other expressions in a way similar to how subsentences in human languages are nested—a subsentence can contain its own subsen­tences, and so on. This allows us to build expressions that describe arbitrar­ily complex computations.

If an expression corresponds to a sentence fragment, a JavaScript state­ment corresponds to a full sentence. A program is a list of statements.

The simplest kind of statement is an expression with a semicolon after it. This is a program:

1;

!false;

It is a useless program, though. An expression can be content to just produce a value, which can then be used by the enclosing code. A state­ment stands on its own, so it amounts to something only if it affects the world. It could display something on the screen—that counts as changing the world—or it could change the internal state of the machine in a way that will affect the statements that come after it. These changes are called side effects. The statements in the previous example just produce the values 1 and true and then immediately throw them away. This leaves no impression on the world at all. When you run this program, nothing observable happens.

In some cases, JavaScript allows you to omit the semicolon at the end of a statement. In other cases, it has to be there, or the next line will be treated as part of the same statement. The rules for when it can be safely omitted are somewhat complex and error-prone. So in this book, every statement that needs a semicolon will always get one. I recommend you do the same, at least until you’ve learned more about the subtleties of missing semicolons.

Source: Haverbeke Marijn (2018), Eloquent JavaScript: A Modern Introduction to Programming,

No Starch Press; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *