Evaluating JavaScript Expressions

Review: Evaluating JS Expressions

We've covered the different data types that JavaScript can handle (numbers, strings and booleans) and how to use variables. An expression is a combination of variables and operators (and other expressions) that produces a value. Let's review the way we write assignment statements in JavaScript.

For example, in the first assignment below, the right-hand side is a simple number value, 14, which is assigned to the variable small_num. In the second assignment, the right-hand side is a more complex expression that evaluates to 331, which is then assigned to big_num. In the last assignment, the right-hand side is an expression involving the variables small_num and big_num. Since small_num has the value 14 and big_num has the value 331 when this assignment occurs, the expression small_num + big_num evaluates to 345, which is then assigned to the variable sum.

var small_num = 14;
var big_num = 33*10 + 1;
var sum = small_num + big_num;
            
small_num = 14;
14

small_num
big_num = 33 * 10 + 1;
14

small_num
331

big_num
sum = small_num + big_num;
14

small_num
331

big_num
345

sum
EXERCISE 1:

Trace the execution of the following JavaScript code, drawing the contents of memory cells after each assignment and listing the output of each alert(). You can test your hypothesis with the evaluation box.

var numA = 14;
var numB = 2 * numA;
alert("numA is " + numA + ", and numB is " +  numB);
numA = numB + numB;
alert("now, numA is " + numA + ", and numB is " +   numB);
            
var numC = (112 % 5) * 2;
var message = "numC is " + numC;
alert(message);
   
numC = 0;
alert(message);
alert("numC holds " + numC);
   
            

Type here:

Displaying the date dynamically

Newspapers on the web usually display the current date on their front pages. Take a look, for example at the Christian Science Monitor. We can do the same in our pages:

Here is JavaScript code that does this:

<script type="text/JavaScript">

var today = new Date(); 
var the_day = today.getDate(); 
var the_month = today.getMonth(); 
var the_year = today.getFullYear(); 

/* correct for the month starting from zero */
the_month = the_month + 1; 

/* create the string you want to print */
var the_whole_date = the_month + "/" + the_day + "/" + the_year; 

/* display the date */ 
document.write("<blockquote>In Wellesley, MA, today is " +
                the_whole_date +"</blockquote>"); 

</script>

Let's examine the code. It is a sequence of JavaScript statements, which will be executed sequentially by the browser. The final statement document.write() (a.k.a “write in the document”) will do the work and write on the page. It will display, in part, the value of a variable, the_whole_date, which is a string composed of the values of three other variables separated by the “slash” symbol. The question is, how did these other variables get their values?

Practice the behavior of the code by using the evaluation box below. Change the code to display the date in the European mode, DD/MM/YYYY.

Important note: In the evaluation boxes, instead of document.write(), always use alert(). Remember, in the evaluation boxes you do not need the SCRIPT tags. They are implied.

Type here:

The very first line has something interesting in it. The right hand side of the assignment says new Date(), which is not a primitive value nor an expression using variables, operators, and primitive values. The keyword new causes a non-primitive object to be created. In this case, the object represents a Date. JavaScript comes equipped with lots of pre-defined object types.

An object is a data value that has two important characteristics:

Both properties and methods are selected from an object using dot notation. In the code above, the variable today contains a date object after the first line. The expression to the left of the dot in today.getDate(), is a variable, today, that contains a date object. To the right of the dot is the name of the thing we want to select from the object. In this case, we select the getDate() method, which returns the numerical day of the month in a date object. (You can tell we're calling method rather than selecting a property by the presence of parentheses after the name.)

Read the book for a detailed line-by-line explanation of the above code as we will do in class. In the class notes we will discuss in some detail a few points that are not treated in depth in the book.

Here are some of the most important methods of the Date object

month = month + 1 (huh?)

EXERCISE 2: Trace the execution of the following JavaScript code, drawing the contents of memory cells after each assignment and listing the output of each write statement.
var pairs_of_shoes = 0;
pairs_of_shoes = pairs_of_shoes + 3;
alert("pairs_of_shoes is " + pairs_of_shoes);
   

pairs_of_shoes = pairs_of_shoes * pairs_of_shoes;
alert("pairs_of_shoes is " + pairs_of_shoes);
   
var word = "littleBunnyFooFoo";
word = word + "-" + word;
alert("word is " +   word);

Verify your predictions by using the following evaluation box.

Type here:

Precedence rules (who gets to go first)

Sometimes, the order in which an expression is evaluated is important to the final result. For example, consider the expression, (2 + 4 * 5). If the addition is performed first, the expression will evaluate to 30. If the multiplication is done first, however, the expression will evaluate to 22.

2 + 4 * 5 ==> (2 + 4) * 5 ==> 30
2 + 4 * 5 ==> 2 + (4 * 5) ==> 22

What happens in JavaScript? The answer is that JavaScript does the multiplication first. Here are the rules:

Some examples:

8 / 4 / 2 ==> (8 / 4) / 2 ==> 1
2 + 10 / 2 ==> 2 + 5 ==> 7
(2 + 10) / 2 ==> 12 / 2 ==> 6
EXERCISE 3:

Try to predict the value of each of the following expressions.

alert(3 + 3 * 2 + 1);
alert(10 / 2 * 5);
alert(7 - 2 - 4);
alert(7 - (2 - 4));
alert(3 * (5 / 2) + 2 * 8);

Verify your predictions by using the following evaluation box.

Type here:

Concatenation or Addition?

Recall that the '+' operator performs double duty in JavaScript, representing addition when applied to numbers but concatenation when applied to strings. When applied to a string and a number, the '+' operator automatically converts the number value into a string and then concatenates. For example,

"We're number " + 1 ==> 
"We're number " + "1" ==> 
"We're number 1"

If proper care is not taken, mixed expressions involving string and numbers can produce unexpected results. Since expressions are evaluated from left to right, the similar expressions below yield substantially different results:

3 + 2 + " is the sum" ==> 
(3 + 2) + " is the sum" ==> 
5 + " is the sum" ==>
 "5" + " is the sum" ==> 
"5 is the sum"
   
"the sum is " + 3 + 2 ==>
("the sum is " + 3) + 2 ==> 
("the sum is " + "3") + 2 ==> 
"the sum is 3" + 2 ==> 
"the sum is 3" + "2" ==> 
"the sum is 32"
EXERCISE 4:

What do each of the following expressions evaluate to? Describe the steps involved in each evaluation.

alert("My favorite number is " + 10 + 24);
alert("My favorite number is " + (10 + 24));
alert("My favorite number is " + 10 + "" + 24);

Verify your predictions by using the following evaluation box.

Type here:

Using prompt() to read in numbers

The mathematical definition of a function is a mapping from some number of inputs to a single output. prompt() is a JavaScript function. It has two inputs, one of which is optional. It has one output (a string), which is what the person typed in. Usually, the output is assigned to a variable.

Consider the following sequence of JavaScript statements.

myNumber = prompt("Enter a number", "");
alert("One more is " + (myNumber + 1));

If the user entered 12 as their number, the alert() statement would actually display the message "One more is 121", since myNumber is a string, which causes conncatenation to be performed in the expression (myNumber + 1). Using parseFloat(), the modified code below would display "One more is 13" given input value 12.

myNumber = prompt("Enter a number", "");
myNumber = parseFloat(myNumber);
alert("One more is " + (myNumber + 1));

Notice that we use the variable myNumber on both the left and right sides of the second statement. The right side converts the string into a number, and the = stores the result into the same storage location (since we no longer need the old value). This should remind you of the x = x + 1 example.

EXERCISE 5:

Trace the execution of the following JavaScript code, drawing the contents of memory cells after each assignment and listing the output of each write statement. Assume that the user enters the value 1024 at the prompt.

x = prompt("Enter a number", "");
alert("Double " + x + " is " + (2 *  x));
alert("Double " + x + " is " + (x + x));
x = parseFloat(x);
alert("Double " + x + " is " + (x + x));

Verify your predictions by using the following evaluation box.

Type here:

Debugging JavaScript

Debugging JavaScript is generally much harder than debugging HTML. As we've seen, JavaScript has at least three built-in datatypes, plus additional kinds of things such as the Data object, which have their own rules and constraints. In HTML on the other hand, a tag is either recognized or it's ignored. There's visual feedback when a tag is recognized, so you can usually figure out what to do, sometimes with a little trial and error. That's not to say that HTML is easy, only that it is easier.

Another thing that makes JavaScript harder to debug is that the browsers are written with regular web surfers in mind, not web page authors. Therefore, the browsers do their best to ignore and suppress JavaScript errors: they are actively trying to hide the errors from you!

Consequently, if you're trying to debug a JavaScript application, you have to know where to look for the errors. Of course, each application does it differently:

To test your debugging, visit this page that has some JavaScript Errors.

We've written a longer essay on debugging techniques which you are strongly encouraged to read.

Note that the errors we are discussing in this section are syntax errors. The syntax of a programming language is the set of rules about punctuation (where the commas and semi-colons go), the order of elements (variables on the left side of an assignment, expressions on the right), and so forth. These debuggers can help you find and fix those, but they cannot help you with logic errors, such as writing “age < 18” when you meant to write “age > 18” and so forth. These are hard to debug, too, because the code “works” in the sense of producing no errors, but it does the wrong thing. Your best strategy is to use alert() to check whether you are getting to the place in the code that you expect and whether variables have the values you expect.

Good luck!

Summary

Solutions to Exercises

Optional reading: Thau Chapter 2.

© Computer Science 110 Staff
This work is licensed under a Creative Commons License
Date Modified: Thursday, 06-Mar-2008 08:57:25 EST