javascript notes

some of these notes may have been created from other online sources.

they are just my home schooling notes.


define the javascript code in the head of the document.
all the main functions and code is defined there.


declare a variable using the var keyword.
variables declared within a function have function-level scope. They only exist within that function
if you create a variable inside a function without using the keyword “var” then it will be created as a global variable.

variables are created by using the keyword “var” and then the variable name.
you can’t write x == NaN to determine whether the value of a variable x is NaN / Instead, you should write x != x.

var email = document.getElementById(‘email’);

finding out a variables type using the typeof operator:
abc = 5;
typeof abc;  // output = “number”

when using typeof on variables, if you use a variable which is undefined typeof will show “undefined”
when usinf typeof on variables that are null in value typeof returns “object”
aaa = null;
typeof aaa; //outputs “object”

with boolean logic undefined == null.
if (null == undefined) {console.log(“hello”)}  //output == hello

when you create variables and do not assign a number or string to them they will not pass boolean logic.
var a, b;
a == b; // false
even though a and b are the same (undefined variables) they do not == each other

var my_variable = 4;

var today = new Date(); //create date object today

declare multiple variables at one time:
var firstName = ‘Casey’, lastName = ‘Evans’;

boolean variables are true and false. lowercase

uninitialized variables are undefined
var unset; // Currently undefined.
Similarly, if a function does not actively return a value, then the returned value is undefined

null is a defined non-value and is best used to represent the consequence of an action that has no result

true and false values:
false == 0;  //true
false === 0; //false
String(false) == 0; //false
Instance of operator:
The instanceof operator expects a left-side operand that is an object and a right-side
operand that identifies a class of objects. The operator evaluates to true if the left-side
object is an instance of the right-side class and evaluates to false otherwise

var d = new Date(); // Create a new object with the Date() constructor
d instanceof Date; // Evaluates to true; d was created with Date()
d instanceof Object; // Evaluates to true; all objects are instances of Object
d instanceof Number; // Evaluates to false; d is not a Number object
var a = [1, 2, 3]; // Create an array with array literal syntax
a instanceof Array; // Evaluates to true; a is an array
a instanceof Object; // Evaluates to true; all arrays are objects
a instanceof RegExp; // Evaluates to false; arrays are not regular expressions
Notice that no space (whitespace character) appears in the expression because it would match the whitespace

all reg exp start with / and end with /
/[ characters ]/   //tells it to match any characters found in between [ and ]
/[a-l]/  //match all characters a through l
/[^a-l]/ //check if a-l doesnt exist
/d/   //check if text has any digits (numeric digits)
/d/   //check if text has any non digits (numeric digits)

var re = /Bob.*/i                                  //the regular expression (i means not case sensitive)
MyArray = re.exec(‘Hello, my name is Bobby.’)      //calls the exec of the regexp, the string could have been a variable name which contained the string
alert(‘Welcome, ‘ + MyArray[0])                    //pops up Hello Bobby

re = /^[(]?(d{3})[)]?[ -.]?(d{3})[ -.]?(d{4})$/    //regexp to validate a phone number
Working with frames:

onclick=”parent.topPage.ChangeContent()”  //parent specifys the frameset, topPage is the name of the frame

document.domain =  //set when pages from different subdomains need to interact
parent.bottomPage.focus();      //give a frame called bottomPage window focus

writing to child frames using javascript:             //open the topPage child frame
window.topPage.document.writeln(‘<head>’)  //write to the child frame
window.topPage.document.close()            //close the file

parent.topPage.Form1.WebPage1.value=’New Label’  //change an element in a form on webpage frame topPage

Rollover images

there is an array called images in the document object.
if the browser supports the document.images then it supports rollovers
best to put rollovers inside an if statement to make sure the browser supports them

if (document.images){
Browser supports rollovers. //rollover code here
else {
Browser does not support rollovers.

rollover example

<img src=”images/arrow.gif” onmouseover=”this.src=’images/arrow-over.gif'” onmouseout=”this.src=’images/arrow.gif'”>

Status bar , banners, slideshows:

window.status=’Trade secrets are revealed in the Demystified Series.’


var o = { x: 1 }
“x” in o;      // true: o has an own property “x”
“y” in o;           // false: o doesn’t have a property “y”
“toString” in o; // true: o inherits a toString property

var o = { x: 1 }
o.hasOwnProperty(“x”);        // true: o has an own property x
o.hasOwnProperty(“y”);        // false: o doesn’t have a property y
o.hasOwnProperty(“toString”); // false: toString is an inherited property

you can convert a string to a number by multiplying it by 1
numbers entered into text boxes are strings.

you can also use parseInt() and parseFloat() to convert the number string to an actual number
both functions start at the beginning of the string and extract a number until an invalid numeric character is encountered
var n = prompt(“please enter your name”);  // opens a prompt box where user can enter a name

try {
//code here if error in code catch is executed

catch {
//code here for catch statement
//code for if there was an error in the try statement
//only executed if there is an error

//code here is always executed no matter if there was an error or not
//finally is optional


the in operator:
for (a in abc) { do stuff }

if (condition) {
// Execute these statements.

if (condition) {
// Execute these statements.
} else {
// Execute these other statements.

if (myList[i] !== undefined) { // Exists! }
if (i in myList) { // Exists!  //uses the in operator

switch (expression) {
case value1:
// Execute these statements.
case value2:
// Execute these statements instead.
// No, execute these statements.

tenary operator:
(condition) ? return_if_true : return_if_false;

for (initial expression; condition; after expression) {
// Execute these statements.

for (var i = 0; i < myList.length; i++) {
// Do something with myList[i].

for (var p in myObj) {
// Use myObj[p].

while (condition) {
// Statements to be executed.

A counterpart to the while loop is do…while:
do {
// Statements to be executed.
} while (condition);

works with arrays but not objects
you pass in a function to forEach (the one below has no name, but it could have one)

var xyz = [1,2,3,4,5,”yes”]
xyz.forEach(function(value) { console.log(value) });   //function(value) is required (value can be any name)
xyz.forEach(function myfunction(x) { console.log(x) });   //function(x) is required (value can be any name)

working with REAL numbers:
use to fixed on a number to make it a real number

// Example: toFixed(2) when the number has no decimal places
// It will add trailing zeros
var num = 10;
var result = num.toFixed(2); // result will equal 10.00 it saves 2 numbers past the decimal point

// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

// Example: toPrecision(4) when the number has 8 digits (4 before, 4 after)
// It will round to the ones place
num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

// Example: toPrecision(2) when the number has 5 digits (3 before, 2 after)
// It will round to the tens place expressed as an exponential
num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

// Example: toFixed(3) when the number has decimal places
// It will round to the thousandths place
num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

when you need to check if a number is not a number, you can use the
isNaN() function:
if (isNaN(n)) { // Not a number.}

working with strings

toLowerCase() or toUpperCase() to peform case insensitive comparision.

if (email.toLowerCase() == storedEmail.toLowerCase()) { // Okay! }

var message = ‘Right now it is ‘ + today.toLocaleDateString();  // string concatenation is done with the “+” operator

var myVar = [];
var myList = [1, 2, 3];
var people = [‘Fred’, ‘Daphne’, ‘Velma’, ‘Shaggy’];
var collection = [1, ‘Fred’, ‘Daphne’, 2, false];

myList.sort(); //sort myList

copy array to new array:
for(var i = 0; i < a.length; i++) { // For each index of a[]
b[i] = a[i]; // Copy an element of a into b

compare two arrays:
function equalArrays(a,b) {
if (a.length != b.length) return false; // Different-size arrays not equal
for(var i = 0; i < a.length; i++) // Loop through all elements
if (a[i] !== b[i]) return false; // If any differ, arrays not equal
return true; // Otherwise they are equal

myList.length; // 3
people.length; // 4
people[0];   //access bucket 0 of people
people[4] = ‘Charlie’;  //access bucket 4 of people

If there is no element in the array indexed at that position, then a new element
will be added to the list.

people[] = ‘Dee’; // Won’t work!
people[people.length] = ‘Dee’; // Works!
delete people[0];  //deletes data stored at bucket 0. the new value for people[0] = undefined

var myList = new Array(1, 2, 3);
var people = new Array(‘Fred’, ‘Daphne’, ‘Velma’, ‘Shaggy’);
var options = new Array(true, false);

var primes = [];
primes.push(1); // [1] uses the push method
primes.push(3, 5, 7); // [1, 3, 5, 7]  // the push method pushes data on to the end of an array
primes.unshift(1)  // [1,1,3,5,7]  unshift pushes data into the front of the array

var grid = [[2, 4, 6, 8], [1, 3, 5]];

grid.length; // 2
grid[0].length; // 4
grid[1].length; // 3

grid[0][0]; // 2, first item in the first subarray
grid[1][2]; // 5, third item in the second subarray

primes.pop(); //1,3,5 (7 got popped off the array) it also returns the value it is popping off the array
var myvariable = primes.pop(); //myvariable contains the number popped off the stack

primes.shift();  //method removes the first element from the array and returns it.

splicing arrays using splice();
Its first argument is the indexed position
to begin at. The second argument is the number of elements to remove.

var people = [‘Fred’, ‘Daphne’, ‘Velma’, ‘Shaggy’];
var person = people.splice(0,1); // person == [‘Fred’]
var person = people.splice(0,2); // fred, daphne are returned and removed from the array

This next bit of code does not remove any elements, but adds two new values
as the third and fourth items in the array:
var people = [‘Fred’, ‘Daphne’, ‘Velma’, ‘Shaggy’];
people.splice(2, 0, ‘Charlie’, ‘Mac’);

One last array method to be discussed is slice(). The slice() method takes
a starting point—an indexed position in the array—and an optional ending point
and returns the corresponding element(s):
var primes = [1, 3, 5, 7]; // [1, 3, 5, 7]
var twoPrimes = primes.slice(0,2);
// primes == [1, 3, 5, 7]; twoPrimes == [1, 3];

if you give a negative number as an argument it will count backwards from the end of the array.
var primes = [1, 3, 5, 7]; // [1, 3, 5, 7]
var aPrime = primes.slice(-2); // [5, 7]
var bPrime = primes.slice(-2, -1); // [5]

joining array members into a string:
To convert an array to a string, call the join() method on the
array, providing the character or characters to use as the “glue” between the array
pieces in the new string

var people = [‘Fred’, ‘Daphne’, ‘Velma’, ‘Shaggy’];
var gang = people.join(‘ – ‘);

converting a string into an array:
To convert a string to an array, invoke the split() method on the string, providing
the character or characters used to break up the string into its pieces:
var gang = ‘Fred,Daphne,Velma,Shaggy’;
var people = gang.split(‘,’);

If the variable x refers to an object, and the code var y = x; is executed, the
variable y holds a reference to the same object, not a copy of that object

notice the semicolon after the closing braces

creating a blank object:
var o = new Object(); // Create an empty object: same as {}.
var o3 = Object.create(Object.prototype); // o3 is like {} or new Object().
var myObj = {}; //creates a blank object using literal syntax
var myObj = new Object();//creates a blank object

To add properties to an object, use the format “property: value”, separating each
property with a comma, as in:
var chapter = {num: 6, title: ‘Complex Variable Types’};

var chapter = {
num: 6,
title: ‘Complex Variable Types’
chapter.num; // 6
chapter.num = 20;//num = 20

If the named property does not exist in the object, it will be added to it

You can confirm that an object has a property in a couple of ways. The first is
to just use the syntax objName.propertyName:
if (chapter.startPage) { // if we are here it Already exists! code here}

you can also check to see if an object has a property by using the “in” operator:
if (‘startPage’ in chapter) { // if we are here it Already exists! code here}

A third option is to use the typeof operator, assuming you know what the
property’s type should be:
if (chapter.startPage == ‘number’) { code here }; // Fit
me.favoriteColors[0]; // Black

is the same as:


you can access the members both ways.

removing properties from an object:
delete chapter.title;

The typeof operator:
The typeof operator tells you the type of object you pass to it as an argument.

meebo = 5;
console.log (typeof meebo) // output == number

var ah = typeof (meebo) // stores “number” in ah

working with forms:

access a value from the form:
var firstName = document.getElementById(‘firstName’).value;

function init() {   // listener
‘use strict’;
document.getElementById(‘theForm’).onsubmit = process;
} // End of init() function.
window.onload = init;

The indexOf() method searches the array for the specified item, and returns it’s position.

The search will start at the specified position, or at the beginning if no start position is specified,
and end the search at the end of the array.

Returns -1 if the item is not found.

If the item is present more than once, the indexOf method returns the position of the first occurence.

Note: The first item has position 0, the second item has position 1, and so on.

if (email.value.indexOf(‘@’) == -1) {//bah it doesnt exist}
if (comments.value.indexOf(‘<’) != -1) {}
if (typeof myVar == ‘number’) {}

a = [0,1,2,1,0];
a.indexOf(1) // => 1: a[1] is 1
a.lastIndexOf(1) // => 3: a[3] is 1
a.indexOf(3) // => -1: no element has value 3

window.document.forms.order  // address the form named “order”.

having a javascript do something when the form is submitted:
<INPUT name=”Submit” value=”Submit” type=”submit” onsubmit=”myfunction()”/>

using this.value:
inside a form, the elements are named and defined.
inside the definition of the element you can put javascript code.
one helpful item is the “this” pointer.
the this pointer points to the current element being defined.
the value points to the value that is set for that element.
so you can use this.value to reffer to the current elements value.

Email: <INPUT type=”text” name=”Email” onblur=”ValidateEmail (this.value)”/><BR>

using an image as a submit button:
<img src=”mysubmit.gif” onclick=”javascript:document.forms.Contact.submit()”/>   //set Contact to the name of the form
<img src=”myreset.gif” onclick=”javascript:document.forms.Contact.reset()”/>     //set Contact to the name of the form

en example form which gets submitted by image and has multiple functions execute when submit is clicked:

function myFunction()
<form name=Contact action=”demo_form.asp”>
Username: <input type=”text” name=”username”><br>
<img src=”winxp.png”   onclick=”myFunction()”/>




window.prompt(“Text to ask question”,”text inside text input box”);

Functions automatically have access to a variable called arguments.
This is an array-like object that reflects
every value passed to the function when the function is called. you can not add to the array
but it does have a length property, like normal arrays
If a function has an parameter that is not passed a value when the function is called,
that parameter will have a value of undefined

functions can be nested

calling a function without () creates a reference
a = myfunction;  // a becomes a reference to myfunction()
a(); //a can be called like myfunction() because it is a reference to it.

checking if the correct amount of arguments were supplied to the function using the “arguments” array:

function functionName(someVar, anotherVar, yetAnotherVar) {

if (arguments.length == 3) { // Good to go! }

else { // Missing something! }


another example testing if the proper arguments were passed to the function:

function functionName(someVar) {

if (typeof someVar == ‘undefined’) { // Not set!}

else { // Good to go!}


setting a default value when an argument is “undefined”:

function functionName(someVar) {
if (typeof someVar == ‘undefined’) {
someVar = ‘default value’;

You should know that when a return statement is encountered, the function’s
execution terminates, even if there is more code after the return statement.
If a function has no return statement, or uses return without a value, the
function automatically returns the value undefined.

function functionName() {
// Function body.
return something;

use the navigator object to retrieve the properties of the browser.

window.document.cookie is what stores the cookie.
cookies have name=value pairs.

window.document.cookie = “CustomerName= ABC;”  //set cookie

var expireDate = new Date
document.cookie=”expires=” + expireDate.toGMTString()

it seems that sometimes when setting a cookie it only sets the first value.
get around this by using multiple cookie statements:

creates a cookie with pa and username.

to kill a cookie:


var windowObjectReference =, strWindowName[, strWindowFeatures]);
strUrl = url of content of window
strWindowName = Name of new window
strWIndowFeatures = options as used below

to change the content of an existing window call with the name
of the window the same as the name of the existing window, it will update
the content of the window instead of opening a new window.

MyWindow =
MyWindow.close() // close the window that was opened

open a ad vertisment window with winxp.png as ad:

MyWindow =‘winxp.png’, ‘myAdWin’, ‘status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, height=250, width=250’)
this.focus()  // give the original window focus. this will make the popup show up behind the current window

left=0,top=0  //options put window in upper left hand corner of screen

check if a window is the top window using the
if ( != window.self) {}

window.self  //the current window – returns the name of site loaded

>>> window.self

Window  //current site in window

window scrolling:

opening many windows:

for (i=0; i<5; i++){“winxp.png”, i)}//add options to customize

notice it creates a window with window name MyWindow
it then writes to this window using document.write() function of MyWindow

<script language=”Javascript” type=”text/javascript”>
function Window() {
MyWindow =
(”, ‘myWin’, ‘height=250, width=250’)
(‘<title> Writing Content</title>’)
(‘<FORM action=””
‘Customer:<INPUT name=”FirstName”
type=”text” />’)
(‘<INPUT name=”submit” type=”submit” />’)

you beak up a single string into multiple lines by using the “” character at the end of each line;
takes 3 lines”

you concatenate strings using the + operator

“mystring1 ” + “mystring2”;
creates mystring1 mystring2

remember that in a string you can use escape characters to represent any characters that are special.

var s = “hello, world” // Start with some text.
s.charAt(0)            // => “h”: the first character.
s.charAt(s.length-1)   // => “d”: the last character.
s.substring(1,4)       // => “ell”: the 2nd, 3rd and 4th characters.
s.slice(1,4)           // => “ell”: same thing
s.slice(-3)            // => “rld”: last 3 characters
s.indexOf(“l”)         // => 2: position of first letter l.
s.lastIndexOf(“l”)     // => 10: position of last letter l.
s.indexOf(“l”, 3)      // => 3: position of first “l” at or after 3
s.split(“, “)          // => [“hello”, “world”] split into substrings
s.replace(“h”, “H”)    // => “Hello, world”: replaces all instances
s.toUpperCase()        // => “HELLO, WORLD”


use alert to pop up alerts with data:
var xyz = “hello”;
alert(xyz);  //creates an alert box with the contents of xyz

using the alert box you can output the source from a function passed to it:
function myfunct() { console.log(“inside myfunct”) }
alert(myfunct); // output = function myfunct() { console.log(“inside myfunct”) }   IN AN ALERT BOX

also use console.log for output when debugging.
var xyz = “hello”;
console.log(xyz); //output = hello

using console.log with myfunct:
function myfunct() { console.log(“inside myfunct”) }
console.log (myfunct());    // output “inside myfunct”

using document.write();
using the document.write function you can write to the browser using the debug bar.
document.write(navigator.appName);  //output “Microsoft Internet Explorer” in explorer

Leave a Reply