Thursday, December 7, 2023

Using JavaScript Variables and Built-In Functions, Part 2

Excerpted from Chapter 2, JavaScript 2nd Edition: A Practical Guide To Interactive Web Pages from No Starch Press


Any series of characters between quotes is called a string. (You’ll be seeing lots of strings throughout this book.) Strings are a basic type of information, like numbers–and like numbers, you can assign them to variables.

To assign a string to a variable, you’d write something like this:

var my_name = “thau!”;

The word thau! is the string assigned to the variable my_name.

You can stick strings together with a plus sign (+), as shown in the bolded section of Figure 2-6. This code demonstrates how to write output to your page using strings.

<title>Seconds in a Day</title>
<script type = “text/javascript”>
<!– hide me from older browsers

var seconds_per_minute = 60;
var minutes_per_hour = 60;
var hours_per_day = 24;

var seconds_per_day = seconds_per_minute * minutes_per_hour * hours_per_day;

// show me –></script>

<h1>My calculations show that . . .</h1>

<script type = “text/javascript”>

<!– hide me from older browsers

X var first_part = “there are “;
Y var last_part = ” seconds in a day.”;
Z var whole_thing = first_part + seconds_per_day + last_part;


// show me –>




Figure 2-6: Putting strings together

Line-by-Line Analysis of Figure 2-6

Line X in Figure 2-6,

var first_part = “there are “;

assigns the string “there are” to the variable first_part. Line Y,

var last_part = ” seconds in a day.”;

sets the variable last_part to the string “seconds in a day.” Line Z glues together the values stored in first_part, seconds_per_day, and last_part. The end result is that the variable whole_thing includes the whole string you want to print to the page, there are 86400 seconds in a day. The window.document.write() line then writes whole_thing to the web page.

NOTE: The methods shown in Figures 2-4 and 2-6 are equally acceptable ways of writing there are 86400 seconds in a day. However, there are times when storing strings in variables and then assembling them with the plus sign (+) is clearly the best way to go. We’ll see a case of this when we finally get to putting the date on a page.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles