JavaScript: Introduction.

To make our HTML pages interactive we can use JavaScript. JavaScript is a special programming language designed for this purpose. It doesn't require any compiler. Code written on JavaScript is ran by web browsers. This language has syntax close to the Java syntax, but this is a completely different language. To include JavaScript code in your HTML document we need to use new HTML tag <script> with corresponding closing tag </script>. Everything what appears between these two tags is considered by a browser as script and will be interpreted. Tag <script> has optional parameter language value of which indicates what language we are using as a script language. The default value for this parameter is JavaScript. <script> tag can appear in any place of your HTML page. Traditionally all functions are declared in the script subsection of the header section, but you can put them in any other place. Here is an example of an HTML file that uses JavaScript:

Comments in JavaScript.

One of the important parts of any language are comments. Comments is a way to hide some text from the interpreter and don't make it run those text. There are two types of comments in JavaScript:
  • one line comments
  • multi-line comments.
    One line comments starts with // (two slashes, no spaces between them) and hide everything between these slashes and the end of the line:
    // this is one line comments
    function my_function()
    {
      alert("Hello!"); // display a message
    }
    
    Multi-line comments start with /* (slash and star) and end with */ (star and slash) and hide everything between them:
    /*
     This function displays an "Hello" message by calling alert() function.
     This line is just another line of comments. 
     */
    function my_function()
    {
      alert("Hello!"); // display a message
    } 
    
    Comments are extremely useful to add some notes to your code to make it more readable or to hide a portion of your code from your browser during the debugging.

    Variables in JavaScript.

    Variables in JavaScript are nothing but a named space to store some values. We can store four different types of values:
  • integer numbers (1, 3, 14, -10)
  • floating point numbers (12.9, -9.9, 12E3)
  • strings ('Hello' or "Bye")
  • boolean (true or false)
  • objects - you can think of an object as a container of other variables
  • arrays of variables of any other type.
    Unlike many other languages programmer doesn't have to specify a type for a variable in JavaScript. Any variable can store a value of any type. To declare a new variable we need to use keyword var:
    <script>
      var str = "Hello";
      var sum = 123;
      var count = 4;
      var avg = sum/count;
      var ExitCondition = false;
    </script>
    
    JavaScript is a case sensitive language. That is, variables sum and Sum are different variables.
    It is clear what are usual variable types (numbers, strings, and boolean values) now let's talk about objects. For now you can think about an object as a way to combine several usual variables together. For example, if we are taking about a rectangle we are having in mind its sizes (width and height), its color, and its position (X- Y-coordinates of one of the angles). If we need to remember all this information inside a JavaScript code it would be convenient to have it all in one place, but not scattered into several variables. Here is how we can do it:
     var rect = new Object();;
     rect.width = 190;
     rect.height = 50;
     rect.color = "blue";
     rect.X = 12;
     rect.Y = 10;
    
    The first line creates a new object rect using construction new Object(), and five other lines assign specific properties of the object. Our variable rect is a container that includes usual variables
  • width (containing integer value 190)
  • height (containing integer value 50)
  • color (containing string value blue)
  • X and Y.
    Moreover, objects can contain not only usual variables, but also other objects. For example, let's create another object circle that contains information like radius, color, coordinates of the center):
     var circle = new Object();;
     circle.radius = 100;
     circle.color = 'red';
     circle.X = 200;
     circle.Y = 150;
    
    and an object picture that has width, height, a rectangle, and a circle:
     var picture = new Object();;
     picture.width = 600;
     picture.height = 400;
     picture.Circle = circle;
     picture.Rectangle = rect;
    
    Now, we can access any piece of information from picture like this:
     picture.Circle.radius = picture.Circle.radius + 10; // increased radius by 10
     picture.Rectangle.color = "yellow"; //change color of the rectangle
    
    There is another way to access properties of an object. We can treat an object as an array and use property's names as indexes of this array. For example, to access property width of object picture we can use either of these methods:
    picture.width
    // or
    picture["width"]
    
    Thus, we can access the whole sub-object circle of the element picture by picture['Circle'] (case-sensitive!!!) and then we can access each element of this sub-object by typing something like:
    pricture["Cirle"].color = "yellow";
    

    Manipulation with variables. Operators.

    To deal with variables there are a set of operators. The simplest thing we can do is to assign a value to a variable.
    var str;
    str = "This is my string";
    
    We can also use simple math operators as +, -, *, and / for all numbers and for strings we can use operator + to add two strings together:
    var str1 = "This is";
    var str2 = "another string";
    var msg = str1 + " " + str2; // now msg = "This is another string"
    

    Below there is a table that contains JavaScript operators:
    Common Arithmetic Operators
    Operator Description Example
    + Adds two numbers a = b + 12;
    - Subtract one number from another b = 32 - width;
    * Multiplies two numbers area = width * height;
    / Divides one number by another. avg = TotalSum / Counter;
    % Returns the integer remaining after division. remnd = 1234 % height;
    ++ Increments a variable by one. counter++;
    -- Derements a variable by one. size--;
    Common Comparison Operators
    Operator Description Example
    == Returns true if the operands are equal. var check = (a == 12);
    != Returns true if the operands are not equal. if( size != 0 ) ...
    === Returns true if the operands are equal and of the same type. check = (widht === height);
    !== Returns true if the operands are not equal or not of the same type. if( width !== height ) alert("Error!");
    > Returns true if the first operand is greater than the second. if( width > height )...
    < Returns true if the first operand is less than the second. while( counter < size ) ...
    >= Returns true if the first operand is greater or equal than the second. if( elem_num >= first ) ...
    <= Returns true if the first operand is less or equal than the second. if( elem_num <= last ) ...
    Common Assignment Operators
    Operator Description Example
    = Assigns the value on the right side of the operator to the variable on the left side. msg = "This is a string";
    += Adds the value on the right side of the operator to the value of the variable on the left side and assigns the new value to the variable. counter += 3; // if counter was 7, then now it's 10
    -= Subtracts the value on the right side of the operator from the value of the variable on the left side and assigns the new value to the variable. counter -= 3; // if counter was 7, then now it's 4
    *= Multiplies the value on the right side of the operator on the value of the variable on the left side and assigns the new value to the variable. double_me *= 2;
    /= Divides the value on the right side of the operator by the value of the variable on the left side and assigns the new value to the variable. half_of_me /= 2;
    %= Divides the value on the right side of the operator by the value of the variable on the left side and assigns the new remainder to the variable. x %= 3; // if x was 17, then now x is 2
    Common Logical Operators
    Operator Description Example
    && Returns true if both operands are true. check = (x
    || Returns true if either of the operands is true. if( (counter>=size) || error_happened ) ...
    ! Returns true if the operand is false. if( ! checked ) ...

    Data Object Model.

    While a web browser interprets an HTML document it creates some JavaScript objects, which can be accessed from scripts. Using JavaScripts designer has control over these objects, and thus, over the document. The two most highest level objects are: This picture just shows the hierarchy of the JavaScript objects created by browser. In the future lectures we'll learn how to use them. We will be especially interested in the object document and its sub-objects all and form. Both of these objects are actually arrays that contains: Here is a short example:

    Examples below illustrates another way of accessing elements of a form by name. To access an element of a form we need to give names to both the form we want to access an element of and the element:
    Code Result
    <form name=testform>
     User name: <input type=text name=user> 
     <input type=button value="Click here to access the text" 
            onClick="alert('User name: '+document.testform.user.value);">
    </form>
    
    User name:
    <form name=testfrm>
     User name: <input type=text name=user> 
     <input type=button value="Click here to access the text" 
            onClick="alert('User name: '+document.forms['testfrm'].elements['user'].value)">
    </form>
    
    User name:

    And here you'll find an example that shows how many properties have form objects such as input, textarea, and button.