find EECS 1550 Javascript Topics Last updated 2015 February 24

Javascript topics

Javascript examples

Debugging

Using JSlint

You check Javascript syntax using JSLint.

It is very strict and imposes style conventions in addition to syntax. I set the following options to remove "errors" that are not errors.

Javascript console

Use the function console.log(String); to log messages to the Javascript console. To activate the console use the following.

Script element

SCRIPT elements can appear in the following locations.

SCRIPT elements in the HEAD are loaded before the contents of the page is loaded. SCRIPT elements in the BODY are loaded when they are encountered, as a consequence, it is frequently the case that the last tag in the BODY is a SCRIPT tag wherein the Javascript modifies the contents of the fully loaded page.

Variables — Program memory

Memory is represented by a collection of boxes, called variables, that contain data.

Variable scope

Variables can have global and local scope
Local variable
Declared within a function, referenceable (visible) only within the function
Global variable
Declared outside of a function, referenceable (visible) everywhere within a script.

Types of variables

Variables are objects with properties depending upon their type. The following lists the types of variables in Javascript.

typeof(), undefined and null types

Javascript is an untyped language; i.e. a variable can be assigned a value of any type at any time. However, operations are specific to particular types. As a consequence, it is necessary, in some circumstances, to verify the type of a variable to ensure it is of the correct type for the operations that need to be done.

if (typeof(aVariable) == "number") { /* doing arithmetic is safe */ }
else { /* Not safe to do arithmetic */ }

The function typeof(variable) returns a string containing the type of the variable where the return type is one of the following.

Datatype conversion

Program statements

Program statements correspond to sentences in a language. Some sentences have a simple structure and some have a complex structure.

Assignment statement
variable = expression;

The expression reads the values of variables and combines them according to the operations in the expression, and then stores the resulting value in the variable on the right of the equal sign.
          a = 3 + 4*(5-7).
          b = 3 * a.
Function call
functionName(argument_list)

A preexisting set of instructions with the name "functionName" is executed using the information given in the argument_list). In the first example alert is the functionName and "The network is down" is the single argument given to the function. Changing the argument list will result in similar but different output.
          // Display The network is down on the screen.
          window.alert("The network is down");
          // Display Please enter a number on the screen.
          window.alert("Please enter a number");
          // Display Line 51 has an error on the screen.
          window.alert("Line 51 has an error");

All arguments are optional

Can nest function defintions: inner ones are hidden (private)

Methods: Static and Instance

The prompt and confirm popup boxes

With the window.prompt("prompt message") operation the user can enter data in a popup box. When cancel is pressed the value null is returned. When OK is pressed the entered data string is returned.

With the window.confirm("confirm message") operation the user can press Cancel, whereupon the value true is returned, or the user can press OK, whereupon the value false is returned.

Control structures

There are three types control structures in writing a program in any language.

A sequence of statements

There is no special syntax. In all languages it consists of writing one statement after another.

A choice of statements

In Javascript there are two structures that deal with choice.
  1. if … then … else
              if (condition) {
              then phrase statements
              }
              else {
              else phrase statements
              }

    if then else example.

  2. Switch statement, written in Javascript as follows
              switch(n) { // n is typically an integer, character or string
              case n_value_1:   case statements; break;
              case n_value_2:   case statements; break;
              default:   default statements;
              }

    switch example.

A loop of statements

In javascript there are four different loop structures. Each one is the best one to use in some circumstances.

  1. Standard for loop
    Good to use when you can count either up or down and will terminate when the counter reaches an appropriate value; i.e. you know ahead of time the number of times you need to go around the loop. For example processing the elements of an array or list.
              for (initialize loop variable ;
              end test for loop variable ;
              increment/decrement loop variable) {
              loop body statements
              }
  2. while loop
    Go around the loop zero or more times.
    Good to use when you do not know ahead of time how many times you may have to go around a loop. For example: in a game loop until you find a good move, where the body of the loop explores different moves, rates them and the loop exits when a good enough move is found.
              while (continue condition) {
              loop body statements
              }

    while example.

  3. do-while loop
    Go around the loop one or more times.
    Use in situations simlar to the while loop, except you must be happy to go around the loop at least once.
              do {
              loop body statements
              } while (continue condition);

    do until example.

  4. for-in loop
    In Javascript use this loop for lists of property-value pairs. For example: the list of components of an object literal; the list of property-value pairs in a style definition; the list of attributes for an HTML element.
              for (variable in collection) {
              statements using the variable
              }

    for in example.

Comments

Javascript has two types of comments.

Writing to HTML elements

Javascript can write an HTML element to a page. We will look at this in more detail when we discuss the DOM model (Domain Object Model). For now here are typical statements to use.

Add a new element
Adds the element to the page at the point at which the function is called.
document.write("<p>A new paragraph added to the page");
Change the contents of an element
Find the element by its id then change its contents.
document.getElementById("ElementID").innerHTML = "NewContents";
Change an attribute value of an element
Find the element by its id, then set an attribute value.
document.getElementById("id").setAttribute("attributeName", "Value");

Error handling

Sources of errors

Error types

Catching & throwing errors

Try, catch and throw example.

Regular expressions

Regular expression topics are here.

Canvas

You can draw on a page with Javascript using the Canvas element. Here are a couple of sites to help you learn about that element.

Here are some examples using the canvas element.

Browser objects

Cookies