Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

70 CHAPTER 3 Getting started with JavaScript


Using unary operators
When an operator requires two operands, it’s a binary operator. Examples of binary operators
are plus, minus, multiply, divide, and modulo. Some operators, called unary operators, require
only a single operand. One unary operator is the typeof operator, which requires a single
operand and returns a string that indicates the operand’s type, as follows:
typeof 'Hello World'
typeof 19.5
typeof true

In the three examples, the first example returns ‘string’, the second example returns ‘num-
ber’, and the third example returns ‘Boolean’.
In addition to being binary operators, the plus and minus signs can also be used as unary
operators, as in the following examples:
+23
-49

In these examples, the plus and minus signs are being used as unary operators to specify
the signs of the numbers.

Understanding the Boolean type
The Boolean type can contain the values true and false. Although you can use these values
directly, it’s more common to produce a true or false value by comparing two values, as
shown in the following examples that use the less-than (<) and greater-than (>) signs:
10 < 9
20 > 3

The first example produces a false value, whereas the second example produces a true
value. The next examples use the less-than-or-equal-to (<=) sign and the greater-than-or-
equal-to (>=) sign:
5 <= 4
7 >= 8

The first expression evaluates to false, and the second expression evaluates to false. You
can also use the equals (==) and not equals (!=) operators, as shown in the following example:
'Apples' != 'Oranges'
10 == 13 - 3

Both of these expressions evaluate to true.

LOGICAL OPERATORS
JavaScript provides three logical operators: and (&&), or (||), and not (!). These operators can
be used in expressions to produce a Boolean value. The and operator will produce a true
value if both operands evaluate to true; else it produces a false value. The or operator will
produce a true value if either operand evaluates to true; else it produces a false value. The not
Free download pdf