ptg16476052
The JavaScript Language 479
17
That’s the string representation of the document object. Many programming languages
would print an error if you tried to use an object like document with a method that
accepts a string. Not JavaScript. It makes do with what you give it.
Operators and Expressions
In my introduction to the JavaScript Console in the Chrome Web Developer Tools, I
talked a bit about expressions. An expression is a snippet of code that can be evaluated
to return a result. You may recognize the term expression from math, and indeed, many
expressions are mathematical expressions. Here’s a simple mathematical expression that
you can enter in the Console:
10 * 50
In this case, JavaScript will multiply 10 by 50. That’s an expression. There are also string
expressions. For example, you can use the + operator to join strings together, like this:
"The bird a nest," + " the spider a web," + " man friendship."
Expressions are built using operators. You’ve already seen a couple: * for multiplication
and + for combining strings or adding numbers. Table 17.1 lists more operators provided
by JavaScript, along with examples. (For a full list of all the supported operators, refer t o
the online JavaScript documentation.)
TABLE 17.1 JavaScript Operators and Expressions
Operator Example Description
5 + 5 Adds the two numeric values; the result is 10.
"Java" + "Script"Combines the two string values; the result is JavaScript.
- 10 - 5 Subtracts the second value from the first; the result is 5.
- 5 * 5 Multiplies the two values; the result is 25.
/ 25 / 5 Divides the value on the left by the value on the right; the
result is 5.
% 26 % 5 Obtains the modulus of 26 when it’s divided by 5. (Note:
A modulus is a function that returns the remainder.) The
result is 1.
There are many other operators, too. All the examples here used literal values in the
expressions, but there are other options as well. You can use values returned by methods
in expressions if you choose, as in the following example:
Math.sqrt(25) - Math.sqrt(16)