Java Reference
In-Depth Information
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 4 you'll be look-
ing 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 numeri-
cal data have 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 4, and
advanced string handling is covered in Chapter 8.
One thing you'll fi nd yourself doing again and again in JavaScript is joining two strings together 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 together.
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” .
Try It Out Concatenating Strings
Let's look at an example using the + operator for string concatenation.
1. Type the following code and save it as ch2_examp5.htm:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/javascript”>
var greetingString = “Hello”;
var myName = prompt(“Please enter your name”, “”);
var concatString;
document.write(greetingString + “ “ + myName + “<br>”);
Search WWH ::




Custom Search