JavaScript

 
Instructor: Michael Wilson

CSIS 135  GCC Homepage   Grossmont College 
Cheat Notes _   Schedule    Assignments    Cheat notes    Home  

   italic items in script examples are optional  
alert, prompt, confirm escape characters functions multidimensional arrays parseInt( ) / parseFloat( )

string properties & methods

arrays event handlers

if

naming rules passing Arguments strings - case

break

expressions

loops - do...while NaN / isNaN( ) random numbers  switch
continue external .js loops - for object types return variable scope
data types forms (all elements) loops - for ... in operators status bar variables
else if   loops - while order of precedence    
           

<script language="Javascript" type="text/javascript">
statement;
statement;
statement;
</script>


  Variables
declaring a variable
var name //simple declaration. "var" required.

//declaring a variable and assigning a value
var name = "Bob" //"var" optional, but use it!

// assigning a new value to an existing variable 
name="Mike"
//only use var when first creating the variable!

//declaring multiple variables with values in one statement
var userName="Bob", userColor="blue"


Functions (the type you write. see "built-in Functions" below)

Functions require 2 parts: 1 - the "Definition" and 2 - the "function call"

1. Defining/declaring (only reads code into memory, to be called later)

function functName( argument1, argument2 ) {    
    statement;
    statement;
    return variable_name;
    }

The argument names names above are optional, and if used, act like local variable names within the function and take the values (called "arguments" or "parameters" ) that are "passed" when the function is called.)

function calcArea(heightX, widthY) {
      var areaXY = heightX * widthX;
       return areaXY;
     }

Passing Arguments (optional) If a function will need unique values to do its job, best practice is to pass the values as arguments when you call the function, rather than have the function access global variables.

calcArea(height, width )
     note: arguments can be literal values or variables

return (optional) is used to output the result of the function's processing. If the f
unction only executes an action, it doesn't need to use return. The value is returned to the point at which the function was called. "return" can only be used once (usually as the last line) of the function. Only one value can be passed by the return, unless an array is returned.

2. Calling the function (actually starts or "executes" the function) Only the name of the function is required to execute the function.

example: calcArea(height, width )

If the function called uses return, the code MUST include some way to use the returned value. The function call effectively becomes an expression, which resolves to a single value: the value returned.

example: var nameEntered = askForName()
example: document.write("Hi " + askForName() )


Built in Functions - Don't have "object. " before them, usually need arguments and ALWAYS return a value.
Example: var num = parseInt("5")

Methods are a type of Function that belongs to an object. They must always be preceded by the object they are affecting (except for the widow object, as in widow.alert() )
Example: document.write("abc") -- write("abc") can not work by itself.)
Exception example: alert("Now you\'ve done it!")


Alert box
-- just passes info
-- only has an "OK" button
-- nothing is returned.
example: alert("Now you\'ve done it!")

Prompt box
-- gives user direction on what to enter
-- has a textbox the user can type into
-- code can insert default text into textbox
-- has "OK" and "Cancel" buttons
-- "OK" returns text entered in textbox
-- "Cancel" or closing the box returns value of "null"
--JS must be written to take the value passed back (usually with a variable)
example: var whatTyped = prompt("Type your name", "In this box")

Confirm box
-- usually asks a question
-- has "OK" and "Cancel" buttons
-- "OK" returns a value of TRUE
-- "Cancel" or closing the box returns FALSE
-- usually the test in an "if" statement.
example: confirm("Are you sure?")


Arrays

declare (create): var daysOfWeek = new Array(7)

enter or change data: daysOfWeek[0] = "Sunday"  (on left)

read element: var firstday = daysOfWeek[0]     (on right)

declare with values: var daysOfWeek = new Array("Sunday","Monday", etc.) (fills indexes in order starting with 0)

single property daysOfWeek.length

-- not restricted to array size defined in declaration
-- don't have to fill data in sequential order
-- can leave indexes unfilled (no data)
-- can mix data types within same array
-- reading an empty index results in "undefined"
-- index can be text based, but may be hard to work with. e.g. groceryList["meat:"] = "beef"

Array Methods -- all directly modify array, not return a modified version!

pop() -- remove last element
push() -- add element to end of array
shift() -- remove first element, all other elements move down and are renumbered
unshift() -- insert new element in first index, all others are renumbered
sort() -- alphabetical/numeric value reorder. A function named in instance (without "()" ) can define the sort order. Function defined as taking 2 arguments and will sort array 2 elements at a time.
reverse() -- the order of elements is reversed
splice() -- concatenates 2 arrays
split() -- actually a string method that splits a string into an array of elements divided by the delimiter defined in instance e.g.  (", ") No delimiter defined will return "undefined" values.
join() -- concatenates array elements into a string, separated by optional argument e.g. var mylist=buyItemsArray.join(", ")
An empty instance inserts a comma by default, and an empty string will concatenate solidly.

 


Multi-Dimensional Arrays  An array of arrays. Each index of the top level holds an array of usually similar data. Each index of the extend arrays usually holds related data across all arrays.

declare top level array: var workerData = new Array( )

create second level:
workerData[0] = new Array( )
// has no name
workerData[1] = new Array( ) // has no name

entering data
workerData[0] [0] = "Bob Johnson"
//each array is an employee
workerData[0] [1] = "accounting"  
   //each index is data on that employee
workerData[1] [0] = "Betty Jones" 
//second array is another employee
workerData[1] [1] = "marketing"

Index [x] of each sub-array is usually related: [0] is all names, [1] is all departments


Expression -- multiple elements that JS can resolve to a single value
Operand -- variables & literals used in expressions
Operator -- symbols used in expressions
---binary operator: needs an operand on either side of it A>B or counter=5
---unary operator: works with only one operand a++ or --a  or -a


Operator Types:

1. Arithmetic: does math   +  -   *  /   %(modulus) 
count * 5

2. Assignment: assigns value to variable 
theAnswer = 5
(5 = theAnswer
will not work!!!)

3. Comparison: compares 2 operands & returns a boolean.
   == is equal to
   === is equal to (inc same type)
5=="5" // true
5==="5" // false
   != is not equal to
   !=== not equal in value or in type
   >, <, >=, <=
5 <= count
"aba" < "bark"
//true - alphabetically

4. Logical: combine boolean comparisons to return a boolean
&& AND, || OR, ! not
a<b && b<c // True if both true
a<b || b<c
// True if either is true
n>10 ! n==15
//True for any value >10 except 15
(n>10 ! 15 would be wrong. 15 is not boolean)

5. String: only + and += (and -=, though not well)
var name = "mike"
name += " wilson"

There are many functions for manipulating strings


String properties, methods()
one property: length
var charCount = name.length

methods that return a value without changing the string
charAt(index) -- returns single character at that index position
indexOf(string, fromIndex) -- returns first index posit of first char of string, starting from optional fromIndex
lastIndexOf(text, fromIndex) -- same as indexOf(), but works backward from end of string
split(delimiter) -- converts string into an array, dividing string by optional delimiter e.g. myList.split(", ")
substring(strtIndx, endIndx) -- returns a substring starting at first argument UPTO (not including) second argument index position.
toUpperCase() -- returns string converted to all capital letters
toLowerCase() -- returns string converted to all lower case letters

methods that change the string's formatting, not just return the change.
link(href)
bold()
fontcolor(color)
fontsize(size)
italics()


string case  changing the case of a text string. Very useful for conditional statements so you only have to test for one capitalization possibility.
   if(name1.toUpperCase() == "BOB")      will not have to test for Bob, bob, boB, bOb, etc.

var name1 = "Bob"
var nameCaps = name1.toUpperCase()             // gives BOB
var nameLwrCase = name1.toLowerCase()      // gives bob

(no change to original value)

name1=name1.toLowerCase()
(original changed)


Decision (flow control) structures

"if" structure
syntax:
     if (condition)
        {
        statement(s)
//executes if conditional True
        }
        else
        {
        statement(s)
//executes if conditional False
        }

-- { } are optional if true is only a single line, but best to always use them.
-- if without else: OK, else without if: NO!


"else if" structure usually used when >2 values or conditions possible. Still must resolve to T or F.

syntax:
     if (condition_1)
        {
        statement(s)
//executes if conditional True
        }
     else if (condition_1)
//same condition
        {
        statement(s)
//executes if conditional True
        }


Nested "if" structure
syntax:
     if (condition_1)
        {
        statement(s)
//executes if conditional True
        if (condition_2)
             {
             statement(s)
//executes if BOTH conditionals True
             }
//closes nested if
        }
// closes top level if

-- for decisions to be made only under certain circumstances, nest them within another if
--use indention to keep structures clearly separated

Position of Nested Else

     if (condition_1)
        {

        if (condition_2) // only if 1st true
             {
             statement(s)
// 1st & 2nd true
             }
             else
             {
            
statement(s) // if 1st True, 2nd false
             }
// closes else
        }
// closes first if

is not the same as:
     if (condition_1)
        {

        if (condition_2)
             {
            
statement(s)
             }
        }
// closes 1st if
        else
// 1st False (2nd if never executed)
        
{
        statement(s)
        }
//closes else   


Switch structure
syntax:
     switch (matchThis) //must be some value (literal, var, or expression) to compare to. Not a boolean expression!!!
       {                        
// don't forget { }
        case valueA:
// don't forget colon
                statement(s)
//executes if valueA==matchThis
                break
// exits switch structure without comparing further cases
        case valueB:
                statement(s)
//executes if valueB==matchThis
                break
        default:
  // optional
                statement(s)
//executes if no case values equal matchThis
         }

-- no break needed with default!

-- if break omitted: once match is made, all statements are executed until a break is encountered, even statements of cases that don't match. This is useful if multiple cases would execute same code.
       example: switch (guess) //correct number is 4
                               {
                                case 1:
                                case 2:
                                case 3 :

                                    document.write("Your guess is too low")
                                    break
                                case 4:
                                    document.write("Good guess!")
                                    break
                                }
             if guess is 1, 2, or 3, it would execute the "too low" but not "Good guess!"


random numbers  creating an unweighted random number within a specified range
Math.random()  is the core if it. This resolves to a number between 0 and 0.9999. (basically between 0 and almost 1)
To get whole numbers, multiply and round.

      --for a random integer between 0 and 5:
Math.floor(Math.random() * 6)
The *6 will give possibilities between 0 (6*0) and 5.9998 (6*0.9999) The Math.floor() rounds down to the nearest integer.  Math.round() would round up or down to the nearest and give an uneven probability to the lowest and highest numbers in the range.

     -- for a random integer between 1 and 5
Math.floor(Math.random() * 5 +1)
The multiplication is done first, and then one added. Possibilities between 1 (5*0 +1) and 5.9998 (5* 0.9999 +1) Rounds down to 1-5.

     -- for a random integer between 10 and 20
Math.floor(Math.random() * 11 +10)
The 11 will give you 0-10 and adding 10 will bring that up to 10-20


term  text

codeExample

moreText


term  text

codeExample

moreText


term  text

codeExample

moreText




 

hiding from older browsers
<-- This will hide from older browsers
statement;
statement;

// end hiding form old browsers -->
<noscript>
Your browser does not support Javascript needed to properly view this page
</noscript>


referencing an external JS source
<script src="functionLibrary.js">
//NO HTML in .js file, NO <script> tags in .js file.


Variable name rules:
    - No reserved words
    - No special characters except "_"
(underscore)
    - Can't start with a number
    - NO SPACES!!!


Objects                   
Properties               object.property
Methods()                object.method(arguments)


  1. Simple Objects: can be used directly. example: document.bgColor
  2. Built-in Objects: Most are like templates -- the object can't be used directly (because you can have more than one of them, so you create an "Instance" of the object. see below) example: Date(), Array() Some can be used directly like Math
  3. Instance of an Object: Created from built-in objects with keyword "new" and the "Constructor" form of the object. (note the parentheses and the capital letter) You give a unique name to every instance.
    Example:
    var daysofweek = new Array()


Variable Scope:
--Variables are usually Global
--If declared using "var" within a function, variables are Local.
--Local variables take precedence over Global within the function and are NOT accessible from outside the function.  Local variables cease to exist after their function executes.


Events user. form element or navigator actions.
click, mouseOver, mouseOut, focus, keypress, blur, load, unLoad, etc.

Event Handlers (event beginning with "on" ) Formatted as an attribute to an HTML tag.
<a> tag can take onClick, onMouseOver, onMouseOut
<body> tag takes onLoad  & onUnload
<form> can take onSubmit, onReset, onLoad
<input type="text"> takes onBlur, onFocus, onChange
<input> of types: button, radio, checkbox, submit, & reset all take onClick
**<img> needs an <a> to make it work with mouse events in older browsers!!!

example: <a href="#" onClick="runThatFunction()"> Run a function </a>

"return" in event handlers: before a function call will cancel the normal HTML action if a "false" is returned from the function. Function must return a boolean <input type="submit" onsubmit="return validate()" >


Writing to status bar from a link rollover
<a href="http://cnn.com" onMouseOver="status='HELP';return true">
//notice especially the nesting of the single and double quotes.


Data Types (nature of data held by variable)

Primitive Composite
  • Integer numbers
  • Floating-point numbers
  • Boolean values
  • Strings
  • Null values

(collections of data with a single name)

  • Functions
  • Arrays
  • Objects

var isWhich = typeof(lastname) Objects, arrays, and null variables will all return "object"

var nothing = "" is called an "empty string" NOT the same as null or undefined


Escape Character a"\" combined with special characters JS is sensitive to or with certain letters is an "Escape Sequence"

\r or \n starts a new line
\t inserts a tab space
\' or \" means JS should ignore the quote and treat it as a quote within a text string.
\\ means ignore the second \

alert("Enter your Social Security Number \n (without hyphens) ") will write on 2 lines in the alert box

use within a string where it is meant to be part of the text. alert("Didn\'t they say \"Go\" ")


NaN -- value returned if arithmetic expression contains operands that are not numbers  var count = 5 - "bob"

function isNaN(stringvar) tests if instance is or can be converted to a number -- returns a boolean value. 5 => True, "5"=> True, "bob":=>false
       


Prefix v. Postfix operators (unary arithmetic)
var A = 3
var B = ++A // changes A to 4, then B is 4
var C = A++ // C is 3, THEN changes A to 4
A++ // simply increases A by 1
-A // changes the sign of A, cannot be Postfix


Shorthand Assignment Operators

+=     -=     *=    /=    %=
1st operand does calculation using 2nd operand and takes resulting value.

A = 5
A *=5
// A is now 25  Same as A = A*5


THE "Conditional Operator"  A statement structure that is a truncated if statement. Don't confuse with "conditional operators" --the group of symbols uses to compare operands.)
Syntax:
boolean_expression? doIfTrue: doIfFalse
guess==5? ans="Good guess":ans="Sorry"


Combining numeric values and strings
mixing yields a string.
5 + 5   //10
5 + "5"    // "55"
5 + 5 + "ish" // "10ish"

5 + 5 * "ish" // NaN


Operator Precedence

() or []
! or - or ++ or --
* or / or %
+ or -
< or > or <= or >=
== or !=
&&
||
= or += or -= or *= or /= or %=
,

best to use nested ( )s to make the order of execution clear, even if not needed.


for structure  loop used when number if iterations can be known (from a literal value or a variable) at execution of the loop, as with counting to a certain number.
syntax:
for (initialize counter; test; increment counter)
        {
        statement(s)

        }
       

-- be sure to use a ; to separate arguments
-- 1. initializing of counter only done when first executing
-- 2. conditional expression is evaluated (test)
-- 3. if True, statements are executed
-- 4. counter increments
-- continues looping until test is False


While structure  loop best used when number of iterations is not knowable, as in with a guessing game.
syntax:
while (conditional expression)
        {
        statement(s)
//executes if True and loops through test again
        }

-- each loop execution is an "iteration"
-- continues looping until test is False
-- loop must include code to change conditional expression, else infinite loop will occur (condition will never be false) usually resulting in computer freeze and possible loss of data.
-- if statement starts as false, statements will not execute even once.

If using a counter:
var counter = 0 //establish before and outside loop
while (count<5)
        {
        document.write(count)
        counter++
  //affects conditional test
        }

NOTE: condition of loop is not dependent on value of "counter" here. "counter" only tracks iterations if needed.


do...while structure  (loop - upside down while)
syntax:
do
        {
        statement(s)
//will ALWAYS execute at least once
        }
while
(conditional expression)
       

-- continues looping until test is False
-- loop must include code to change conditional expression


for ... in structure  specialized loop that steps through specified array based on index number held in variable. Loop auto increments index counter.

for (indexNow in myArray)
       {
        statement(s)

        }       

-- before the loop, establish a variable (indexNow in the example code) to hold the value of the current index number for each iteration of the loop.
-- this index counter variable need not start with 0. (first position in array), but will continue until last element in array.
-- statements should somehow use the value of the current index (otherwise, what's the point?)


break statement
halts the loop at that point (statements in the loop AFTER the continue are not executed in that iteration) and then EXITS the loop after the closing }. No further iterations of the loop are executed.


continue statement
halts the loop at that point (statements in the loop AFTER the continue are not executed in that iteration) and then RESTARTS the loop for another iteration, starting with testing the conditional again. (like saying "skip the rest this loop")


parseInt( ) / parseFloat( )   converts strings to numeric values when possible. Integers [does a Math.floor() ] or Float for decimals. If string is mixed, converts as far as possible. If doesn't at least start with a number character, returns NaN

3+parseInt("6")  // gives
3+parseInt("6 is a string number
")  // gives
parseInt("The string number 6 ")  // gives


FORMs  Mostly HTML tags and HTML attributes, with the tags holding Javascript event handlers.

  • Form elements have properties and methods and MUST be in a <form> tag.
  • <form> tag's action, method, and target attributes optional if not submitting form to server.
  • name=" " attribute in <form> useful to Javascript
form arrays attributes of elements
how many?forms/ elements properties of elements
accessing form or element event handlers in forms
submit and reset all flavors methods used on elements
form element tags examples of form tags

  • document.forms[ ] is an array of all forms in the document
  • document.form[x].elements[ ] contains all elements in each form (in order, any type except type="image")

  • How many forms in document?  document.forms.length (or use names given )
  • How many elements in a form?  document.forms[1].elements.length (or use names given )
    Accessing Form and its Elements
  • Access form through EITHER:
    • name attribute document.myform
    • document object's form array document.forms[ ]   note plural, not form[ ]
  • Access elements within the form (to read or change) EITHER through:
    • name attributes document.myform.fname
    • array object's elements array within the document object's forms array  document.form[x].elements[y]   note plural, not element[ ]

  • All flavors of Submit and Reset
  • submit button (HTML-- no JS needed)
  • submit() (submits by JS code, not button needed)
  • onsubmit() (attribute of submit button that runs code before form is actually sent to server. Good for validation when used with return to stop submission if error found)
  • reset button (HTML)
  • reset() (same thing using JS)
  • onreset() to detect a reset button action.
    Creating elements within a form
  • <input > creates most and type="xyz" determines type
    • text, password, or hidden
    • checkbox or radio
    • button, submit, reset.
  • <textarea> creates a multi-line text area
  • <select> creates select box with one or more lines
  • note: <textarea> and <select> both require closing tags and select requires <option> elements

Element Attributes
  • ALL but<select> use name=" " (disabled="true" & tabindex="#") consistently, while all but form and select can take value=" ", but value attribute works a bit differently with each.
  • <text>&<password>  can have maxlength=" ", size=" ", readonly="true" (value enters default text)
  • <button>&<submit>&<reset> (value sets label on button)
  • <radio>&<checkbox>   defualtchecked or checked="checked" (value sets a hidden data value for each selection) In <radio>, name=" " MUST have the same value for each element in a mutually exclusive group.
  • <textarea> sets width with cols=" " and height with rows=" " wrap="hard" (sends <br> tags within submitted data) & readonly="true"
  • <select> size=" " for lines displayed, multiple to allow >1 selection, (no value attribute)
  • <option> selected="selected" (value is hidden data value for each choice)

    Form and Element Properties
  • All attributes are basically properties. Also:
    • all but form have type (even select and textarea)
    • all but form have form property for which form the element belongs to. note this is a bit odd as it is reverse of the "general.specific" pattern.
    • forms and select objects can have a length
    • radio object has index[ ]
    • select object has selectedindex

    Form Event Handlers
  • Most take onclick
  • Unique to <form> are onload, onsubmit & onreset
  • text, textarea, select, radio, & checkbox can take:
    • onchange
    • onselect
    • onfocus
    • onblur
    • onclick

  • Methods used on Form Elements
  • submit() and reset() can be applied to form object
  • focus() and blur() can be applied to all elements
  • select() applied to text, password and textareas; selects all the text
  • click() can be applied to radio and checkboxes and all buttons
             
    Note:
  • All have focus property, focus() method, onfocus() event handler
  • All have blur property, blur() method, onblur() event handler

examples:

<form name="myform" onsubmit="return validateMe()">
      Your name:
       <input type="text " name="myName"  value="" maxlength="25" size="10"> <br /> <br />

       <textarea name="notes" cols="25 " rows ="10" wrap="soft"> My Notes: </textarea> <br /><br />

       Musical Preference: <br />
       <input type="checkbox" name="musictype"  value="country" defaultchecked >Country <br />
       <input type="checkbox" name="musictype"  value="western" defaultchecked >Western <br /> <br />
        Your gender: <br /> 
       <input type="radio" name="gender"  value="male" >MALE <br />
       <input type="radio" name="gender"  value="female"> FEMALE <br /><br />

      Or pick it here:
      <select name="genderpick" size="1" onchange="checkThis">
              <option value="" selected ></option>
              <option value="male">Male</option>
              <option value="female">Female</option>
       </select>   <br /><br />

       <input type="button" name="calc" value="calculate" onclick="doCalcs()" >

</form>


Your name:


Musical Preference:
Country
Western

Your gender:
MALE
FEMALE

Or pick it here:  



term  text

codeExample

moreText


term  text

codeExample

moreText