JAVASCRIPT: For Programmers



About JavaScript

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.
JavaJavaScript
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';
Console Input name=reader.nextLine();
age=reader.nextInt();
gpa=reader.nextDouble();
Console
const prompt=require('prompt-sync')();
name=prompt("Enter name:");
age=parseInt(prompt("Age:"));
gpa=parseFloat(prompt("GPA:"));
*may require console command: npm install prompt-sync
HTML
name=document.getElementById('name');
age=parseInt(document.getElementById('age'));
gpa=parseFloat(document.getElementById('gpa'));
Dialog Input name=JOptionPane.showInputDialog("Enter Name");
age=Integer.parseInt(JOptionPane.showInputDialog("Enter Age"));
gpa=Double.parseDouble(JOptionPane.showInputDialog("Enter GPA"));
name=window.prompt("Enter Name");
age=parseInt(window.prompt("Enter age"));
gpa=parseFloat(window.prompt("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.equals(string);
str.equalsIgnoreCase();
str.compareTo(string);
str.compareToIgnoreCase(string);
str.length;
str.indexOf(string);
str.lastIndexOf(string);
str.charAt(num);
str.toUpperCase();
str.toLowerCase();
str.substring(start, [end]);
str.substr(start, length);
Conditions if(condition)
code
else
code
if(condition)
code
else
code
For Loop for(int x=0; x<5; x++) for(var x=0; x<5; x++)
While Loop while(condition) while(condition)
do...while do{...}while(condition); do{...}while(condition);
Functions 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
Variables and Output
Input

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.
if(condition){
    ...true code...
}
else{
	...false code...
}
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).
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().
var arr=[];
arr.push(5);            //arr={5}
arr.push(10);           //arr={5,10}
arr.push(3);            //arr={5,10,3}
arr.push(20);           //arr={5,10,3,20}
document.write(arr[1]); //10

The JavaScript DOM
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>