Javascript Essentials

Comments

Comments in your programs can be useful to remind you and whoever else might be reading your code what your code is supposed to do. In any line of JavaScript code, any characters after a double slash // are ignored.
circle(200,200,20);     //Draw a circle of radius 20 at (200,200)
point(200,200);         //Draw a point at (200,200)
Comments can be used to make sections of a program easier to locate.
// Initialization **********************************
...INITIALIZE STUFF...

// Drawing *************************************
...DRAWING STUFF...
Comments which span multiple lines should be placed within /*...*/ like so:
/* John W. Smith
Creature Assignment
July 9, 2012 */

Semicolons

Aside from comments, a JavaScript program consiste of statements or commands which tell the computer what to do. Each statement should end with a semicolon (to tell the computer when the statement ends). Generally, we will place one statement per line.
circle(200,200,20);
line(10,10,90,90);

Case

JavaScript is case sensitive. alert is different from Alert.

White Space

All white space (spaces, tabs, carriage returns, etc.) in JavaScript are treated as single spaces. Extra spaces, tabs, and carriage returns are often inserted to make code more readable.

Alert

The command alert(someString) will place someString in an alert box for the user to read. Alerts are not used much in JavaScript programming, but they can be useful when programming to get quick feedback to see how your programming is coming together.
alert("This is some text.");

Variables

A variable in JavaScript is a container or box in which you can place information or data. For us, names of variables consist of characters which should be letters, numbers, or underlines. The first character should be a letter. JavaScript is case sensitive so firstName and firstname would be different variable names. Some valid variable names are:
x
i
x2
firstName
last_name
phone2
Variable names should generally be descriptive. This means the variable name might be constructed from more than one word. To make the name readable, the words might be divided using either under_lines or camelCase. The most popular option these days seems to be camelCase, but you can use whichever you are more comfortable with. Data values are placed in (or assigned to) variables using an equal sign =.
x=2;     //place the value 2 in the variable x
Before a variable is used, it should be declared or created. (Before anything can be placed in a box, the box must exist.) This is done with var.
var x;                   //declare the variable x
var firstName;      //declare the variable firstName
var age=32;          //declare the variable age and assign the value 32 at the same time!
Data in JavaScript comes in a variety of types. We will be concerned with numbers, strings, and Boolean. Numbers look like:
var age=32;
var pi=3.14159;
A string is a list of symbols inside of quotation marks. You can use double or single quotation marks.
var teacherName = "John Snow";	
var college = 'Concordia University';
If you want a string to contain a single quote, you should enclose the string in double quotes. If you want a string to contain a double quote, you should enclose the string in single quotes.
var aString = "Bob's brother is 19 years old";
var quoteInQuote = 'This contains "double" quotes';
A Boolean data type holds either the value true or false.
 lightsAreOn=true;
 grassIsGreen=false;

prompt

A prompt can be used to get data from the user. Prompts are not used all that often in JavaScript, but they can be useful when writing and testing code.
var x=prompt("Enter your first name:");
Prompts gather strings from the user. If you want a number input, you need to convert the string to a number. A simple way to do this is with the eval command.
var stringInput;
var numberInput;
stringInput=prompt("Enter a number between 1 and 10:");	//Input is string
numberInput=eval(stringInput);				//Convert string to number
Note: The eval command can be used to evaluate or execute any piece of JavaScript code.

Arithmetic Operators

Arithmetic operators are used to perform arithmetic with numerical values and variables. Assuming that x=7, here are some examples
NameExampleValue of y
Additiony=x+5;12
Subtractiony=x-5;2
Multiplicationy=x*5;35
Divisiony=x/5;1.4
Modulus (remainder)y=x%5;2
Mixedy=((x*5)-3)/8;4

String Operators

JavaScript provides very powerful means for manipulating strings. We will simply be concatenating or adding strings for now. When the addition sign + is placed between two strings, the result is to glue the two strings together end to end. For these examples, assume that x="How now" and y="brown cow".
ExampleValue of z
z=x+y;"How nowbrown cow"
z=x+" "+y;"How now brown cow"
z=x+" is the "+y"How now is the brown cow"
z=x+5"How now5"
z="51"+50"5150"
Notice in the last two examples how when addition, numbers, and strings are combined everything is treated like a string.

Boolean Operators

The basic operators that can be applied to Boolean data types are and &&, or ||, and not.

If a=true and b= true, then a&&b=true. If either a or b is false, a&&b=false.

If a=false and b= false, then a||b=false. If either a or b is true, a||b=true.

if a=true, then !a=false. If a=false, then !a=true.

Comparisons

JavaScript provides these comparison operators (among some others) which will always return either a Boolean true or a Boolean false.
NameSymbols
Is equal to==
Is not equal to!=
Is greater than>
Is less than<
Is greater than or equal to>=
Is less than or equal to<=
Note that = is used for variable assignment and == is used for testing equality.

Functions

When a piece of code might be used repeatedly or might be needed in a variety of environments we can use that code to define a function. Here is a function which computes the average of two numbers a and b.
function average(a,b){
	var r;                  
	r=(a+b)/2;
	return(r);
}
The function definition begins with the word function which tells the computer a function is being defined. The word average is the name of the function. Following the name of the function are variables a and b in parenthesis. These are the arguments of the function. When the function is called, values will be substituted for a and b. After the arguments of the function comes a code block separated off by braces {...}. Comments about braces are below. For now, just note that the entire code of the function needs to be within braces. Note also that we indented all of the function code so that it is clear where the function begins and ends. The variable r is defined inside the function. This makes r a local variable. It is only accessible from within the function. Variables defined outside of any function are global variables. These are accessible anywhere. The last line of the function uses the command return. This means that the function returns the value calculated and stored in r to whoever called the function. The function may be called or used in this manner:
y=average(10,20);
This line asks the computer to run the code inside of the average function substituting 10 for the first variable (a) and 20 for the second variable (b). At the end of the function code, the value 15 will be returned and placed in the variable y.

Not all functions require arguments.
function getBackgroundColor(){
	return(document.body.style.backgroundColor);
}
This function would be called with something like:
y=getBackgroundColor();
Note the use of parenthesis even though there are no arguments. Some functions may not take arguments or return values:
function setBackgroundColor(){
	document.body.style.background='red';
}
This would be called with :
setBackgroundColor();

Braces

Many a computer programmer has spent many a late night arguing with other programmers about how to indent and place braces around code blocks. If you have never programmed before, this should seem silly and trifle. If you have written a lot of programs with one style and then tried to read a program with another style, you will understand the controversy. Most methods of indenting present positives and negatives. The truth is that the overall goal is usually readability, and you will find that whatever you practice the most is going to be most readable to you. If you are working with colleagues, you should try to indent the same way they do. If you are in a class, you should indent however your instructor tells you to. Here are thee common ways that the function above might be indented and braced.

Initial brace on first line of function, code block indented, final brace on own line not indented:
function average(a,b){
	var r;                  
	r=(a+b)/2;
	return(r);
}
Initial brace on first line of function, code block indented, final brace on own line indented:
function average(a,b){
	var r;                  
	r=(a+b)/2;
	return(r);
	}
Initial brace on own line not indented, code block indented, final brace on own line not indented:
function average(a,b)
{
	var r;                  
	r=(a+b)/2;
	return(r);
}

Control Structures

if...else

JavaScript provides conditional statements so that whether or not a statement is executed depends on whether or not a condition is true. The structure of an if is
if (condition){
	code to execute if condition is true
}
In the following example, a circle is drawn and the value of x is modified if x < width.
if (x < width){
	circle(x,y,10);
	x=x+dx;
}
If the code block for an if statement only includes one statement, the braces can be omitted.
if (x < width)
	circle(x,y,10);
Conditions of if statements can be combined with and and or as in:
if ((x < width) && (y < height)){
	circle(x,y,10);
	x=x+dx;
	y=y+dy;
}
Here the condition on x and the condition on y must both be met for the code to be executed. Note how each small condition is in parenthesis and how the entire condition is in parenthesis. Sometimes we want to execute one code block if a condition is true and another if a condition is false. This is accomplished through the if...else statement.
if (condition){
	code to execute if condition is true
}
else{
	code to execute if condition is false
}
In the following example, dx is added to x if x < width. Otherwise (when x >= width), dx is subtracted from x.
if (x < width)
	x=x+dx;
else
	x=x-dx;

while

Sometimes it is necessary to repeatedly execute some code until a particular condition is met. This is accomplished with the while statement.
while(condition){
	code to execute as long as condition is true
}
For example, the following code will repeated draw points and add 1 to x until x reaches the value width. Because x is initially set to 0, points will be drawn at (0,100), (1,100), (2,100), all the way to (width,100).
x=0;
while (x <=; width){
	point(x,100);
	x=x+1;
}

for

The structure of a while statement frequently looks like this:
initialize a variable i
while(condition){
	code to execute as long as condition is true
	modify the variable i
}
The for statement or for loop is short hand for this type of arrangment.
for (initialization; condition; modification){
	code to execute as long as condition is true
}
In this example, first the initialization code is executed. Then the condition is checked. If it is true, the code is executed. After the code is executed, the modification code is executed. Then the condition is checked again and the process continues until the condition is no longer true. The while statement
x=0;
while (x <=; width){
	point(x,100);
	x=x+1;
}
can be expressed with a for loop more succinctly as
for (x=0; x <= width; x=x+1)
	point(x,100);
Notice how the statements inside the parenthesis defining the for loop are separated with semicolons.

document.getElementById

JavaScript can be used to modify HTML elements on a web page. This is most easily done for elements that have IDs. Until recently, to access the value attribute of an element with id "elementID" you had to use the function document.getElementById like so:
document.getElementById("elementID").value="something";
However, according to the latest standard, elements can be accessed directly with their IDs without using document.getElementById. The previous like of code can now be written much more simply as
elementID.value="something";

Manipulating HTML Elements

JavaScript can be used to modify HTML elements. This can most easily be done with elements that have IDs. Suppose we have this div in our HTML:
<div id="myDiv"></div>
We can change style attributes of this div with code such as:
myDiv.style.width="100px";
myDiv.style.color="blue";
myDiv.style.backgroundColor="green";
HTML elements also have an attribute named innerHTML that can be used to write HTML directly into the element. Modifying this attribute completely changes all of the HTML in the element. Here we place a table in myDiv:
myDiv.innerHTML="<table><tr><td>a</td></tr><tr><td>b</td></tr></table>";
Suppose that we have a textarea defined this way:
<textarea id="myText"></textarea>
To modify the value (contents) of the textarea we can use
myText.value="some text";
We can get the value of the textarea and store it in a string this way
s=myText.value;
Suppose that we have this image:
<img id="myImg" src="image1.png">
If we want to change what picture is displayed in the image (say, for an image slider) we can use this code
myImg.src="image2.png";

Buttons

The JavaScript in the head section of our HTML does not have to be Spork code. The code there can be executed when a page loads to initialize content on the page, or it can run when triggered by certain events on the page. An example of one such event is the click of a button. First, buttons are created this way:
<button>Click Me</button>
To add functionality to the button, you define the onclick for the button like so:
<button onclick='alert("Ouch!");'>Click Me</button>
The text in quotes after onclick= must be properly formed JavaScript ending with a semi-colon. It will be executed when the button is clicked. If you want to execute a substantial amount of JavaScript, you should place that code in a function (in the head section) and call the function when the button is clicked. Buttons can be styled, and any HTML can be placed between the button tags. This way you can turn images or tables or whatever into buttons. We will see later that the onclick event can also be defined for most HTML elements.

Scripting HTML

Of course, the JavaScript included in a web page can do more than just drive Spork programs. HTML elements can be added, deleted, and modified with JavaScript. This is most easily done by referring to the element by ID. Consider this code:
This is an unstyled div.
IN A SCRIPT IN THE HEAD
function changeStyle(){
	myDiv.style.width='200px';
	myDiv.style.background='yellow';
	myDiv.style.margin='auto';
	myDiv.style.border='2px solid black';
}
...IN THE BODY
<div id='myDiv'>This is an unstyled div.</div>
<button onclick='changeStyle'>Style the Div</button>
When the button is clicked, the function changeStyle() is called. The function changes style attributes of the div. The div is accessed through its ID myDiv. Style attributes are accessed through myDiv.style.attributeName.

innerHTML

Divs (and other HTML elements) have a property called innerHTML which is a string that contains the HTML in the div. JavaScript can take complete control over what is in a div by changing this value. Consider this code:
This is an unstyled div.
IN A SCRIPT IN THE HEAD
function changeStyle(){
	myDiv2.style.width='200px';
	myDiv2.style.background='yellow';
	myDiv2.style.margin='auto';
	myDiv2.style.border='2px solid black';
	myDiv2.innerHTML='This is now a styled div.';
}
...IN THE BODY
<div id='myDiv2'>This is an unstyled div.</div>
<button onclick='changeStyle'>Style the Div</button>
Now when the button is clicked, the contents of the div change with the style.

document.write

The command document.write('string') will write string in the web page. If this is called in the head section, the entire contents of the web page will be over written with string. This could allow you to use JavaScript to generate all of the HTML for a page and then display the page. If document.write('string') is called in the body of an HTML page, then the string is written at that location in the web page. This can be useful if you have a complicated menu system or such that you want included in several web pages. You could make a file menu.js with a function like this in it:
IN menu.js
function writeMenu(){
	document.write('Complicated menu HTML.');
}
Then, in each web page in wich you want to use the menu, you need this line in the head so that the function will be available.
IN HEAD SECTION
<script src='menu.js'></script>
If you place this line
IN BODY SECTION
<script>writeMenu();</script>
in the body of your HTML, then the menu will be placed in the web page (at that location). Of course, your complicated menu might have many lines. To have a multi-line string in JavaScript, you need to end each line between the quotation marks with a \ like so
function writeMenu(){
	document.write('<img src="logo.png">;\
				<a href="page1.html">Page One</a>\
				<a href="page2.html">Page Two</a>');
}

Randomization

Two advantages of drawing with a machine are the ability to perform tasks repeatedly (which we will explore later) and the ability to introduce randomness.

random

The JavaScript function random(); returns a random number between 0 (might be 0) and 1 (but not equal to 1). This function can be used to generate random numbers in any range. To assign a variable x to a random number between 0 (may be 0) and 255 (will not be 255), you can use
x=255*random();
This might have the result of x=0 or x=38 or or x=100.5 or x=254.9976. To leave off the decimal part of the random number (in case you want a "whole number") you can use floor.

floor

The command floor(x) will remove the decimal part of x. So floor(1.234)=1 and floor(1.999)=1. The command
x=floor(255*random());
will give a random whole number between 0 (might be 0) and 254 (might be 254, not 255). The command
x=floor(255*random())+1;
will give a random whole number between 1 (might be 1) and 255 (might be 255).

Random Coordinates

Canvas coordinates do not need to be whole numbers. Recall that the canvas width and height are stored in the variables width and height. If no transforms have been applied to the canvas then this code will draw a circle of radius 10 at a random location on the canvas:
circle(width*random(), height*random(),10);
Notice that this works no matter what the size of the canvas is.

Random Colors

The first three numerical arguments to the color function need to be whole numbers. We could use the floor function to get random colors. This would give a random color:
color(floor(256*random()),floor(256*random()),floor(256*random()));
This would give a random color with a random alpha (transparency) value:
color(floor(256*random()),floor(256*random()),floor(256*random()),random());
The problem with this approach to random colors is that the colors really are random - they have no relationship to each other. There is no coordination, complementation or anything. We can be more deliberate with randomly selecting colors by using an array.

Arrays

We introduce arrays with an example. Suppose we declare the variable colorArray this way:
var colorArray = ['blue', 'lightblue', 'steelblue', 'gray', 'lightgray'];
The variable colorArray now contains 5 distinct values or entries which are numbered 0 through 4. To get the first value we can use colorArray[0]. The value of colorArray[0] is 'blue'. The value of colorArray[1] is 'lightblue'. The value of colorArray[2] is 'steelblue', and so on.

Now, to generate a random color from among these 5, we can randomly select an entry in the array colorArray. We first select a random integer from 0 to 4 and then get that entry in colorArray.
var colorArray = ['blue', 'lightblue', 'steelblue', 'gray', 'lightgray'];  //define colorArray
i = floor(5*random());                                                     //select random integer
randomColor=colorArray[i];                                                 //get random entry

Random Function

We can also use arrays to call random functions. Suppose that we have three functions drawCircle(x,y), drawSquare(x,y), drawTriangle(x,y). If we define this array
var functionArray = [drawCircle,drawSquare,drawTriangle];
We can now call our three functions as functionArray[0](x,y) or functionArray[1](x,y) or functionArray[2](x,y). Now the following code will randomly draw a circle or a square or a triangle:
var functionArray = [drawCircle,drawSquare,drawTriangle];  //define array of functions
i = floor(3*random());                                     //select random integer
functionArray[i](x,y);                                     //draw shape at (x,y)