Variables, Types and Expressions

Data Types and Expressions

We've now seen various examples of JavaScript programming (remember the basketball?), and learned the general template for how to write JavaScript code. JavaScript allows for computation involving text, numbers and boolean (true/false) values as well. Today, we'll cover the basic data types of JavaScript and the operations defined for those types. (Data types means the kind of information that JavaScript can handle, things like numbers, words, etc.).

Three Data Types (and Operators)

There are three basic types of values in JavaScript, and there are operators to compute with those values:

  1. Numbers are the easiest to understand, since we've used them since elementary school. There are quite a few operators that apply to numbers. You already know +, -, * and / as the basic four arithmetic operations. You also already know some of the comparison operators like less than (<) and greater than (>). Another operator, denoted %, is the remainder operator: if you divide one number by another, this operator gives you the remainder. For example, 7%3 is 1.
  2. Strings are what computer scientists call “pieces of text” or “sequences of characters.” For example, "Frodo", "The Lord of the Rings", and "this is a string" are all strings. Strings can be created with either the double quote character (") or the single quote character ('). The only operator for strings is the concatenation operator, written +, which glues two strings together. For example, "rail"+"road" is "railroad".

    Warning! Since + can mean two different things, it will be a source of errors (aka “bugs”) in your code!

  3. Booleans are values that you may not have heard about before.

    We will examine booleans in more detail in a future lecture, but here is a brief description of what they are:
    Booleans are logical values that are either true or false. For example, the expression 7 > 13 is false while the expression 7 > 3 is true. There are three logic operators for boolean values:

    ! means not, so !(7 > 13) is true
    && means and, so (7 > 13) && (7 > 3) is false
    || means or, so (7 > 13) || (7 > 3) is true
    Booleans appear in the code when making decisions. Note: Some of the Booleans use unfamiliar characters. The & (pronounced “ampersand”) is found above the 7 on your keyboard. The vertical bar is above the backslash on your keyboard. In some fonts, the vertical bar looks like a capital I, but it's not, so be careful about that. Another common error is to leave out one of the ampersands or vertical bars: For combining booleans, there are two!

Variables

As we mentioned, JavaScript variables can be assigned values of any type, including numbers and numeric expressions. For example, the first assignment below stores the value 24 in the memory cell corresponding to the variable my_age. The second assignment stores the value 1024 in your_age's memory cell, leaving my_age unchanged. The statements on the left are JavaScript, the labeled boxes on the right are a way for you to visualize what's happening.

var my_age = 24;
24

my_age
var your_age = (100 * 10) + my_age;
24

my_age
1024

your_age

To execute JavaScript code, one has to type it inside an HTML file, surround it with the SCRIPT tag and then use a browser to run the code and see the results. That takes a little bit of time. In the online notes, we will use the Evaluation Box (see below) to execute small pieces of Javascript. You can assume that the Evaluation Box is surrounded by the SCRIPT tag. Try it!

EXERCISE 0 You can type JavaScript code into the following box and evaluate it. Evaluate the following statements:
   var x = 4 * 3;
   var y = 4 / 3;
   var z = 4 % 3;
   var simpson = "Homer" + "Marge";
   var kids = "Bart " + "Lisa " + "Maggie";
   var ans = "The answer is " + (4 * 3);
   var bad_ans = "The answer is " + "(4 * 3)";

For each line, type in the line and an alert() command with the appropriate variable to show the value. Before you evaluate each thing, see if you can predict what will show up in the alert box.

Evaluation Box:

Assignment Changes the Contents of the Variable

In JavaScript, values are assigned to variables (and thus stored in their associated memory cells) using the assignment operator =. For example, let's say we want to assign values to variables named name, current_age and sings_about_rainbows.

var name = "kermit";
            
var current_age = 20;   // disclaimer: how old is kermit, really?
            
var sings_about_rainbows = true;
"kermit"
20
true
name current_age sings_about_rainbows

Once you have assigned a value to a particular variable, any reference to the variable name evaluates to the value stored in its associated memory cell. If kermit just had a birthday and also got laryngitis (some birthday party, huh?), then we could update current_age and sings_about_rainbows like this:

current_age = 21;
            
sings_about_rainbows = false;
"kermit"
21
false
name current_age sings_about_rainbows

Notice that we didn't say var here. That's because we assume the variables were introduced earlier.

Let's Play the Computer

Once a value is stored in a variable, the variable can be used in place of the value. To understand a sequence of statements, you have to take them one at a time, top to bottom, understanding the effects of each in turn.

EXERCISE 2:

Trace the execution of the following JavaScript code. For assignments, draw each memory cell along with its contents. For alert statements, list the output that would be displayed.

var fred = 14;
var wilma = fred % 3;
var about_wilma = "wilma is " + wilma;
alert(about_wilma);
   
var homer = 0;
var marge = homer + 100;
var lisa = marge * 2;
alert("lisa is "+ lisa);

Verify your predictions by cutting-and-pasting the above code into the following form and evaluating it.

Type here:

Your First Calculations

EXERCISE 3:

The following formula can be used to convert a temperature in degrees Fahrenheit to Celsius.

   var temp_in_Celsius = (5 / 9) * (temp_in_Fahr - 32);
 

Write some code where the first statement just assigns this room's temperature (make a guess) to temp_in_Fahr, the second computes the temperature in Celsius, and the third is an alert() to report the value. Make the alert() nice and descriptive, like this:

You entered 32 degrees Fahrenheit. That's equivalent to 0 degrees Celsius.

Type here:

Use your code to convert each of the following temperatures from Fahrenheit to Celsius, and report the corresponding temperatures.

98.6 Fahrenheit
100 Fahrenheit
212 Fahrenheit
  0 Fahrenheit

What value of Fahrenheit is the same as the value in Celsius?

Swapping Values is Tricky!

The following pair of assignments is intended to swap the values stored in variables elmo and grover.

var elmo = 21;
var grover = 18;

elmo = grover;
grover = elmo; 

Will the execution of these two statements result in the values of the two variables being swapped? For example, if elmo had value 21 and grover had value 18, does executing the assignments result in elmo being 18 and grover being 21?

Note: Your code should work no matter what values are in the two variables. We are using 18 and 21 for concreteness only, but your code should work if they are 7 and 27 or 3 and 92 or ...

To test your reasoning, write a few lines of code to (1) set grover and elmo to 18 and 21, respectively, (2) swap their values using the idea above, and (3) report the result using an alert(). If the code does not work, try to figure out different code that does work.

Type here:

Prompting for Text

Remember the prompt() function we saw earlier? Like alert(), it pops up a box, but it allows the user to type something in, and the result is the value of the function. Thus, you can do things like:

var name = prompt("What is your name?");
alert("your name is " + name);

The prompt() function takes either 1 or 2 arguments (an argument is one of the values in parentheses). The first is reported in the box. The second, if supplied, is a default value. For example:

var quest = prompt("What is your school?", "Wellesley" );
alert("your school is " + quest);

Using a default value makes it easier on the user when the default is right, but lets him or her correct (override) the value when it's wrong.

Type here:

The result of the prompt() function is always a string, NOT a number .

Solutions to Exercises

Optional reading: Thau Chapters 1-2.

© Computer Science 110 Staff
This work is licensed under a Creative Commons License
Date Modified: Thursday, 24-Jan-2008 12:54:57 EST