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
- JavaScript is Object Oriented
- Single line comments use //
- Multi-line comments use /*...*/
- Code can be written in an HTML document using
- Code can be written externally in a .js file and included into a web page using:
Variables and Output
- All variables in JavaScript are declared using the keyword var. This means that variables can change type throughout the run of a program, though this practice is not advised. JavaScript supports the use of int, float, String, char, boolean and even allows for user created objects.
- The concatenation operator is +
- Dialog output is accomplished using window.alert("output string here");
- On page output is written as the page is interpreted using document.write("output string here"); The output string of a write method can include HTML tags if desired. For example, to output information and then move to a new line, the br tag needs to be concatenated onto the end of the output string.
Input
- Text input can be received in dialog form using window.prompt("prompt","default response");. All information returned from this method is returned in the form of a string. Use parseInt or parseDouble to convert the strings.
- A boolean value can also be returned from a dialog box using window.confirm('prompt');.
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 |
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("This is in italics.");
document.write("This is written on
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.
- length - a property (not method) that returns the number of characters in the string (str.length returns 11)
- indexOf(string) - returns the starting index of the first occurence of string in str, -1 if not found (str.indexOf("gram") returns 3)
- lastIndexOf(string) - does the same as indexOf, but counts backwards from the end
- charAt(num) - returns the character at the specified index (str.charAt(4) returns "r")
- toUpperCase() - returns the string as all upper case (str.toUpperCase() returns PROGRAMMING)
- toLowerCase() - returns the string as all lower case
- substring(start, [end]) - returns a substring of the string starting at start, up to but not including end. If end is not specified, the remainder of the string is included (str.substring(3, 7) returns "gram", str.substring(7) returns "ming")
- link(url) - takes a string and makes it an active link to the url
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.
- Math.sqrt(num) - returns the square root of the num
- Math.pow(base, exp) - returns base raised to the exp power
- Math.min(num1, num2, ...) - returns the smallest of the list of numbers
- Math.max(num1, num2, ...) - returns the largest of the list of numbers
- Math.round(num) - returns the rounded value of num (.5+ rounds up, under .5 rounds down)
- Math.ceil(num) - returns the next highest integer - rounds up (4.2 returns 5)
- Math.floor(num) - returns the next lowest integer - rounds down (6.8 returns 6)
- Math.abs(num) - returns the absolute value of num (-5 returns 5)
- Math.random() - returns a random value between 0 and 1.0
- Math.PI - a constant used to represent 3.1415...
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.
- getDate() – returns the day of the month
- getDay() – returns day of the week
- getFullYear() – returns full year
- getHours() – returns hour
- getMinutes() – returns minutes
- getMonth() – returns month as a number
- getSeconds() – returns seconds
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.
- close( ) – closes specified window: myWindow.close()
- open ( ) – opens a new window: myWindow=window.open(“source.html”,”target name”,”options”)
options: toolbar, location, directories, status, menubar, scrollbars, resizable (all yes|no),width, height(in pixels)
options are separated by commas, default is no
Document object
The document obect controls the content on the page. There are many properties that we can access, but the most common are:
- document.lastModified - displays the date/time of modification, automatically updated
- document.title – sets the document title
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.
- location.href=”url” – sets address to url
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.
- forward() – moves forward one entry
- back() – moves back one entry
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.
- javaEnabled() – returns true or false
- appName – return name of application
- appVersion – returns application version
- cookieEnabled – true or false to see if browser accepts persistent cookies
- platform – a string representing the platform that the browser is running on
- userAgent –a string representing the userAgent heade