Java Reference
In-Depth Information
The calculation of the expression on the right‐hand side of the equals sign raises a number of important
points. First, just as in math, the JavaScript equation is read from left to right, at least for the basic math
functions like +, , and so on. Secondly, as you saw earlier, just as there is precedence in math, there is
precedence in JavaScript.
Starting from the left, first JavaScript works out 5/9 = .5556 (approximately). Then it comes
to the multiplication, but wait… the last bit of your equation, degFahren - 32 , is in parentheses.
This raises the order of precedence and causes JavaScript to calculate the result of degFahren - 32
before doing the multiplication. For example, when degFahren is set to 50 ,
(degFahren ‐ 32) = (50 - 32) = 18 . Now JavaScript does the multiplication, .5556 * 18 ,
which is approximately 10 .
What if you didn't use the parentheses? Then your code would be:
degCent = 5/9 * degFahren - 32;
The calculation of 5/9 remains the same, but then JavaScript would have calculated the multiplication,
5/9 * degFahren . This is because the multiplication takes precedence over the subtraction. When
degFahren is 50 , this equates to 5/9 * 50 = 27.7778 . Finally, JavaScript would have subtracted the
32 , leaving the result as -4.2221 ; not the answer you want!
Finally, in your script block, you display the answer using the alert() function:
alert(degCent);
That concludes a brief look at basic calculations with JavaScript. However, in Chapter 5 you look at the
Math object, which enables you to do more complex calculations.
Basic string operations
In an earlier section, you looked at the text or string data type, as well as numerical data. Just as
numerical data has associated operators, strings have operators too. This section introduces some
basic string manipulation techniques using such operators. Strings are covered in more depth in
Chapter 5, and advanced string handling is covered in Chapter 6.
One thing you'll find yourself doing again and again in JavaScript is joining two strings to make one
string—a process termed concatenation . For example, you may want to concatenate the two strings
"Hello " and "Paul" to make the string "Hello Paul" . So how do you concatenate? Easy! Use the
+ operator. Recall that when applied to numbers, the + operator adds them up, but when used in the
context of two strings, it joins them:
var concatString = "Hello " + "Paul";
The string now stored in the variable concatString is "Hello Paul" . Notice that the last
character of the string "Hello" is a space—if you left this out, your concatenated string would be
"HelloPaul" .
 
Search WWH ::




Custom Search