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.

Basic Language Features
Variables and Output
Input

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.
JavaScriptJava
Language Type Object Oriented / Interpreted Object Oriented / Compiled
Comments // & /*...*/ // & /*...*/
Console Output document.write() System.out.print()
System.out.println()
Dialog Output window.alert() JOptionPane.showMessageDialog();
Concatenation Operator + +
Variables var age = 43;
var gpa = 3.5;
var name = "Jim";
var isMale = true;
var middleInit = 'G';
int age = 43;
double gpa = 3.5;
String name = "Jim";
boolean isMale = true;
char middleInit = 'G';
Console Input name=document.getElementById('name');
age=parseInt(document.getElementById('age'));
gpa=parseFloat(document.getElementById('gpa'));
name=reader.nextLine();
age=reader.nextInt();
gpa=reader.nextDouble();
Dialog Input name=window.prompt("Enter Name");
age=parseInt(window.prompt("Enter age"));
gpa=parseFloat(window.prompt("Enter GPA"));
name=JOptionPane.showInputDialog("Enter Name");
age=Integer.parseInt(JOptionPane.showInputDialog("Enter Age"));
gpa=Double.parseDouble(JOptionPane.showInputDialog("Enter GPA"));
Math Methods Math.sqrt(num);
Math.pow(base,exp);
Math.min(num1, num2, ...);
Math.max(num1, num2, ...);
Math.round(num);
Math.ceil(num);
Math.floor(num);
Math.abs(num);
Math.random();
Math.PI;
Math.sqrt(num);
Math.pow(base,exp);
Math.min(num1, num2);
Math.max(num1, num2);
Math.round(num);
Math.ceil(num);
Math.floor(num);
Math.abs(num);
Math.random();
Math.PI;
String Methods str.length;
str.indexOf(string);
str.lastIndexOf(string);
str.charAt(num);
str.toUpperCase();
str.toLowerCase();
str.substring(start, [end]);
str.substr(start, length);
str.length;
str.indexOf(string);
str.lastIndexOf(string);
str.charAt(num);
str.toUpperCase();
str.toLowerCase();
str.substring(start, [end]);
str.equals(string);
str.equalsIgnoreCase();
str.compareTo(string);
str.compareToIgnoreCase(string);

Output


One of the easiest things to do in JavaScript is to output information to the screen. While there are many ways to send information to your web page viewer, we will concentrate on two: document.write and window.alert. These two methods produce very different outputs. document.write is used to output information into the body of a web page, while window.alert produces a pop-up window with a message.

The code written in a document.write method is the equivalent to putting text inside the body tag of your HTML markup. The information will appear wherever it is written in the source code. That being said, we can also use HTML markup inside of a document.write to modify the appearance of the text. Once the page has finished rendering, no more document.write commands can be called. Examples: document.write("Welcome to our web page. Enjoy your stay!"); document.write("<em>This is in italics.</em>"); document.write("This is written on <br/> two different lines.");
A window.alert method produces a popup window with information. The window.alert method will be called in order as the page is being rendered, often halting rendering until the user dismisses the popup. Unlike document.write, window.alert can be called to display information after a page has been rendered. Also, window.alert does not respond to HTML tags. Examples: window.alert("This site best viewed in Firefox."); window.alert("This is written on \n two different lines."); //notice the use of \n - an escape sequence that creates a new line window.alert("This output \t is separated by a tab."); //document.write and HTML typically ignore whitespace like the \t escape sequence. However, it works inside the window.alert method
In both cases, different pieces of output can be put together using the '+' command, often known as concatenation. Examples: document.write("My favorite number is "+ 17); window.alert("Hello "+"Jim"+" welcome to the program.");
However, you must be cautious of overusing the '+' symbol as errors can occur: window.alert(" The sum of 4 and 5 is "+4+5); //results in an output of 'The sum of 4 and 5 is 45
The correct code would be window.alert(" The sum of 4 and 5 is "+(4+5));


Variables


Unlike many programming languages, JavaScript does not require the type of variable to be declared. In other words, the interpreter doesn't care if a variable holds an integer, string or boolean value. You need only state that an item is a variable, by using the keyword var, and give it a name. The names of JavaScript variables must start with a letter and can be made up of letters, numbers and underscores. Example: var firstName; //used to store a string representing a first name var gpa; // used to store a decimal number representing a students gpa var isMale; // used to store a true/false value representing if a person is male var age; // used to store an integer value representing a persons age var initial; // used to represent a character value representing a persons middle initial
The above statements are all variable declarations. All they do is allocate a location in memory for the information to be stored and label that location with the given name.

To give the variables values, we need to initialize them (assign a starting value). Example: firstName="Mickey"; //double quotes around the string gpa=4.0; //no quotes around the decimal number isMale=true; //no quotes around the word true or false age=39; //no quotes around an integer number initial='G'; //single quotes around a character value * Notice the lack of the keyword var. This is because these variable had already been declared previously in the program.

Often times, variables can be declared AND initialized in the same statement: var lastName="Engel"; var birthMonth=9;
Output with Variables

To output statements that contain variables, the variable names must be outside of the quotes in order to show their value. Thus, concatenation must be used. Otherwise, if the variable name is in the quotes, the variable name will be displayed and not its value. var name="bob"; document.write("Welcome "+name); //would output Welcome bob window.alert("Welcome name"); //would output Welcome name

Input Basics


Up to this point, all variable values have been directly assigned in the code. This means that each time a program runs, the output is the same - unless, you go into the code and change the variable values. Example: var birthYear=1972; var currentYear=2013; document.write("You are "+(currentYear-birthYear)+" years old this year.");
Javascript offers the first opportunity for users to interact with a web page. This is through the use of input. Input allows us to use the same program structure as above, but instead of 'hardcoding' values into the variables, the user inputs values that are stored in the variables. This allows the program to do the same calculations with different values each time it runs. Example: var birthYear=window.prompt("What year were you born?"); var currentYear=window.prompt("What year is it now?"); document.write("You are "+(currentYear-birthYear)+" years old this year.");
See that the hard coded values of 1972 and 2013 were replaced with input functions. Whatever values the user enters when presented with these questions will be the values stored in the variables and, consequently, the values used in the calculation.
Prompting

One of the keys to gathering input from a user is to be very clear in what you are asking for. This is called a prompt. The more specific you can be with a user, the better off you will be. For example, in the code above, we prompted the users to enter a year. We could be more specific by prompting them with "What year were you born? (yyyy)". This shows the user that we need a 4 digit year as input.

window.prompt

The main method of gathering user input is the window.prompt() method. This method takes 0, 1 or 2 pieces of information. If nothing is written in the parenthesis, a blank prompt box is shown. If one string is presented, it acts as the prompt. If two strings are presented, the first is the prompt and the second is the default text that appears in the input box. window.prompt(String prompt, [String default]);
As stated above, there should always be a prompt, but the default text parameter is optional.

The one trick with the window.prompt method is that everything comes into javascript as a String. In other words, an entered value of 1972 is treated as "1972". This will prevent us from performing mathematical operations on the numerical information gathered from an input window. To fix this problem, we must parse any numerical information that comes in. This is done using parseInt for integers (non decimal numbers) and parseFloat for decimal numbers. The easiest thing to do is to put the entire prompt call inside the parse method. Again, this is only done when asking the user for numbers on which you may want to do mathematical operations. See the most recent version of the age program below: var birthYear=parseInt(window.prompt("What year were you born?")); var currentYear=parseInt(window.prompt("What year is it now?")); document.write("You are "+(currentYear-birthYear)+" years old this year.");
window.confirm

Another way to get user input is to use the window.confirm method. Like window.input, window.confirm will take a String parameter that represents the prompt. The confirm method will ask a user if something is true or false. It will then present the user with two buttons: OK (true) and CANCEL (false). This allows the user to make a choice. If set equal to a variable, the confirm method will store the values true or false in the variable. This type of information will be handy later when we learn conditions.

Standard Classes

JavaScript provides a number of classes and methods for use by programmers. A few of those items are described below:

String Class

The String class methods must be called from a string variable. In other words, var str="programming", must first be declared and the methods would be called from the str variable (str.toUpperCase()). Many string method operate on indicies, a numbered order of characters. The important thing to note is that strings start counting at 0. So, in str, the index of the character p is 0.

Math Class

The Math class methods are static methods that are called from the class name (e.g. Math.sqrt()). Each method takes at least one parameter and performs the required operations on it.

Date object

The Date class methods allow access to information about the date and time. They are accessed using Date.functionName. The Date object relies on internal clock, if set wrong, the wrong information will show.

Window Object

The window class controls the window that the content (document) appears in. We can open new windows and close others from within a document.

Document object

The document obect controls the content on the page. There are many properties that we can access, but the most common are:

Location object

The location object relates to current URL and page. WE can use the href property to either access OR set the page location.

History object

The History object contains information and methods relating to the page history. These controls can be useful for creating a book type setting or slide show.

Navigator object

The Navigator object returns information about the browser being used by the client. The methods and properties are called using navigator.function or property.