Overview
JavaScript is a client side programming language designed to give life to the web. JavaScript is interpreted on the fly by the clients browser. Different browsers handle some elements of JavaScript differently, so sometimes, cross browser coding is necessary. Below, you will find a simple guide for programmers as an introduction to JavaScript. Those who have programmed in C++, Java or C# should have little difficulty in making the transition.
Methods
JavaScript allows the creation of functions. Without functions, JavaScript code will run automatically when encountered. JavaScript functions can take multiple parameters, but can only return one variable. The basic syntax for creating a function is:
function functionName(parameter list){
code
}
JavaScript functions can be called from other JavaScript code, from the href attribute of an a tag, or using events.
Arrays
In JavaScript, an array is an object. So, variables that store arrays must be declared and instantiated
var names=new Array();. While the typical array subscript notation is allowed, JavaScript also provides several methods for manipulating the array including pop(), push(), shift(), and unshift().
JavaScript vs. Java
Below you will find a table comparing many of the basic commands/ideas from Java and JavaScript. This table will help JavaScript programmers see some basic differences between the two languages.
| JavaScript | Java |
Functions |
function funcName (age, gpa){ code; return value;} |
public static int funcName(int age, double gpa){ code; return value;} |
Arrays |
var arr=[]; arr[0]=53; |
int [] arr=new int[10]; arr[0]=53; |
Function Review
In a web pages, JavaScript code written in <script> tags executes automatically when the page loads it. For example, a page that has some text, JavaScript alert code and two images (in that order), will load the text, pop up the alert, and will only show the images AFTER the alert has been dismissed. In order to keep the alert from happening until we want it to, we need to put the JavaScript code in a function (also known as a method). A function is defined as a type of procedure or routine. The idea is that we encapsulate several lines of code that may need to be called often into a function so that they can be called with a single line. In JavaScript, a function is written using the following code:
function functionName() {
//lines of code go here
}
Where "functionName" is any valid identifier name. Like with variables, the name should be indicative of what the function does. If the function is designed to calculate a persons pay, we may call it calculatePay. Regardless of the name, it should always be followed by a set of parenthesis () and curly braces {}. All of the code for the method goes in the curly braces.
function alertHello(){
window.alert("Hello");
}
Any JavaScript code can be placed in a function. We can write functions that would draw shapes on a canvas, ask users for information and perform calculations, etc. The main difference at this point, is that the code in a function WILL NOT EXECUTE until we call it, whereas all other JavaScript on the page will execute as it is loaded.
Information can be sent into a function using parameters. Parameters are a comma separated list of variables inside the parenthesis. The parameter variables must be given a value prior to the function being called. In the example below, the variables value1, value2 and value3 are initialized in the main and then sent into the function. In the function, they are referred to by their parameter names, param1, param2, and param3, where param1=value1, param2=value2 and param3=value3.
function function1(param1, param2, param3){
window.alert(param1+param2+param3);
}
///main javascript code
var value1=5;
var value2=6;
var value3=7;
function1(value1, value2, value3);
Function Returns
We have now seen how to send informtion into a function, but to get information back from a function we use a return statement. A function can only return one value, so it is important to create functions that complete a single task. It is also important to store the value that is returned in a variable. See the example below.
function mult(val1, val2){
var product=val1*val2;
return product;
}
//main code
var num1=parseInt(window.prompt("Enter a number"));
var num2=parseInt(window.prompt("Enter a number"));
var result=mult(num1, num2); //result now stores the value of the product variable from the method
window.alert(result);
Arrays
An array is an ordered collection of data of the same type. Arrays allow us to store multiple values in a structure that can be looped through as opposed to creating multiple variables or writing over previous information. For example, if we wanted to store three names in a program, we would write the following:
var name1="Mickey Mouse";
var name2="Tom Cat";
var name3="Big Bird";
However, what if I wanted to store 30 names? 100? 1,000? That is a lot of variables to keep track of. Arrays allow us to store all of the names in one variable that is sectioned into parts.
In many programming languages, arrays need a maximum size assigned at the time of creation. In JavaScript, this is NOT the case. An array can be created without a maximum size and items can be added as needed.
When an array is instantiated, the computer allocates a set of consecutive spaces in memory. These spaces are then sequentially numbered for reference using indicies. The first index of an array is always 0. This means that an array with 10 elements has indicies of 0-9, inclusive. Trying to reference information in index 10 will result in an error.
The syntax of referencing an array element is arrayName[index]. This syntax can be on the left or right side of an assignment statement, compared to other values, output, or sent as a parameter to a method. In other words, it can be treated like any other variable. So, to assign the first element of a names array tot he name "Joe Smith", the code would be as follows:
names[0] = "Joe Smith";
Declaring Arrays
When declaring a 1D array, we create it like any JavaScript variable. The difference is we initialize it (set its initial value) to empty square brackets []. This tells the computer to treat this variable as an array. So, the declaration of our names array would be:
var names = [];
The names array can store any type of information, but all of the information in the array should be of the same type (string, int, double, boolean, etc).
Arrays can also be created with information already in them. If you know the information to be stored in the array at the time of creation, simply list the data, separated by commas in the square brackets. Remember, strings need quotes, but ints, doubles and booleans do not.
var names = ["Mickey Mouse", "Tom Cat", "Big Bird"];
Built In Properties & Methods
An array in JavaScript is an Object. This means that the variable, once created, has certain properties and methods that can be accessed. For the purposes of these examples, we will be working with the names array created previously.
- names.length - returns the number of elements in the arrays (will be one more than the highest index)
- names.push(value) - adds the value to the end of the array and increases the array size by 1. The push method eliminates the need to write names[names.length]=value.
- names.indexOf(value) - returns the index of the value that you are searching for in the array. If the value is not found, -1 is returned.
- names.sort() - sorts the items in the array into ascending alphabetical/numerical order.
Traversing Arrays
The advantage of using arrays is the ability to cycle through a set of data using a loop structure. Typically, this looop is a counting loop used to iterate through the indicies of the array. The loop efficiency is dependent on the array length property. By using the length property instead of a literal number, our loop will continue to work properly even if the array size changes.
for(var x=0; x
The loop body can do any number of things, such as:
- Output the information document.write(names[x]);
- Assign information names[x] = window.prompt("Enter a nmae");
- Search for a value if(names[x] == "Joe Smith")
- Keep a running total sum+=studentGrades[x];
Parallel Arrays
Sometimes, we have multiple pieces of data that belong together, such as a student name, phone number and grade. Some programmers will make multiple arrays of the same size, two of type string for name and phone and one of type int for the grade. These arrays are called prapllel arrays becasue the data in each index is partnered with the data in the same index of the other arrays. This is a great way to store information, but proceed with caution because sorting one array will leave the elements of the other arrays unmatched and our data will no longer correspond properly.