HTML and CSS Reference

In-Depth Information

EXAMPLE
5.1

<html>

<head><title>First JavaScript Sample</title>

<script type = "text/javascript">

1

var result = 5 + 4 * 12 / 4;

</script>

</head>

<body bgcolor="yellow" text="blue">

<big>

<script type="text/javascript">

2

document.write("result = " + result,"<br />");

</script>

</big>

</body>

</html>

EXPLANATION

1

The order of associativity is from left to right. Multiplication and division are of a

higher precedence than addition and subtraction, and addition and subtraction

are of higher precedence than assignment. To illustrate this, we'll use parentheses

to group the operands as they are grouped by JavaScript. In fact, if you want to

force precedence, use the parentheses around the expression to group the oper-

ands in the way you want them evaluated. The following two examples produce

the same result:

var result = 5 + 4 * 12 / 4;

could be written

result = (5 + ( ( 4 * 12 ) / 4));

2

The expression is evaluated and the result is assigned to variable,
result
. The value

of
result
is displayed on the browser (see Figure 5.1).

Figure 5.1
Output from Example 5.1: Precedence and associativity.