Lesson 2: Input and Variables: OBJECTIVES: in This Lesson You Will Learn
Lesson 2: Input and Variables: OBJECTIVES: in This Lesson You Will Learn
How to use the prompt statement to collect information from the user
Preparing to Program
A critical feature of programming is the ability to represent data (information). If a
computer cannot process information, it is not much use. Programming languages use
variables to represent information. A variable is an idea you may remember from
algebra: it is a name that stands for a value. Since that value can change (vary) over time,
it is called a variable. It does not mean it has to change, it just means that it may change.
In programming, a variable is a container that holds information used by a program. In
algebra, you learned that variables like x and y can hold numbers. In JavaScript programs,
variables can also hold strings (character data) or Boolean (logical) values.
Declaring Variables
The first step requires that you create a variable. This is called a variable declaration. In
JavaScript, a variable declaration looks like this:
var myName;
var is a keyword that indicates this is a variable declaration. This line of code says that
“myName” is the name of the variable. In programming, the name of a variable is called
an identifier. All programming languages have syntax rules that restrict what can be a
legal identifier. In JavaScript, the first character must be either a letter or an underscore
(_). The remaining characters may include numbers, along with letters or an underscore.
You cannot include a blank space or any other special characters like dash (-). You may
also not use any JavaScript reserved words as an identifier (see Appendix A for a list of
JavaScript reserved words). Identifiers are case sensitive, so”myName” and “MyName”
are treated as different identifiers. Mis-spellings causes by the wrong case are usually
difficult to spot, so always be careful when creating and using variable names.
myName = “Fred”;
The equal sign is called the assignment operator. Notice the value is copied from the right
to the left. This is opposite of how you used the equal sign in your math classes. In most
programming languages, values are assigned from the right into the left. The opposite
direction is an error:
“Fred” = myName;
//this is an error, the variable name must be on the left
You can also declare a variable and assign it a value at the same time:
Syntax:
The entries inside the parentheses of a method are known as parameters. Remember, in the
Introduction you learned about the idea of a function or method, which is a mini-program that
carries out a specific task. Parameters are information that a method or function uses when
carrying out its specialized tasks. You will learn more about parameters, functions, and
methods in Lesson 6.
This week in the lab you will use the prompt method to collect information from the user
and make use of it in your programs.
myName is the name of the variable, and Sam is the value or contents of the variable.
When you use a variable in a document.write statement, the contents of the variable are
displayed on the page. For example, the statement
document.write(myName);
displays the name Sam on the page. Notice there are no quote marks surrounding
myName. If you were to include quote marks, then the contents of the quote marks, not
the contents of the variable would be displayed. The basic rule controlling output is this:
characters inside quotes are printed; characters not inside quotes are considered variables,
and the value of the variable is printed.
For example:
document.write(“myName”);
Once all three parts are combined, the variable sentence has the value “This sentence has
three pieces.” Notice you need to include blank spaces within the string. If you omit them,
they words will run together.
You can also use concatenation to combine strings inside quotes along with variables. For
example:
var myCar = “Corvette”;
You will use concatenation in this lesson to combine variables containing values input by the
user in a display message.
In the Lab
This week in the lab you will add interactivity to your Web pages by introducing variables
and user input with the prompt method. This will allow you to customize the appearance of
your page. We will also try out a simple version of Mad Libs, a word game that creates
mangled sentences.
Start 1st Page 2000 and begin a new HTML document. Save it giving it the name
lesson0201.html. Following the instructions outlined in Appendix B, place your cursor
between the <BODY> … </BODY> tags, and insert the SCRIPT tags and hiding comments
by using the Scripting menu.
<!--
//-->
</script>
After you have typed in the above code, run it using the preview button. If you have any
errors, correct your code until you have output that looks like the following:
Student Modifications
Make the following modifications to the code:
In the prompt method set the value of the second parameter to “”, which means
empty. This takes away the default entry. Run the code again, and do not input a
value, just hit the enter key. What is displayed?
Create another variable called myMovie. Ask the user to input their favorite movie,
and store their answer in myMovie. Write a document.write statement that displays
the variable.
Use HTML format tags to change the format of a variable. Remember, the HTML
tags need to be inside quote marks, so you must use concatenation to do this.
The following JavaScript code uses variables and the prompt method to create a Mad Lib.
<html>
<head>
<title>Simple Mad Lib</title>
</head>
<body>
<script language="Javascript">
<!--
document.write(sentence);
//-->
</script>
</body>
</html>
After entering this code, run it a few times with different words. Check your blank spaces,
and be sure the words are spaced properly.
Student Modifications
You have used embedded HTML to change the format of string output. JavaScript also has
string formatting methods that can simplify your output formatting.
For example, add the following code after the first document.write statement (line 17):
document.write(sentence.bold());
Type this code in and run it. You will see it displays sentence in bold. This method performs
the task of adding <B> to the front of sentence and </B> to the end of sentence.
Here are some additional string methods:
string.blink()
string.fontcolor(colorValue)
string.fontsize(integer1to7)
string.italics()
string.big()
string.small()
Try some or all of these methods in your Mad Lib. For example, to use italics, replace string
with sentence, i.e.
document.write(sentence.italics());
If you want to use fontcolor, you will need to include a color as a parameter. Select a color
from the list in Appendix C. If you want to use fontsize, you will need to include a number
between 1 and 7 as a parameter.
Lesson 2 Summary
You learned how to declare and name a variable using the JavaScript rules for identifiers.
You also assigned values to a variable with the assignment operator. You queried the user for
input, and stored the user’s response in a variable with the prompt method. You learned how
to combine strings using concatenation and the + operator. You also learned how to display
the value of a variable with document.write. Finally you learned how to use string formatting
methods to alter the appearance of a string.
Lesson 2 Exercises
2_1. Write a JavaScript program that uses three variables and three prompt statements. Ask
the user to enter their first name, middle name, and last name in separate prompt statements.
Then use string concatenation to display the name in the following format:
last name, first name middle name
So if Thomas Francis Jones is the name that is entered, your program will display:
Jones, Thomas Francis
Be careful of spaces. Be sure to include any needed spaces within your quote marks.
2_2. Write a JavaScript program that asks the user to input their name, what city they were
born in, and the month of their birthday. Then display that information using document.write.
It was a adjective kind of day when person's name walked out into the street. The sky
was a deep color , and same name was walking his new pet animal ...
Making the following substitutions:
adjective = smarmy
person's name = Chris
color = mauve
animal = gnu
It was a smarmy kind of day when Chris walked out into the street. The sky was a deep
mauve, and Chris was walking his new pet gnu ...
The content of the story can be anything that you like -- be creative! Your story must meet the
Copyright © August 2002 Pace University
JavaScript 101 | 2-13