A Brief Introduction to JavaScript & Programming

By Philip Likens

Scripting in JavaScript

We can use JavaScript to create small programs or Scripts that will run in our browser. Up to this point we have not learned anything about interacting with the user, manipulating the browser or creating programs that do much of anything useful. We will continue to introduce built-in features of JavaScript, but this section will be more focused on how we can use these elements rather than introducing you to the concept of the element itself. To continue our previous analogy - we're going to begin driving.

I will take a moment to remind you, any of the code you see below should be put inside <script> tags. I would also strongly suggest, as I did earlier, that you use Firefox with the Firebug plugin installed to view your scripts - it will be extremely helpful in debugging your code should you miscopy or mistype something.

Reading Code Specs

Many times you will see coding guides or websites write functions something like this:

string prompt ( string msg [, mixed input ] )

What does all of this mean?

First of all, we are looking at the prompt function so prompt() would be our base syntax for a prompt function - which means the rest of the words have to do with the other specifics of how we write our prompt function. If there is a word in front of our function name, it typically is telling us what value will be returned from our function. In this case, it is a string that will be returned. So now we know that our prompt() function will return a string when we call it. Now we need to figure out what parameters we need to pass into our function. Any parameters you must include will be sitting just inside the parentheses, separated by commas. Any optional parameters will be set aside with square brackets []. Typically the parameter will be grouped into two words - the first should tell you the data type the function is expecting, the second should give you a hint as to what that parameter does. In this case, the first parameter is mandatory, should be a string, and will be a message to the user. The second parameter is optional, if you're going to include it you'll need to put a comma in before it, the data type is mixed meaning most any data type will work, and the word input is to denote the fact that the second parameter specifies what will go into the prompt's input field.

I have taken the liberty of bolding the name of the function and italicizing the data types for you, so it will make it easier to differentiate.

Here are a few examples of how we might write a prompt, in light of the guide above:

var state = prompt("What is your favorite state?","Texas");
var num = prompt("What is your favorite number?",7);
prompt("True or False?",true);

As you can see, the first parameter is always a string. The second parameter is optional, and can contain a string, boolean or number. A prompt box returns a string, which we can choose to catch inside a variable on the lefthand side, or ignore.

Dialog Boxes

One of the easiest and most basic ways of giving a user information, and also requesting feedback, is through the use of dialog boxes. In JavaScript there are three types of built-in functions that produce dialog boxes - Alert, Confirm and Prompt. Each type of dialog box is meant to do a different task.

Alert

An alert is the first type of dialog box we'll discuss. An alert is useful for passing a message to a user. The syntax for an alert box is simply:

alert(string msg)

For example:

alert("Hello World");

Our example will pop up a dialog box showing the words Hello World to the user. Go ahead and retype the code above into your HTML document, between the script tags. Your HTML document should end up looking something like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My First JavaScript!</title>
</head>
<body>

<script type="text/javascript">
// All of our code goes here between
// the script tags like so:
alert("Hello World");
</script>

</body>
</html>

This is the only time I will show you what the HTML document should look like, I just thought it would be best to be sure we were on the same page. You are welcome to copy and paste what I have here as a template for all your other code. Though, keep in mind, each example I show you is meant to be independent of all other JavaScript code, unless otherwise noted. So if you use the code I've given you, but sure to delete the alert("Hello World"); line before you create your new script - otherwise you'll have a dialog box popping up in every script you create.

So an alert basically just gives us a way to interact with the user unidirectionally - meaning we only tell the user something, the user cannot respond. We can alert anything we would like - a string as we did with "Hello World", a number, a boolean value, a variable. If you put an expression inside an alert, JavaScript will run the expression then alert it. For instance:

alert("Hello " + "World"); // Shows "Hello World"

The example above concatenates the two words, then runs the alert. It is also important to note that popping up an alert, or any other dialog box, will stop the script from running further until the dialog box is closed. For example:

alert("Hello");
alert("World");

This script would pop up a dialog box containing "Hello" then pause before it does anything else. Once the user closes the first dialog box, JavaScript will execute the second line, again pausing the script.

Confirm

A confirm box is similar to a dialog box with one major difference, it gives the user two options for feedback, and returns the value they choose (a boolean true for ok or false for cancel). The proper syntax for using a confirm function, that will pop up a confirm box, is:

boolean confirm ( string statement )

Statement is whatever we want our dialog box to display. Consider the following:

var feedback = confirm( "It is sunny outside" );

This code opens a dialog box containing the words "It is sunny outside" and gives the user the option of ok or cancel. Once the user presses ok or cancel, the corresponding boolean value is returned from our confirm function and saved into our variable feedback. So if the user hits "ok", feedback will contain the boolean value true. If the user hits cancel, our variable will contain false. If you've tried this, you might be thinking "What if the user hits the X (close button in the top right)?" Good question. If the user simply presses the X in the top right corner of our dialog box, our function will return false just like it would if they had clicked on cancel.

Prompt

A prompt is a little more fancy than the other two functions we've see so far. A prompt allows us to ask the user for some sort of written feedback. Once they hit ok, the function will return whatever the user typed (or didn't type if they left it blank). If the user presses either cancel or closes the dialog box with the top right X button, the function will return null (not the string "null" but the actual data type null). The syntax for a prompt box is as follows:

string prompt ( string msg [, mixed input ] )

Msg is where we place whatever we want to say to the user, and input is an optional parameter that can be used to show a default answer in the text box where the user will type. Here's an example that asks the user for their age and gives a default value of 21. We are also setting up a variable userAge to capture whatever information the user enters.

var userAge = prompt( "What is your age?", 21 );

The variable userAge will then either contain whatever the user typed, 21 if they left the default answer, or null if they canceled out of the prompt. It is important to note that anything the user enters, whether it be true, false, a number or a string - all feedback will be returned as a string data type, if it is not null. It's then up to you to convert their response to whatever data type you need it to be. So to use the previous example, we might want to convert userAge to a string using parseInt so we can see if the user is of a certain age. To do so, you would add the following line:

userAgeNum = parseInt( userAge );

Now userAgeNum will either contain NaN (Not a Number) or a numeric value that we can then use in comparisons or math operations.

Core Objects

Core objects are objects JavaScript has built in that give us access to methods and properties that we can use to manipulate or retrieve information from those objects. For instance, any array we create has a built in property that can tell us the length of the array (the number of indexes). For any string we have methods, because of these core objects, that we can call that will change our string to capital or lower case letters.

We will not cover all the properties or methods of these objects, only the most useful ones under normal circumstances. There may be extenuating circumstances when it will be required to use other methods or functions - you can find a more complete list on other websites.

Array Object

Array Properties

Length returns the number of indexes in an array - if an array has indexes of 0-5, the length is 6.

number (array var).length

Array Methods

Further resources on Array Methods can be found at JavaScript Kit.

Concat concatenates any values, including other arrays, onto the end of the original array and returns a new array. Does not modify the original array.

array (array var).concat(mixed value [,... ])

Join creates a string of all the elements of an array, each element separated, or delimited by the specified string.

array (array var).join(string separator)

Pop deletes and returns the last element of an array.

mixed (array var).pop()

Push modifies the original array, adding any values specified onto the end and returns the new length of the modified array.

int (array var).push(mixed value [,... ])

Reverse reverses all elements in an array.

(array var).reverse()

Shift deletes the first element of an array and returns that element.

mixed (array var).shift()

Slice returns the values of an array between the starting index and the end, or the optional ending index.

array (array var).slice(int start [, int end])

Splice deletes the remainder (optionally count will only delete the specified number) of an array beginning with the start index and returns the values being deleted. Optionally you may specify values to replace the deleted portions of the array.

array (array var).splice(int start [, int count] [, mixed value1, ...])

toString returns a string representing all the elements in the original array.

string (array var).toString()

Unshift adds values to the beginning of an array, modifying the original array and returning the resulting array's new length.

int (array var).unshift(mixed value1 [, ...])

Date Object

See http://www.javascriptkit.com/jsref/date.shtml

Document Object

See http://w3schools.com/htmldom/dom_obj_document.asp

Math Object

Math Properties

Math.PI returns the number pi, correct up to 48 decimal places. Use the toFixed method to specify the precision of the decimals - 15 is the default.

Math.PI

Math Methods

Math.abs returns the absolute of the number in parenthesis.

number Math.abs(number num)

Math.ceil rounds the given number up to the nearest whole number.

number Math.ceil(number num)

Math.cos returns the arc cosine of the number in radians.

number Math.cos(number num)

Math.floor rounds the given number down to the nearest whole number.

number Math.floor(number num)

Math.max compares and returns the highest number of the pair.

number Math.max(number num1, number num2)

Math.min compares and returns the lowest number of the pair.

number Math.min(number num1, number num2)

Math.pow returns the result of raising the number to the exponent.

number Math.pow(number num, number exponent)

Math.random returns a random number between 0 and 1.

number Math.random()

Math.round rounds the number to the nearest whole number - .5 will round up.

number Math.round(number num)

Math.sin returns the arc sine of the number in radians.

number Math.sin(number num)

Math.sqrt will return the square root of the number up to 16 decimal places.

number Math.sqrt(number num)

Math.tan returns the arc tangent of the number in radians.

number Math.tan(number num)

Number Object

Number Properties

Number.MAX_VALUE gives the maximum value available in JavaScript.

Number.MAX_VALUE

var bigNum = Number.MAX_VALUE;

Number.MIN_VALUE gives the minimum value available in JavaScript.

Number.MIN_VALUE

NaN stands for Not a Number.

NaN

Number.NEGATIVE_INFINITY represents the value of negative infinity in JavaScript.

Number.NEGATIVE_INFINITY

Number.POSITIVE_INFITIY represents the value of infinity in JavaScript..

Number.POSITIVE_INFITIY

Number Methods

ToFixed formats a number to match the length of decimal places, rounding and filling in 0s where necessary.

int (int var).toFixed(int length)

ToString converts a number to a string. Radix allows you to specify a base in order to facilitate number conversions.

string (int var).toString(int radix)

var num = 14;
var convertedNum = num.toString(16); // e

String Object

String Properties

Length returns the length of the string by number of characters, spaces and punctuation included.

number (string var).length

var name = "Bob";
var nameLength = name.length; // nameLength will be 3

String Methods

CharAt returns the character or space at a given index position in a string.

int (string var).charAt(int index)

Concat combines more than one string and returns the result. The original strings are not modified.

string (string var).concat(string string1,string string2 [,...])

IndexOf searches for a string (searchTerm) inside another string - if a match is found the index value of the match will be returned. If no match is found, -1 will be returned. The startPos parameter is optional and defaults to 0.

int (string var).indexOf(string searchTerm [, int startPos])

LastIndexOf does the same thing IndexOf does, except it returns the index of the last match, rather than the first.

int (string var).lastIndexOf(string searchTerm [, int startPos])

Slice selects and returns a portion of the string, from the start index position up to, but not including, the optional end index position. If no end is specified, Slice will return the string from the start position on. Starting and ending positions can be negative, in which case javascript will count a number of places from the end of the string toward the beginning: -1 in the string "abcd" would be d.

string (string var).slice(int startPos [, int endPos])

Split breaks a string into pieces wherever the delimiter is found and returns an array of all the pieces.

string (string var).split(string delimiter)

Substr extracts and returns a string from the start index position, through the length specified.

string (string var).substr(int startPos [, int length])

ToLowerCase converts an entire string to lowercase.

string (string var).toLowerCase()

ToUpperCase converts an entire string to uppercase.

string (string var).toUpperCase()

Still to Come

Custom Objects
The Document Object Model
Events
Event Listeners
Regular Expressions

JavaScript uses Perl style regular expressions

-- replace(string searchTerm, string replaceValue) - Regular Expressions

-- search(regExp)