JScript basics.

Comments in JScript.

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 JScript:
  • 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()
    {
      WScript.Echo("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()
    {
      WScript.Echo("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 the script engine during the debugging.

    Variables in JScript.

    Variables in JScript 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 JScript. Any variable can store a value of any type. To declare a new variable we need to use keyword var:
    var str = "Hello";
    var sum = 123;
    var count = 4;
    var avg = sum/count;
    var ExitCondition = false;
    
    Scalar Data Types
    Data type Description Example
    Undefined   No value assigned; a variable that has been declared, but doesn't have a value var c;
    Null The value of an undefined variable. st = Null;
    Boolean A logical value; either true or false var notDone = true;
    Number An integer or floating point numbers. var sum = 0;
    String Characters within a single or double quotation marks. var str = "short line";
    JScript is a case sensitive language. That is, variables sum and Sum are different variables.

    Using Strings

    Since JScript automatically types variables, we do not need to declare a variable as a string. All we need to do is to assign a string value; that is, assign any quoted string (we can use either single or double quotes).
    var str = "My name is";
    var name = 'Daniel';
    
    Probably, the most often operation on strings is concatenation of several strings. To do this, we need to use operator plus:
    var sentence = str + name + ".";
    
    Note that if we enclose numeric values within quotation marks, JScript will interpret these as strings, which can lead to strange result when we add them together:
    var one = "1";
    var two = "2";
    var sum = one + two;
    WScript.Echo('sum = ' + sum);
    

    String to Number and Number to String conversion

    Very often we need to convert a numeric variable or constant to a string. To do that we can use method toString() of the object Number. For example, the following example prints "12" as the sum:
    var one = 1;
    var two = 2;
    var sum = one.toString() + two.toString();
    WScript.Echo('sum = ' + sum);
    
    In fact, JScript often does the number to string conversion implicitly when we add number to a string, like we do in the following example:
    var one = "1";
    var two = 2;
    var sum = one + two;
    WScript.Echo('sum = ' + sum);
    

    To convert in the opposite direction, string to a number we can use one of the built-in functions:

  • parseInt()
  • parseFloat()
    The parseInt() function converts a string to an integer. The parseFloat() function converts a string to a floating point number:
    var first = "12";
    var second = "2.5";
    var sum = parseInt(first) + parseFloat(second);
    WScript.Echo('sum = ' + sum);
    
    We will discuss these functions with more details later. For now please find additional information here and here.

    Using Arrays

    JScript arrays are initialized with the new Array() statement. In the parenthesis we may specify the size of the array, although we do not have to do that:
    var grades = new Array(10);
    var books = new Array();
    
    As with C/C++. arrays always begin at 0. As we initialized an array we can insert values:
    grades[0] = 10;
    grades[1] = 8;
    grades[2] = 9;
    grades[3] = 8;
    grades[4] = 10;
    
    Property length of an Array object contains the number of elements inside the array. Thus, for the previous example grades.length is equal to 5.

    An interesting thing happens when we do not initialize the size of an array and insert elements there with gaps in indexes:

    var books = new Array();
    books[0] = "My first book";
    books[2] = "I lost one book";
    books[4] = "One more book";
    WScript.Echo("I have " + books.length + " books. They are: ");
    for(i=0;i<books.length;i++)
      WScript.Echo(i + ': ' + books[i]);
    
    In this example the size of the array is equal to 5, but two elements (with indexes 1 and 3 are undefined). To check if an element of an array is defined (or, in general, if a variable is assigned a value) we can use function typeof(), which returns a string containing type of the value. In the case of non-assigned variable it returns "undefined". Using the following if we can correct the output of the previous example:
      if( typeof(books[i]) == "undefined" )
        WScript.Echo(i + ': lost');
      else
        WScript.Echo(i + ': ' + books[i]);
    

    We can also combine declaration of a new array and assigning its values using the following syntax

    var grades = new Array(10, 8, 9, 10, 8);
    

    Objects

    Another composite data type is Object. In JScript, objects and arrays are handled almost identically. Both can have arbitrary properties assigned to them, and indeed Arrays are merely a special kind of Object. The difference between Arrays and Objects is that arrays have a "magic" length property, wich objects do not. This means that if we assign a value to an element of an array that is greater than every other element — for example, myArray[100] = "hello" — then the length property will automatically be updated to be 101 (the new length). Similarly, if you modify the length property of an array, it will delete any elements that are no longer part of the array.

    All objects in JScript support "expando" properties, or properties that can be added and removed dynamically at run time. These properties can have any name, including numbers. If the name of the property is a simple identifier, it can be written after the object name with a period, such as:

    var myObj = new Object();
    
    
    // Add two expando properties, 'name' and 'age'
    myObj.name = "Fred";
    myObj.age = 42;
    
    If the name of the property is not a simple identifier, or it is not known at the time you write the script, you can use an arbitrary expression inside square brackets to index the property. The names of all expando properties in JScript are converted to strings before being added to the object.
    var myObj = new Object();
    
    
    // Add two expando properties that cannot be written in the object.property syntax.
    // The first contains invalid characters (spaces), so must be written inside square brackets.
    myObj["not a valid identifier"] = "This is the property value";
    
    
    // The second expando name is a number, so it also must be placed inside square brackets
    myObj[100] = "100";
    

    The following example shows how to create an object and access all its properties like hash elements:

    var book = new Object();
    book.author = "William R. Stanek";
    book.title  = "Windows 2000 Scripting Bible";
    book["ISBN"] = "0-7645-4677-5";
    
    
    WScript.Echo("The following book is recommended for the class:");
    for ( pr in book )
      WScript.Echo(pr + ": " + book[pr]);
    
    To initialize an object at the same time we declare it, we can use the following syntax:
    var student = new Object( {name: "Bob", city: "Huntington", zip: 25755} );
    

    We can also create an array of objects (hashes) by combining two definitions together:

    var hash = new Array( { name: "Bob", city: "Huntington", zip: 25755},
                          { name: "William", city: "Ashland", zip:29874});
    
    for(i=0;i<hash.length;i++){
       WScript.Echo(i+1, ":");
       for(p in hash[i])
          WScript.Echo(p, ":", hash[i][p]);
    }
    

    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 JScript 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 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 ) ...