Javascript Recap


Values, Expressions, Statements

What have we learned about JavaScript so far?

  • Values include numbers, strings, booleans, dates, etc.
  • Expressions are program phrases that denote values. They can be composed of different parts such as: literals (e.g., numbers, strings); variable references; operators (e.g., +, -, *, /, %); function names (e.g., prompt, parseInt), and method names (e.g., querySelector, getMonth).
  • Statements are program phrases that perform actions. Statements are executed sequentially from top to bottom in a program.

    Some statements we've seen so far are:

    • function invocations like alert(exp);.
    • method invocations like document.querySelector(exp);.
    • variable declarations of the form var variable-name;
    • variable assignments of the form var variable-name = exp; or variable-name = exp;

    In variable assignments, = is pronouced "gets" and not "equals".

    In all of the above statements, exp can be any expression, from a simple literal (like 17 or "CS110") or variable (like num) to a complex expression like

    "The sum of the numbers is "
    + (parseFloat(prompt("Enter number 1","17"))
       + parseFloat(prompt("Enter number 2","23")))

    If there is a variable declaration as a part of a statement, a new variable box in the memory is created and named. The assignment operator then assigns the value on the right side of = to this box.

    You should use descriptive names for variables They greatly help the development of correct programs.

Here's a sample sequence of variable declarations with assignments:

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

In the first statement, the right-hand side is a simple number value, 14, which is assigned to the variable small_num. In the second statement, the right-hand side is a more complex expression that evaluates to 331, which is then assigned to big_num. In the last statement, 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.

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

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:

Re-assigning Variables

In many examples so far, we have created new variables to assign the next step of the calculation to.

  • Is there any limit to the number of variables in a Javascript (JS) program? No, not really.
  • Should you reduce or minimize the number of variables in a JS program? No, not really. You should use any variables that you feel makes your code clearer, easier to understand, and easier to debug. (Variables can help with debugging because you can print intermediate steps to check that part of the calculation.)
  • Is there any advantage to re-using a variable? No. In fact, in most cases, if you re-use a variable to hold a different value, you will increase the chance of confusing anyone reading your code, including yourself. Thus, we discourage you from re-assigning to a variable (but see next section for more details).

Here's an example of poor use of re-assignment:



Ask yourself: what kind of value does val hold? It depends on where in the code you're looking; it changes from place to place. That's why we gave the variable such a vague and unhelpful name: we couldn't use anything more specific. In fact, the value even changes type from place to place (in the last assignment, it becomes a string). Since we know that the + operator treats strings differently from numbers, this sort of confusion can be a big problem.

The moral here is that it's not good enough for the JavaScript program to work. The underlying JavaScript code should be easy to read and understand as well!

Good Re-assignment

Is there ever a time when you should re-use a variable? Yes.

Let's turn to that now. It makes sense to re-assign to a variable when it holds the same information (the same meaning and same type), but that the old value needs to be updated. For example, suppose you are counting something, and the count has changed. In an online shopping application, you might be counting the number of items the user has in her cart. Suppose that the variable item_count stores the current number of items in the cart. When she adds another item to the cart, you want to increase that variable's value by one. Here's how:

  item_count = item_count + 1;

Notice that if that were a mathematical equality statement, it would be impossible: no number can equal one more than itself. But this is not equality, this is assignment, so it says to take the current value of item_count, add one to it, and store that value back into the variable.

Below is a specific example, where we count mouse clicks. We are not showing the whole code of the example, but only the variable declarations, so that you are aware of where the values are being stored.

var start_time;
var stop_time;
var total_time = 0;
var click_count = 0;

How fast can you click? Start the timing, then click like mad in the yellow area, and then stop the timing when you're done.

click here

You clicked times in milliseconds, which is clicks per second.

Here's an execution box that will add one more click to your click count and report the current values.



There are two things worth noticing from the code above:

  1. When we re-assign a variable, we omit the var out front. The var tells JavaScript that we are creating a new variable, and, of course, when we are re-assigning, we aren't creating a new variable.
  2. Remember that = should be read as "gets". So in the first line, we are not saying that click_count is equal to click_count plus one. That would be impossible! Instead, we are saying that the value assigned to click_count should be updated to the current value of click_count plus one.