HTML and CSS Reference
In-Depth Information
EXAMPLE
3.7 (
CONTINUED
)
</body>
</html>
Output:
3
25 cats
4
almost 25
5
29
6
510 years
7
30 dogs
8
dogs255
EXPLANATION
1
Variable
x
is assigned a number.
2
Variable
y
is assigned the string
510 years
. If the + operator is used, it could mean
the concatenation of two strings or addition of two numbers. JavaScript looks at
both of the operands. If one is a string and one is a number,
the number is con-
verted to a string
and the two strings are joined together as one string, so in this
example, the resulting string is
510 years
. If one operand were
5
and the other
10
,
addition would be performed, resulting in
15
.
3
A number is concatenated with a string. The number
25
is converted to a string
and concatenated to
“ cats”
, resulting in
25 cats
. (Note that the
write()
method can
also use commas to separate its arguments. In these examples the <
br
> tag is not
concatenated to the string. It is sent to the
write()
method and appended.)
4
This time, a string is concatenated with a number, resulting in the string
almost 25
.
5
When the operands on either side of the + sign are numbers, addition is per-
formed.
6
The value of
y
, a string, is displayed.
7
The + operators works from left to right. Because
x
and
y
are both numbers, addi-
tion is performed,
25 + 5. 30
is concatenated with the string
“ dogs”
.
8
Because the + works from left to right, this time the first operand is a string being
concatenated to a number, the number is converted to string
dogs25
and concat-
enated with string
5
.
The weather and moods are variable; time is constant, and so are the speed of light, mid-
night,
PI
, and
e
. In programming, a constant is a special kind of placeholder with a value
that cannot be changed during program execution. Many programming languages use a
special syntax to define a constant to distinguish it from a variable. JavaScript declares
constants with the
const
type (which replaces
var
) and the name of the constant is in