Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Kick some booty with invisible Flash!

JavaScript Bookmarklets

Why bother with JavaScript?

JavaScript Games #2 - Solitaire

Writing a midi hifi system in JavaScript

JavaScript Beginners Start Here

Keeping Count of Downloads

JavaScript Games

Online JavaScript Resources

JavaScripting Essentials

You are here: irt.org | Articles | JavaScript | Miscellaneous | JavaScripting Essentials [ previous next ]

Published on: Sunday 12th September 1999 By: Ryan Detert

The Invariable Variable

Unlike C++ or Visual Basic, in JavaScript you do not have the ability to define the size of a variable. For example you cannot make a variable contain only the values 0-255 by going unsigned char x; like you can in C++. Instead, JavaScript decides for you how to store the variables. To declare a variable in JavaScript, all that you need to do is go var x;, where var is the keyword for variable definition. Variables like these are "loosely-typed". In addition, all variable names in JavaScript must begin with a letter or underscore "_". For instance var _123; is legitimate but var 123_; is not.

Global Variables

A global variable is one whose value can be accessed and altered from anywhere inside a script. To make these in JavaScript simply define them outside of a function but still between the <SCRIPT></SCRIPT> tags.

Local Variables

A local variable can only be accessed from within the function that it is called. Generally, a new instance of the variable is created each time that the function is called and is destroyed after the function is through. There are some ways around this but in my experience it is a serious pain. It is better to determine the variables that you will need throughout the game and define them as global variables.

Variable Parenting

Variables can be accessed between frames as well! For instance, let's say that you have a page with two frames. You may define variables in the parent document as well as in each individual frame. To access a variable in a frame from the parent go parent.variable_name;. To access a variable between frames you may either go parent.frames[frame_index].variable_name; or parent.frames["frame_name"].variable_name;.

Arrays

Arrays are special types of variables that all programming languages have. The are basically a series of variables stored in your computer's RAM. Arrays can be especially useful when processing large amounts of information. There are two ways to make an array in JavaScript so let's look at some examples.

You may use the built in Array() function by going:

var myArray = new Array("I", " have", 28, " cats");

The above examples uses both strings and numbers and is said to contain four elements. To access the first element, the word "I", you could do something like:

alert(myArray[0]);

Notice that the index, or number between the brackets, is zero. The reason for this is fairly advanced and confuses many people. In Assembly languages the brackets symbolize addition when you are dealing with memory addresses. Since an array is a series of memory locations all in a row, the above example is telling the computer to retrieve the variable at the starting memory address of myArray plus zero bytes over.

Just remember that the first element in any array is always zero, the second is one, etc.

You may use an object-oriented method that creates a new instance of your own function like so:

function initMyArray( num ) { for (var j=0; j < num; j++) this[j] = 0; }

var myArray = new initMyArray(4);

Don't worry about exactly how this works, just realize that this is how most programmers initialize arrays when the values of the array elements are undetermined.

The for() Loop

Looping is one of the most important concepts that you will ever use in programming. There are other looping functions such as the while() function, however, I prefer to use the for() loop. The function can take as many arguments as you want to pass to it but the arguments must be divided into three segments in accordance with the following protocol:

for(initalize variables; condition; increment variables)

The function will first initialize the specified variables and then before each loop is executed the function will make sure that the condition is true. After each loop the specified variables will be incremented.

Curly braces "{}" are optional in the for() loop, however without them the loop will only perform the next line of commands, whereas with the braces all commands enclosed will be executed.

The loop terminates when the condition is false.

Now for some examples to show you some different ways of writing for() loops.

for(var i=9; i <=8; i++)
    Code ?

The above loop will not execute because 9 is never less than or equal to 8.

for(var i=0; i < 9; i++)
    Code ?

var i=0;
for( ; i < 9; i++)
    Code ?

var i=0;
for( ; i < 9; ){
    Code ?
    i++;
}

var i=0;
for( ; ; ){
    if (i++ > 9) break;
        Code ?
}

Notice that the above four loops are exactly the same, though the last one is extremely inefficient and should never be used, and will execute the code ten times.

var i=0;
for(var j=1, var k=8; i < 9; i++, j++, k+=9)
    Code ?

Note that the above code is also valid.

Trinary Operator

The trinary operator is often a very convenient way of making a simple if...then statement and is often easier to read. There are three operands involved in a trinary operator. The protocol is:

(condition) ? argument true: argument false;

Note that the two snippets below will achieve the same thing but the second one is easier to read.

if (x == 9){
    y = "September";
}else{
    y = "wrong month.";
}

y = (x == 9) ? "September" : "wrong month.";

The Lesser Known Modulus

Everyone knows how to add '+', subtract '-', multiply '*', and divide '/' in JavaScript, but there is another basic operator that is incredibly useful as well, it is called the modulo operand and is represented with the percent sign '%'. It returns the remainder value after a division. For instance, 11 % 3 = 2. For example, you may also use it to determine whether a number is even by going:

var isEven = (x % 2) ? "odd" : "even";

document.write()...As Dynamic As Older Browsers Get

In older browsers, it is impossible to change the HTML of a web page after the page has loaded. However, the document.write() gives you some versatility. To print a string to the screen all you need to do is go:

document.write("string");

To incorporate variable values and HTML simply go:

document.write("The variable <B>X</B>= ", x, " and the variable <EM>K</EM>= ", k);

You should also be aware of the escape character '\' (backslash) which when placed before the special character will allow you to display characters that may be confusing to the scripting engine, examples are slashes and extra quotations. Notice that the browser would have a difficult time interpreting this because of the extra quotations and the slashes could be confused for a closing HTML tag:

document.write(""http://www.irt.org/"");

But in the next example the computer knows exactly what you want and:

document.write("\"http:\/\/www.irt.org\/\"");

will yield:

This is very important and many people don't don't know about the escape character. (To write a backslash go \\)

Casting

Casting is a way of making the computer interpret variables different ways. For example, in C++ you can temporarily shrink a 16-bit integer into an 8-bit character by going (char)variable_name;. JavaScript also has a casting of some sort though not nearly as powerful.

You may apply the + operator to cast numbers into strings by going:

var myVar = "I can count 1" + 0

yields:

"I can count to 10"

To convert a string into an integer you may either use the - operator or the parseInt() function which has a protocol:

parseInt(string, number base [optional]);

The parse functions will search a string until it reaches a non-numeral. For example,parseInt("109.5 meters"); yields 109, which is an integer and not a floating point decimal. Using this expression parseInt("meters = 109.5") will result in NaN. Note that to do the same thing with floating point decimal numbers you may use the parseFloat() function, which was the same protocol as parseInt().

Of course, you could just use the - operator and do something like:

var abc = "109.5" - 2

which will yield the number 107.5

Precedence

Operator Precedence is an important concept. It means that JavaScript looks at some operators before others. The operator with the highest prececence of all are the parenthesis '()'. Anything contained in parenthesis is executed first. It is often easiest to just place everything in parenthesis that you want executed together.

Look at these two precedence examples, both the lines of code look the same but they do two completely different things.

8 - 4 * 3 = -4;
(8 - 4) * 3 = 12;

Here is a list of precedence for JavaScript listed from highest to lowest:

Many unintentional errors can result from false precedence.

No Pasta Please

Most novice programmers make the mistake of having code that is scattered about and can't be re-used in any way. This is a big mistake but improves with practice. When making something as complex as a game, one must write functions that have specific jobs i.e. determining if a number is even. This way other functions can also also use the function that determines if a number is even. This makes what is often referred to as "tight" code and it makes you scripts or programs much more readable, smaller, and more efficient.

For example, to make a function to return whether a number is even go:

function isEven( num ) { return (num % 2) ? false : true }

Now to make a function to determine if the first number is odd and the second is even we can go:

function isOddAndEven( num1, num2 ){
    if ( !(isEven(num1)) && isEven(num2))
        return true;
    else
        return false;
}

His Majesty, The <IMG> Tag

Can you imagine the web without images? Well, it used to be this way, but now images are an integral part of web pages. Images are especially important for web-based games because JavaScript will not allow you to plot your own pixels. Due to this dilemma, everything that is not text, or a button, etc. must be an image.

Netscape 3.x and IE 3.02+ allow you to alter an images source. This is perfect for designing games because you can keep changing the images to make it look as if a snake is moving or blocks are falling, etc. Newer browsers have better methods by allowing you to move the images around the document but we won't mess with all the DHTML this time.

The <IMG> tag has the following attributes:

~ SRC - A necessity, it tells the browser where to look for the image.
~ Border - A numeral defining width of a border in pixels around the image.
~ Height - A numeral defining the height of the image in pixels.
~ Width - A numeral defining the width of the image in pixels.
~ Name - You can name the image so that it is easier to change the source of the image later on.
~ ALT - Textual description of image in case they do not load properly.

The <IMG> tag has the following events attributed to it:

~ onClick - Event occurs when image is clicked. (Netscape 3.x and IE 4.x)
~ onMouseOver - Event occurs when the mouse hovers over the image.
~ onMouseOut - Event occurs whent the mouse hovers off the image.

So, to make an event occur when an image is clicked we can go:

<IMG SRC="pic.jpg" WIDTH="35" HEIGHT="35" BORDER="0" NAME="myPic" OnClick="alert('Thanks for Clicking!')" ALT="Example Pic">

To change an image defined in HTML as:

<IMG SRC="red.gif" NAME="myPic">

We can do either of the following:

document.myPic.src = "green.gif"
document.images[image_index_in_document].src = "green.gif"
document.images["myPic"].src = "green.gif"

BookMarklets

In case you don't want to use the onClick method for your images, you may also use what is known as a bookmarklet. This allows you to call javascript functions from within a URL. Bookmarklets are supported on all platforms in the same browsers as the onClick method, however, I use bookmarklets for asthetic reasons.

Firstly, when using bookmarklets the mouse cursor changes to a hand. Secondly, in the status bar you will see something like javascript: isEven(34), which I think is a nice touch. (call me weird)

Here is an example: (click the code)

<a href="javascript:(alert('Bookmarklets Are Fun!'))"></a>

Related items

Kick some booty with invisible Flash!

JavaScript Bookmarklets

Why bother with JavaScript?

JavaScript Games #2 - Solitaire

Writing a midi hifi system in JavaScript

JavaScript Beginners Start Here

Keeping Count of Downloads

JavaScript Games

Online JavaScript Resources

Feedback on 'JavaScripting Essentials'

©2018 Martin Webb