 # JavaScript Programming Notes

## "Hello World" in JavaScript

document.write("Hello World");

Single line comments are started with a double slash.

// This is an example of a JavaScript single line comment.

/* This is an example of a JavaScript
multi-line comment. */

## Embedding an External JavaScript file in an HTML Document

<script language="javascript" src="name_of_file.js"></script>    // Place this code in the 'head' section of the HTML file.

## JavaScript Operators

### Comparison Operators

Comparison operators compare the value of two operands. A boolean 'true' or 'false' is returned based on the results of the comparison.

 === Equal To. !== NOT equal To. < Less than. > Greater than. <= Less than or equal to. >= Greater than or equal to.

### Logical Operators

 && Tests if both operands are true. || Tests if either operand is true. ! Reverses the logical state of an operand.Sometimes referred to as 'not' or 'bang'.

### Examples of Comparison and Logical Operator Usage

For the these examples, assume the following:     x = 2;     y = 3;     z = 2;

 x < y true x === y || x === z true x > y false x === y && x === z false x === y false x + 1 < y false x !== y true x + 1 <= y true x === 2 true (x === 2 && y === 3 || y === 4) true x !== 2 false (x === 2 || y === 3 && y === 4) true

### Assignment Operators

 = a = 2 += a += 2   is the same as   a = a + 2 −= a −= 2   is the same as   a = a − 2 *= a *= 2   is the same as   a = a * 2 /= a /= 2   is the same as   a = a / 2 %= a %= 2   is the same as   a = a % 2

## Math Functions in JavaScript

Math is a JavaScript built in object with its own methods.

### Methods of the Math Object

 Math.random() Syntax: Math.random(); Uses: Returns a random number between 0 and just under 1. Math.floor(Math.random()*11) Returns a random number between 0 and 10 Math.floor(Math.random () * 6 + 1) Returns a random number between 1 and 6 Math.pow() Syntax: Math.pow(base, exponent); Uses: Raises a base to an exponent. Math.pow(2, 3) Returns 8 Math.max() Syntax: Math.max(num1, num2, ...); Uses: Returns the largest value given as an argument. Math.max(-15, -16, -9) Returns -9 Math.min() Syntax: Math.min(num1, num2, ...); Uses: Returns the smallest value given as an argument. Math.min(-15, -16, -9) Returns -16 Math.sqrt() Syntax: Math.sqrt(number); Uses: Returns the square root of a number. Returns NaN for a negative number. Math.sqrt(9) Returns 3 Math.sqrt(-9) Returns NaN Math.abs() Syntax:Math.abs(number); Uses: Returns the absolute value of a number. Math.abs(-15.627) Returns 15.627 Math.round() Syntax: Math.round(number); Uses: Rounds a number to the nearest integer. Math.round(1.3) Returns 1 Math.round(2.74) Returns 3 Math.ceil() Syntax: Math.ceil(number); Uses: Rounds a number UP to the nearest integer. Math.ceil(1.3) Returns 2 Math.ceil(2.74) Returns 3 Math.floor() Syntax: Math.floor(number); Uses: Rounds number down to nearest whole number. Math.floor(1.3) Returns 1 Math.floor(2.74) Returns 2 Math.sin() Syntax: Math.sin(angle); Uses: Returns the sine of an angle. Math.cos() Syntax: Math.cos(angle); Uses: Returns the cosine of an angle. Math.tan() Syntax: Math.tan(angle); Uses: Returns the tangent of an angle. Math.asin() Syntax: Math.asin(number); Uses: Returns the arcsine of number. Math.acos() Syntax: Math.acos(number); Uses: Returns the arccosine of number. Math.atan() Syntax: Math.atan(number); Uses: Returns the arctangent of number

## Working with Strings in JavaScript

### Methods of the String Object:

Some of these examples use the following sample string:

samp = "This is a sample string."

 .length Syntax: string.length Uses: Returns the number of characters in a string. "a".length Returns 1 "hello world".length Returns 11 samp.length Returns 24 .substring() Syntax: string.substring(start, end) Uses: Extracts a substring of a string between two index locations. "hello".substring(0,2) Returns "he" "hello".substring(3,4) Returns "l" "hello".substring(1) Returns "ello" (length is optional. If omitted, returns to end of string.) samp.substring(5, 16) Returns "is a sample" .substr() Syntax: string.substr(start, length) Uses: Extracts a substring of a string between a starting index and length. "hello".substr(0,2) Returns "he" "hello".substr(2,2) Returns "llo" "hello".substr(1) Returns "ello" (length is optional. If omitted, returns to end of string.) samp.substr(5, 6) Returns "is a s" .replace() Syntax: string.replace(find, replace) Uses: Replaces part of a string "hello world".replace("world", "people") Returns "hello people" samp.replace("sample", "test") Returns "This is a test string." .toUpperCase() Syntax: string.toUpperCase() Uses: Converts a string to upper case. "hello world".toUpperCase() Returns "HELLO WORLD" samp.toUpperCase() Returns "THIS IS A SAMPLE STRING." .toLowerCase() Syntax: string.toLowerCase() Uses: Converts a string to lower case. "HELLO World".toLowerCase() Returns "hello world" samp.toLowerCase() Returns "this is a sample string." .indexOf() Syntax: string.indexOf(otherStr) Uses: Returns the index of a string in another string. "Hello world!".indexOf("H") Returns 0 "Hello world!".indexOf("r") Returns 8 "Hello world!".indexOf("z") Returns -1 (Returns '-1' if substring is not found) "Hello world!".indexOf("world") Returns 6 samp.indexOf("This") Returns 0 samp.indexOf("world") Returns -1 .charAt() Syntax: string.charAt(index) Uses: Returns the character at the specified index. "Hello world!".charAt(6) Returns w samp.charAt(0) Returns T samp.charAt(samp.length-4) Returns i .split() Syntax: string.split(separator,limit) Uses: Splits a string into an array of substrings. "Hello world!".split() Returns ["Hello", "world!"] samp.split() Returns ["This is a sample string."] samp.split(" ") Returns ["This", "is", "a", "sample", "string."] samp.split(" ", 2) Returns ["This", "is"] samp.split(" ", 4) Returns ["This", "is", "a", "sample"] samp.split("", 12) Returns ["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "s", "a"] .concat() Syntax: str.concat(str1, str2, ...) Uses: Concatenates two or more strings. "Hello world! ".concat(samp) Returns "Hello world! This is a sample string." "Part one and ".concat("part two.") Returns "Part one and part two." .charCodeAt() Syntax: string.charCodeAt(index) Uses: Returns the Unicode for the character at a specific index. samp.charCodeAt(3) Returns 115 .lastIndexOf() Syntax: string.lastIndexOf(search, start) Uses: Returns the index of the last occurrence of a substring. "Hello world!".lastIndexOf("world") Returns 6 samp.lastIndexOf("sample") Returns 10 samp.lastIndexOf("world") Returns -1 (Returns '-1' if search string is not found) samp.lastIndexOf("i") Returns 20 samp.lastIndexOf("i", 10) Returns 5 .slice() Syntax: string.slice(start,end) Uses: Permanently removes part of a string and returns a new string. samp.slice(8,16) Returns "a sample" samp.slice(8) Returns "a sample string." samp.slice(-4) Returns "ing."

## Working with Arrays in JavaScript

### What Are Arrays?

An array is a variable that can hold one or more values. The following is an example of an array.

sampleArray = ["elm", "maple", "ash", "oak", "cedar"]

Items in an array are indexed starting with '0'. In the above example, the array items have the following index positions: elm = 0, maple = 1, ash = 2, oak = 3, cedar = 4. Note that the last item in the array has an index value one less than total number of items in the array. We can use the index positions to work with items in the array. For instance, if we wanted to print "oak" we could use the following code:

document.write(sampleArray);

Use .length to return the length of an array. sampleArray.length will return a value of 5. The total number of items in the array.

To perform an operation on all items in an array, the following structure can be a good starting point.

for (var i=0; i<myArray.length; i++) { //do something }

The following code will loop through and print all items in the 'sampleArray' array.

for (var i=0; i<sampleArray.length; i++) {

document.write(sampleArray[i] + "<br />")

}

### Creating Arrays

An array can be created using several techniques.

var sampleArray=new Array();

sampleArray="elm";

sampleArray="maple";

sampleArray="ash";

sampleArray="oak";

sampleArray="cedar";

Another way.

var sampleArray = ["elm", "maple", "ash", "oak", "cedar"]

### Two-dimensional Arrays

The following is an example of a two-dimensional Array

var treeList = [["silver maple","sugar maple"],["red oak","bur oak"],["ponderosa pine","scotch pine"]];

Creating and assigning values to a two-dimensional array

var treeList=new Array(3)

for (i=0; i <3; i++) {treeList[i]=new Array(2)}

treeList="silver maple";

treeList="sugar maple";

treeList="red oak";

treeList="bur oak";

treeList="ponderosa pine";

treeList="scotch pine";

Performing operations on all element of two-dimensional array can be accomplished using nested for-loops.

for (var i = 0; i < treeList.length; i+=1){              // This code will loop through and print all elements of the treeList array.

for (var j = 0; j < treeList[i].length; j+=1){

document.write(treeList[i][j] + "<br />");

}

}

### Methods of the Array Object:

JavaScript has a number of built-in methods for working with arrays. In addition to returning information from an array, some of these methods change the underling array.

The examples in this section each use these arrays as a starting point:

sampleArray = ["elm", "maple", "ash", "oak", "cedar"]

sampleArray2 = ["willow", "pecan", "poplar"]

 .concat() Syntax: array.concat(ar1, ar2, ...) Uses: Returns a new array consisting of the values from two or more arrays. sampleArray.concat(sampleArray2) Returns ["elm", "maple", "ash", "oak", "cedar", "willow", "pecan", "poplar"] .indexOf() Syntax: array.indexOf(item,start) Uses: Searches for and returns the index of a value. A start point is optional. sampleArray.indexOf("oak") Returns 3 .join() Syntax: array.join(separator) Uses: Creates a string including all elements from an array. sampleArray.join() Returns "elm,maple,ash,oak,cedar" sampleArray.join(" ") Returns "elm maple ash oak cedar" sampleArray.join(" - ") Returns "elm - maple - ash - oak - cedar" sampleArray.join(" tree, ") Returns "elm tree, maple tree, ash tree, oak tree, cedar " .lastIndexOf() Syntax: array.lastIndexOf(item,start) Uses: Returns the index of the last occurance of a value. A start point is optional. sampleArray.lastIndexOf("oak") Returns 3 .pop() Syntax: array.pop() Uses: Returns the last element from an array and removes it from the array. sampleArray.pop() Returns "cedar"sampleArray = ["elm", "maple", "ash", "oak"] .push() Syntax: array.push(item1, item2, ...) Uses: Adds new items to the end of an array and returns its length. sampleArray.push("palm", "cherry") Returns 7sampleArray = ["elm", "maple", "ash", "oak", "cedar", "palm", "cherry"] .reverse() Syntax: array.reverse() Uses: Reverses the order of elements in an array. sampleArray.reverse() sampleArray = ["cedar", "oak", "ash", "maple", "elm"] .shift() Syntax: array.shift() Uses: Returns the first item from an array and removes it from the array. sampleArray.shift() Returns "elm"sampleArray = ["maple", "ash", "oak", "cedar"] .slice() Syntax: array.slice(start, end) Uses: Returns a new array containing items from an existing array. sampleArray.slice(2, 4) Returns ["ash", "oak"] .sort() Syntax: array.sort(function) Uses: Sorts elements of an array. An optional sort function may be included. sampleArray.sort() Returns ["ash", "cedar", "elm", "maple", "oak"] .splice() Syntax: array.splice(index,num,item1,...) Uses: Adds or removes items from an array sampleArray.splice(2,2) Returns ["ash", "oak"] sampleArray = ["elm", "maple", "cedar"] sampleArray.splice(2,2,"walnut","beech") Returns ["ash", "oak"] sampleArray = ["elm", "maple", "walnut", "beech", "cedar"] .toString() Syntax: array.toString() Uses: Converts an array to a string. sampleArray.toString() Returns "elm,maple,ash,oak,cedar" .unshift() Syntax: array.unshift(item1,item2,...) Uses: Adds new items to the beginning of an array. Returns the array length. sampleArray.unshift("birch", "spruce") Returns 7sampleArray = ["birch", "spruce", "elm", "maple", "ash", "oak", "cedar"]

### More Array Method Examples

Another series of array examples. In this case, each method is working on the modified array. The starting array is:

sampleArray = ["elm", "maple", "ash", "oak", "cedar"]

 sampleArray.sort() sampleArray = ["ash","cedar","elm","maple","oak"] sampleArray.reverse() sampleArray = ["oak","maple","elm","cedar","ash"] sampleArray.push("palm", "cherry") sampleArray = ["oak","maple","elm","cedar","ash","palm","cherry"] sampleArray.unshift("birch", "spruce") sampleArray = ["birch","spruce","oak","maple","elm","cedar","ash","palm","cherry"] sampleArray.pop() sampleArray = ["birch","spruce","oak","maple","elm","cedar","ash","palm"] sampleArray.pop() sampleArray = ["birch","spruce","oak","maple","elm","cedar","ash"] sampleArray.shift() sampleArray = ["spruce","oak","maple","elm","cedar","ash"] sampleArray.shift() sampleArray = ["oak","maple","elm","cedar","ash"] sampleArray.push('locust','Magnolia') sampleArray = ["oak","maple","elm","cedar","ash","locust","Magnolia","Mulberry"] sampleArray.splice(2,2) sampleArray = ["oak","maple","ash","locust","Magnolia"] sampleArray.splice(2,2,"walnut","beech") sampleArray = ["oak","maple","walnut","beech","Magnolia"]

## Example Functions Using Arrays

### Playing Cards

The following function creates a two-dimensional array containing 52 playing cards.

function createCardDeck() {

var ranks = [2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"];

var deck = [];

for (var suit = 0; suit < suits.length; suit += 1) {

for (var rank = 0; rank < ranks.length; rank += 1){

deck.push([ranks[rank], suits[suit]]);

}

}

}

The following function increments throught the deck and prints all 52 playing cards.

function printCardDeck() {

for (var i = 0; i < deck.length; i += 1) {

document.write(deck[i] + "<br />");

}

}

Output for the function above: