HTML and CSS Reference
In-Depth Information
EXAMPLE 5.2
<html>
<head>
<title>Precedence and Associativity</title>
</head>
<body>
<h3>
<script type = "text/javascript">
1
var x = 5 + 4 * 12 / 4;
2
document.writeln( "The result is " + x + "<br />");
3
var x = ( 5 + 4 ) * ( 12 / 4 );
4
document.writeln("The result is " + x );
</script>
</h3>
</body>
</html>
EXPLANATION
1
The variable, called x , is assigned the result of the expression.
var x = 5 + 4 * 12 / 4;
results in
x=5+48/4
results in
x=5+12
results in
17
Because multiplication and division are higher on the precedence table than addi-
tion, those expressions will be evaluated first, associating from left to right.
2
The result of the previous evaluation, the value of x , is sent to the browser.
3
The expressions enclosed in parentheses are evaluated first and then multiplied.
var x = ( 5 + 4 ) * ( 12 / 4 );
results in
x=9*3
results in
27
4
The result of the previous evaluation, the value of x , is sent to the browser. The
output of the script is shown in Figure 5.2.
Search WWH ::




Custom Search