Java Reference
In-Depth Information
assigning Variables the Values of Other Variables
trY it out
Let's look at another example, this time assigning variables the values of other variables.
1.
Type the following code into your text editor and save it as ch2_example2.html :
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Chapter 2, Example 2</title>
</head>
<body>
<script>
var string1 = "Hello";
var string2 = "Goodbye";
alert(string1);
alert(string2);
string2 = string1;
alert(string1);
alert(string2);
string1 = "Now for something different";
alert(string1);
alert(string2);
</script>
</body>
<html>
2. Load the page into your browser, and you'll see a series of six alert boxes appear.
3. Click OK on each alert box to see the next alert. The first two show the values of string1
and string2 Hello and Goodbye , respectively. Then you assign string2 the value that's in
string1 . The next two alert boxes show the contents of string1 and string2 ; this time both
are Hello .
4. Finally, you change the value of string1 . Note that the value of string2 remains unaffected. The
final two alert boxes show the new value of string1 ( Now for something different ) and the
unchanged value of string2 ( Hello ).
The first thing you do in the script block is declare your two variables: string1 and string2 . However,
notice that you have assigned them values at the same time that you have declared them. This is a
shortcut, called initializing , that saves you typing too much code:
var string1 = "Hello";
var string2 = "Goodbye";
Note that you can use this shortcut with all data types, not just strings. In the next two lines you use
the alert() function to show the current value of each variable to the user:
alert(string1);
alert(string2);
Search WWH ::




Custom Search