Lesson #3 - Variables and Values

Lesson # 3 Variables and Values

# 3 Review Questions # 3 Assignment

What are Variables

Technically, variables are just places in the computer's memory where we can store information such as numbers and text for a future use. They work almost like a mailbox, where they could hold a variety of different pieces of information. A variable could hold a string of text such as:

memberName="Arnold Schwartzenegger";

Or a variable could hold a number value as in:

pi=3.14159;

The sample programs you have seen so far just display text, useful maybe, but only the beginning. We can use variables to perform useful calculations by storing numbers, and we can store text such as user login names, passwords, addresses, and much more. Variables themselves don't have a distinct data type, which is a fact that drives experienced programmers crazy. They get their type from the value that is stored in them, and values can be of several types, as shown in the chart below. The type is determined by the value that each variable is asked to store for us.

Types of Data that can be stored in Variables

Value DataType What it can store Examples
int
positive and negative whole numbers between -2^53 to +2^53 meaning from -9007199254740992 to +9007199254740992 0,1,2,3,-75, 32677, -30000, 25000000000 but not 3.14 or -25.5
float

floating point decimals in either decimal format or scientific notation between approximately + or - 1.7976931348623157 x 10^308 down to  + or - 5 x 10 ^ -324

3.14159, -900234.2345, and in scientific notation (also known as exponential notation) 7.123 x 10^-22 , -2.07e17 (where 'e' means 10 raised to the power of 17)
Boolean
These are nifty ways to hold true or false values, with false being considered a 0 and true is non-zero. Useful for testing for certain logical conditions. This type is named after George Boole, a famous mathematician. true, false but not maybe.
String
Any kind of text including letters, numbers, punctuation characters that probably won't be used for doing math. Examples are people's names, merchandise items for sale on e-bay, addresses, zip codes, social-security numbers, telephone numbers, the words to a song, etc.Strings need to be enclosed in single or double quotation marks. "Good evening", "Arnold Schwartzenegger", "503-431-4000", "97223", "mypassw0rd"

There are a few more types, but this will get us started.

Rules for Naming Variables

We use the keyword var to create a variable. And we want to choose the names with care. Choose a name that lets you and others know the purpose and describe the variable's contents. Don't use single letter names such as x or y except in a few instances where it is common practice. Most programmers, for example, will use i for the name of a counting or index variable.

var lastName;

This is a statement that creates, or a variable named lastName and lets the browser know that we will be using this variable later to store, manipulate, or display some information. Use var only once per variable, when you declare it for the first time. After that just use its name. Here is another example:

var lastName = "Einstein";

This is a statement that not only creates a variable and assigns it a value of "Einstein" using the = sign. This is called initializing, and it is a very good practice. Once we assign it a value, we don't have any risk that some unknown or random value might be hanging out in our variables.

 

Another way to get a value stored in a variable is the prompt() method. It is a little like the alert() method in that it is part of the core JavaScript language, so we don't have to use it as part of an object, but it does something nice. It allows us to store a value in a variable for use later in the program. Here is an example of using the prompt() method. The statement looks like this:

var myVariable = prompt("Type in your favorite food.", "Anchovie Pizza");

There are some hard and fast rules for naming variables, and there are some common sense suggestions (which bad programmers will ignore).

First the rules you MUST obey!

  1. No reserved words or keywords may be used as variable names. Click here to see a list of JavaScript keywords.
  2. No spaces are allowed in variable names, but you can use a capital letter or an underscore ("_")as a separator.
  3. Values may be assigned to a variable using the "=" sign, as in age=16; or dogBreed="Airedale";
  4. The first character must be a letter of the alphabet or an '_', so names like 2000wages or %taxrate are illegal.
  5. Variable names, like everything else in JavaScript is case-sensitive, so myPayCheck and MyPayCheck are two different variables.

Now the suggestions! These are commonly agreed practices that good programmers use - so use these suggestions to avoid looking like a dufus.

  1. Always begin each variable name with a lower case letter.
  2. Think carefully about the name - it should be some sort of noun that describes why on earth this variable is used in your program. Not too short and not too long. Some good examples are: numItems, zipCode, gpa, userName, speedOfLight. Here are some bad examples: b, gh, number, result, Taxes_I_paid_in_1971.
  3. The dollar sign "$" is not recognized by Navigator 2.02 and IE 3.02, so it should be avoided in naming variables.
  4. Always use the keyword var when creating or declaring a variable.
  5. Declare all the variables you plan to use in a script at the top, so they will always be easy to find.

Check yourself here. Classify each of the variable names below as Valid or Not Valid, and think about why.

var continue Valid Not Valid

var movieTitle Valid Not Valid

var movie GrossSales Valid Not Valid

var _counter Valid Not Valid

var gpa12thGrade Valid Not Valid

 

Showing Values on the Web Page

Before we can display our variables on the screen, we need to store some values in them. Remember that variables get their data type from the values we store in them.

  • var someType = 25; //someType is now an int variable
  • var someType = 12.75 // someType is now a float variable
  • var someType="Arnold" // someType is now a string variable

So far we have only talked about using the "=" sign to get values stored in variables. That means that YOU, the programmer are the only one that can choose the values that we can use. Lets look at one way that JavaScript can let the user of the Web Page store values into our variable. A prompt() method can be used to allow the user to enter a value. Here is an example:

Here is the code and an explanation of how that works.

 

<input type="button"

 

name="exampleButton"

 

value="Example"


onClick="var someData=prompt('Enter some data here.',' '); alert(someData);" >

The input type of button is just a device to trigger the Javascript to run. We click the button, and the event onClick is triggered to execute.

The name of the button is invisible to the user, but as programmers we will learn later how to use that name to identify components of a document..

The Value="Example" is the text the user sees on the button. We try to make it logical for the user.

Here is the real action. Click is the event, and the event handler has the same name with 'on' attached. Hence - onClick. First a variable is declared named someData. It recieves its value from the prompt function that tells the user to enter some data, then sends the value of that data to the variable. Last, an alert function shows that data back to the user.

Getting Fancy

Here is a sample of a small HTML form, with a place to get some input, and then do a little math, then show the output. Try it for yourself and then we will break it down and explain the details.


Welcome to the Body Mass Index Calculator!

In this little form, you are asked to enter your height in inches and your weight in pounds. The code will convert the inches and pounds to metric units for you, and then calculate the body mass index as the ratio of weight divided by height squared. If your body mass index is under 25, then you have a healthy weight to height ratio.

Please enter your height in inches Enter your weight in pounds
Your height in meters is Your weight in kilograms is
Your Body Mass Index is

Here is the code and the breakdown of what it all means. You need to know the names of the boxes on the form, so here is a list. The name of the form in BMICalc.

It is a little tricky to see how the variables are accessed, so pay attention to that part

The Code The Explanation
function bmiMath(form) {

This code all appears in the <HEAD> section of the web page. It is called into play when the user clicks the button. JavaScript starts with the first line and goes through all the lines in sequence.

function is a keyword - it needs to be there

bmiMath is the name of the function. I tried to make it describe what it really does.

(form) is the entire set of objects that make up this form. It recieves the values that are sent by the onClick="bmiMath(this.form)"); This way it can have access to all the boxes and their values on the form.

The opening curly brace { denotes the beginning of a function or block of code and it ends with the closing curly brace }.

// Declare variables and initialize

var height = parseFloat(form.inches.value);
var weight = parseFloat(form.pounds.value);

First the keyword var is used to declare and initialize the two variables named height and weight. Values are stored in them using the = sign.

Here is the important part.

(form.inches.value) and (form.pounds.value) - - These two items refer to the values that are passed in from the function call to bmiMath(form). When the form gets sent to this function, the JavaScript needs a way to tell which text boxes we are talking about. The name that gets sent from the button's onClick method is just 'this.form'. It means the form and all of its form elements. Then we refer to each element by name, using the . to separate the parts. The user types in text that is stored in the 'value' property of each text box. It is stored as a string value. To access that text, we must use the name of the form that recieves the value (I used 'form'), then the name of the textbox, and lastly the value property. Since it is received as a string, we convert it to a numeric float type by calling the parseFloat() function of JavaScript. Note, there is also a parseInt() function.

Whew! Lots to learn.

var meters = height * 0.0254;
var kilograms = weight * 0.45;
var bodymassindex = kilograms/(meters*meters);

Here, three more variables get declared and initialized by using the conversion factors to change english units to metric. We multiply inches by 0.0254 to convert to meters, and multiply pounds by .45 to convert to kilograms. Note my variable names make it hard to get confused here. The body mass index is weight divided by height squared so you see that math being done in the last line. These variables are all containing values of type float (short for floating point decimal) so they are all capable of doing the math.

At this point in the program, the work is done, but nothing will be displayed yet.

// display results

form.meters.value = meters;
form.kilos.value= kilograms;
form.bmi.value = bodymassindex;

Here we go back and assign the variables on the right side of the = sign to be stored in the value properties of the last three textboxes on the form. Again we use the object notation of form.nameOfTextBox.value for each one. As soon as these assignments are made, it shows up on the web page.
if (bodymassindex > 25.0)
   alert("Learn all you can about healthy diets and exercises!");
else
   alert("Your body mass index is within the healthy range.");

This little if-else statement was just me having some fun - and will be covered again later. It checks the value stored in bodymassindex. If it is 25 or more, the alert box displays one message, and otherwise, the alert box displays a different message. Hopefully you got the second message when you input your own data.

Also note how the lines are indented. That's for readability and all good programmers do it.

}// end function bmiMath() All functions are enclosed inside of curly braces {} and it is a good idea to add the // for commenting. It helps the code remain readable.
   

note // the following appears in the body - since the Calc button is in the form named BMICalc and it calls the function described above.

<input type = "button" name = "Calc"

value = "Calculate my BMI" onClick="bmiMath(this.form)">

This is the tag in the web page for the button that actually calls the JavaScript program into action. Focus on the onClick part. Inside the quotation marks, we use the name of the function, which is bmiMath, followed by a set of parentheses( ). The parentheses are always needed, even if no information is passed to the function. But in this case, we are passing in the entire form and all of its form elements.

 

 

Return to Top of Page | Back to Main Menu