JavaScript Language Syntax


JavaScript Basics

  • A typical script:

    <SCRIPT LANGUAGE="JavaScript">
    <!-- Hide script from old browsers
    document.write("Hello, net!")
    ...more JavaScript...

    // End the hiding here -->
    </SCRIPT>
     

  • JavaScript comments

    // -- for inline comments
    /* ... */ -- for multi-line comments

  • Statement separator - semicolon (;)
    Only needed to separate multiple statements on the same line
  • Variable names
    • Can only have alphanumeric characters plus the underscore character (_)
    • They can not start with a digit
    • Cannot use reserved JavaScript keywords either
    • Sample variable names:
      Valid names:
      count, Count, try1, num, showMessages, table_index, i, j, k
      Invalid variable names: count$, my-name, 2cows
  • JavaScript is very case-sensitive!
  • Declaration and assignment statements

    variable_name
    var variable_name = "Hello"
    // -- preferred
    message1 = "Hello" // -- is OK too
    var count=100

  • NoScript tag - to notify users or take different action if JavaScript is not available or enabled.

    <NOSCRIPT>
    Please use a browser with JavaScript enabled to view this document.
    </NOSCRIPT>

  • Selective JavaScript version snippets

    <SCRIPT LANGUAGE="JavaScript1.1">
    <!--
    Run on JavaScript 1.1 browsers only
    document.write("...from
    JavaScript 1.1")
    ...more JavaScript...
    // End the hiding here. -->
    </SCRIPT>

    <SCRIPT LANGUAGE="JavaScript1.2">
    <!--
    Run on JavaScript 1.2 browsers only
    document.write("...from JavaScript 1.2")
    ...more JavaScript...
    // End the hiding here. -->
    </SCRIPT>


Data Types

  • Numbers

    dec_number = 255 // -- decimal is default
    hex_number = 0xff // -- hex value of FF (255)
    fp_number = 2.456 // -- Floating point number

  • Boolean operators
    A boolean value can only be true or false.
  • Character strings

    var mystring = "University"
    emailaddress = 'itl@uic.edu'
    thisYear = "1998"
    myQuote = "Let's do it!"

    •  

  • Data type conversion
    JavaScript is a loose type language
    var myval = "water"  // -- myval initialized
    myval = true         // -- myval is boolean true
    myval = 98           // -- now myval has an integer

NOTE: User input entered via a form element is usually read as a string. If you need to use it as a number, you need to first convert it with the parseInt or parseFloat built-in function

    myStrVar = "24"
    myIntegerVar = parseInt(myStrVar)

    myStrVar = "24.75"
    myFloatVar = parseFloat(myStrVar
    )

  • Operator precedence – same as in other programming languages

    higest priority: () e.g 5*(4+5)
    followed by: ++ e.g. ++1 or 1++
    followed by: -- e.g. --1 or 1--
    highest to lowest: *, /, %, =, -, ...and so forth

  • String operators

    String1 = 'Java'
    String2 = 'Script'
    // -- Concatenate to get "JavaScript"

    String3 = String1 + String2


Conditionals

  • The if/else statement
    It requires a boolean expression to decide between two alternative actions.

  • if (x > 0) {
    document.writeln("
    x is positive");
    }
    else {

    document.writeln("
    x is negative");
    }

  • The for loop
    The for loop instructs the computer to repeat a piece of code, a specific number of times.

    for (initial, condition-check, increment)

    for (j=1, j<10, j++) {
    document.writeln("This is loop#", j);
    }

  • The while loop
    Simply loops until some condition is true.

    var n = 5
    document.write("n! of ", n);
    var fact =1;
    // -- Compute n factorial (n!)
    // --
    where n is a non-negative integer
    while (n > 1) {
    fact = fact * n
    n = n -1
    }
    document.writeln(" is ", fact);

  • Also, break, continue and labels; plus, Do While and Switch in JavaScript 1.2.

Functions

JavaScript, like most programming languages, has facilities for creating subprograms to modularize or divide programs into distinct functions. When required, a function can be called to carry a particular task. In general, functions in JavaScript should be placed in the <HEAD> portion of the document to ensure that they are loaded before they are called.

Why should you use functions?

  • To exploit reusable code
  • They are easier to debug and test
  • Functions are much easier to maintain
  • They help you write clean structured programs

JavaScript functions behave a little differently than you might expect:

  • There is no value/reference distinction
  • There is no data type distinction
  • Return values do not have data types and are optional!

A couple of examples

function max(a,b) { 
// -- Multiple Returns if (a > b) return(a); // -- Return a else return(b); // -- Return b }
function verifyEmail(email) {
  /* -- Description: Checks for valid email addresses.
      Arguments: email - a string with an email address.
      Returns: false if any field is deemed invalid; 
true otherwise */
  if ((email.indexOf ('@', 0) == -1 || 
     (email.indexOf ('.', 0) == -1)) {
      // -- An email address should contain at least 
// -- one at-sign (@) and one period(.).

alert("Enter your Email address");
return false } return true; } ... <FORM NAME="signup" ACTION="..." METHOD=POST onSubmit="return verifyEmail(signup.txtEmail.value)"> Email Address:
<INPUT TYPE="text" NAME=txtEmail VALUE="" SIZE=40> <INPUT TYPE="submit" NAME="submit1" VALUE="Submit"> </FORM>

 

JavaScript Seminar Home | Previous | Next


Last Modified: March 2, 2001 — UIC Instructional Technology Lab