CpSc 130 : Introduction to Programming and Information Systems

CpSc 130 Notes Javascript and User Interaction


Terms

variable
Variables are a way of remembering a value — I called them Post-it® notes in the last chapter. They consist of a unique (meaningful) name which is used to access some computer storage location, a data type, and a value. Allowable values depend on the data type, but any variable may be empty. That is, you may not have given it a value to remember yet – this is a common cause of errors — blank Post-it® notes.
Variables in JS need to be declared using the var keyword. Unlike many other languages, you do not have to specify the data type. JS figures that out automatically from the value you give it.
data types
There are three basic types of data in JS: numbers (integers or floating point, like 1 or 1.234); boolean (true or false); and strings (text). It is interesting to note that when you type a "number" at the keyboard, you are always actually typing a bunch of characters, that is a text string. This is true in any programming language! (The system converts the digits to a number for you. And converts it back to digits for display.)
You may also use the assignment operator to change the value of a variable.
accessing variables
JS variables are accessed through their names or identifiers. (See naming conventions.) When the name appears to left of an assignment operator we are storing a value in the variable for later use. When used on the right side of an assignment operator or as a function argument, we look up the value of that variable and use the current value. HTML "variables" are accessed using getElementById().
Technically, you are accessing the properties of an HTML element or object in the Document Object Model.
type conversions
Although a variable has a data type of number, you can still assign the value of a string (or vice versa). JS automatically changes the data type of the variable. This neat feature is also the cause of many programming errors. We will use parseInt() or parseFloat() to force a string to become a number (assuming it's a legitimate numeric string).
numeric expressions
Like a set of number and operators entered into a calculator, an expression in JS results in a value. We can save that value by assigning it to a variable (like "storing" it in a calculator) or display it using alert() (calculators do this as a default action) or use it like any other value. We can add (+), subtract (-), multiply (*) or divide (/) numbers. We can also get the remainder of a (long) division using the modulus (%). Strings can be "added" using the concatenation operator (+). Yes, that's the same operator as is used for addition. JS figures out which you want based on what you are "adding".
const
vs. var
A const is a variable that receives a value when it is declared and cannot be changed, although you can use its value many times. PI (3.14) would be a good choice for a constant, as would the local TAX_RATE (0.06). (Note that by convention, we capitalize the names of constants.)
The const is part of the latest standard for JS. Because it causes an error when it is not recognized, we will use var instead.
NaN
Acronym for Not a Number. This occurs (too) frequently because we are not careful using JS's automatic type conversions and because users sometimes enter data incorrectly. The isNaN() function can be used to test for this error. When applied to a string, isNaN() returns true for text that cannot be converted to a number (because the string is Not a Number. Example.
parseInt()
This built in function tries to retrieve an integer value from the text string you give it as a argument. The result is NaN if the text cannot be correctly converted, so it is best to test the string first with isNaN(). You can also use isNaN() to test a numeric variable before using it as a number.
How can a numeric variable not be a number? If you haven't initialized it with a numeric value yet.
parseFloat()
Same as parseInt(), except it tries to retrieve a decimal number (such as 1.234) from the text.

Text boxes
var
  • You can create variables on the fly just by using the name you create
  • Or you can explicitly let the browser and anyone who reads your code know that you are defining a variable
  • Use the var keyword to do this:
    var taxRate; var donut, numCakes;
  • Variables can hold numbers or strings
  • javascript treats all data as text/strings unless specifically told to treat them as numerics. So, BE CAREFUL!
    numbers and expressions
    • We need to tell JS to treat anything we get from the user as a number.
    • The function for treating text as an integer is parseInt();
    • The function for treating data as a real number is parseFloat();
      var userInput;
      var myNumber;
      
      userInput = document.getElementById('someTextBox');
      myNumber = parseInt(userInput);
      
      myNumber = myNumber + 3; 
      			
      
      Enter a value and then
    • Try entering a number such as 50
    • Now try a word such as hello
    • Now try 50hello
    • When the user enters a word, we cannot do addition since it is not a number ( NaN )
    • Variables can also hold decimal numbers:
      var TAXRATE = 0.0925;
      var DONUTPRICE = 0.50;
          
    • We call these floating point numbers
    • We can also change numbers to floating point using
      parseFloat()
    • We will learn how to make sure that NaN doesn't cause unwanted problems when we cover if statements in Chapter 7. But here's a preview:
      if (isNaN(numCakeDonuts))
             numCakeDonuts = 0;
      
    • We can do mathematical expressions uing the following
      	+	addition
      	-	subtraction
      	*	multiplication
      	/	division
      	( )	to get the correct order of operations
      

    Programming
    • To include javascript code in your html code you will need to encompass it with the script tag:
      <script type="javascript">
      and the end script tag: </script >
    • The code gets pretty messy if we try to put it all inside of an onClick=""
    • And, the nested quotation marks won't be such a problem
    • In top down programming, you try to identify all of the features and all of the possible bugs ahead of time. With this engineering-style approach, a lot of work is done before any code is ever written. Software often fits the iterative process better.