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.
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.
Java
JavaScript
Language Type
Object Oriented / Compiled
Object Oriented / Interpreted
Comments
// & /*...*/
// & /*...*/
Console Output
System.out.print() System.out.println()
Console-> console.log(); HTML-> document.write();
Dialog Output
JOptionPane.showMessageDialog();
window.alert()
Concatenation Operator
+
+
Variables
int age = 43; double gpa = 3.5; String name = "Jim"; boolean isMale = true; char middleInit = 'G';
var age = 43; var gpa = 3.5; var name = "Jim"; var isMale = true; var middleInit = 'G';
public static int funcName(int age, double gpa){ code; return value;}
function funcName (age, gpa){ code; return value;}
Arrays
int [] arr=new int[10]; arr[0]=53;
var arr=[]; arr[0]=53;
Language Features
Below is a list of JavaScript language features with a little more explanation than in the table above.
Basics
JavaScript is Object Oriented
Single line comments use //
Multi-line comments use /*...*/
Code can be written in an HTML document using
<script>...</script>
Code can be written externally in a .js file and included into a web page using:
<script src='jscode.js'></script>
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(). 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.
document.write("output string here <br/>");
document.write("This will be on a new line.");
Input
Text input can be received in dialog form using window.prompt(). window.prompt() takes a string parameter which is the question and a second, optional, string parameter to show a default value in the window (often used to show users desired format). All information returned from this method is returned in the form of a string. Use parseInt or parseDouble to convert the strings.
var birthYear=parseInt(window.prompt("What year were you born?","Ex: 1999");
A boolean value can also be returned from a dialog box using window.confirm().
window.confirm('prompt');
Conditions
JavaScript supports the use of if...else structures and switch statements. The logical operators used are &&(AND), ||(OR), and !(NOT). Also, the use of == is for comparison, while = is for assignment.
switch(variable){
case value: code; break;
case value: code; break;
default: code;
}
Iteration(Loops)
JavaScript supports the use of for, while and do...while structures. The format for each of these loops is the same as in Java, except remember to use var instead of Java types. In addition, there exists a for each loop. The format of a for each loop is as follows:
for(var x in arr){code}
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.
Events
Events are actions, triggered by a user, that cause code to be executed. It is the ability to create and handle events that allows JavaScript to help make the web dynamic and interactive. Most often, an event is written as an attribute of an HTML tag and calls a JavaScript method. That method then uses JavaScript and the DOM to gather information and make changes to the page. Here is a list of some events and the HTML elements that they can be used on. This is not an exhaustive list, but a list of commonly used events and the elements that they are most often used on(in parenthesis).
onblur - when an element loses focus (button, input, label, select, textarea, body)
onchange - selection in an alement loses focus and value changes when focus returns (input, select, textarea)
onclick - mouse press and release(most elements)
onfocus - when an element gains focus (button, input, label, select, textarea, body)
onload - when the element completes loading (body, img)
onmouseover - when the mouse enters an element (most elements)
onmouseout - when the mouse exits an element(most elements)
This is an example of code that swaps images based on the mouse rolling over/out of it.
<script>
function over(){
document.getElementById('pic').src="picover.jpg";
}
function out(){
document.getElementById('pic').src="originalPic.jpg";
}
</script>
<img src='originalPic.jpg' id='pic' onmouseover='over()' onmouseout='out()' />
Arrays
In JavaScript, an array is an object. While the typical array subscript notation is allowed, JavaScript also provides several methods for manipulating the array including pop(), push(), shift(), and unshift().
The most common way to enter the DOM is using an element's id attribute and the document object. The element is returned as an object though the document.getElementById() method. Once we have the element object, we can use a variety of methods to alter it attributes and contents. The easiest way to do alter the content of the object is to use .innerHTML(). The innerHTML method takes a single parameter of the string type that can contain both text and html and replaces all html within the opening and closing tags. Attributes of the desired element can be altered using the setAttribute() method. The setAttribute method takes two string parameters, the first being the attribute and the second being the value. Finally, styles can be changed in the DOM using the .style.property='value' property. So, in an example of the above, if we wanted to alter the size and color of a div with id 'myDiv', we would do the following:
<div id='myDiv' onclick='change()'><div>
<script>
function change(){
var div=document.getElementById('myDiv');
div.setAttribute('width', '100px'); //sets the width of the div to 100px
div.style.backgroundColor='blue'; //changes the background color to blue
div.innerHTML('<em>Italic text</em>'); //add the words Italic text (in italics) to the inside of the div
}
</script>