Javascript Crash Course (for Java programmers)

This tutorial attempts to create a Javascript coding environment for a developer as close to Java-style OOP as possible. It’s pretty raw right now, and I tend to dumb things down for the sake of clarity, so feel free to tell me where I’m wrong, where I’ve left things out or where I should add more. :)

One quick note: because I’m assuming you’re a Java programmer, I’m going to make JavaScript as OOPy as possible. For example, even though many methods in JavaScript don’t require you to explicitly note the object that declared them, I’ll make sure to always provide the object, as you would with Java. The most blatant example will be any method called on the window object. If you see a method call like window.alert(), just know that you can remove the object call and just say alert() (in fact most other tutorials on the Web would show you it that way since it’s shorter).

  1. Embedding Javascript in an HTML file
  2. Useful Built-in Functions
  3. Variables
  4. Loops
  5. Function Basics
  6. Classes
  7. JSON
  8. jQuery
  9. jQuery Functions

 

Embedding Javascript in an HTML file

First off, you gotta know where to put your code. As I’m sure you’re aware, Javascript is (most commonly) a client-side programming language (meaning: JavaScript is interpreted by a user’s Web browser, not by a server). Since browsers are built to understand HTML documents, Javascript code is written within these documents. If you want to write your Javascript separately, you can (for all intents and purposes) tell the browser to copy and paste the code from external files behind the scenes. No matter how many times and ways you add Javascript code to your HTML file, all the code will be visible to all the code added after it. And, just as in Java, functions (methods) can be written and called in any order.

<html>
    <head>
        <script type='text/javascript'>
            //This code is embedded into the head of a document.
            /*
            Generally speaking, code that runs here will run before
            the html for the page has loaded.
            There are various ways to get around this.
            */
            //The following line attempts to grab data from an HTML element
            document.getElementById('paragraph1').innerHTML; //Error!
            //Error thrown because no HTML elements exist yet.
        </script>
    </head>
    <body>
        <p id='paragraph1'>Hello, World</p>
        <script type='text/javascript'>
            //This code is embedded into the body of a document.
            //This code will generally run after the html written
            //before it has loaded.
            console.log(document.getElementById('paragraph1').innerHTML);
            //Prints out "Hello, World" to the console (similar to System.out.println)
        </script>
        <script type="text/javascript" src="http://tinyurl.com/jquery-code-js">
/*
Javascript from http://tinyurl.com/jquery-code-js
will run as if it were copied and pasted right here.
*/
        </script>
    </body>
</html>

Code added in any (or all) of the above ways just runs. You don’t need to add anything special like import statements, and you don’t need to compile your code, just open your page in a browser and voilà, your code runs.

Useful built-in functions

<script type='text/javascript'>

console.log("Hello, world"); //Use this like System.out.println()...
window.typeof("Hello, world"); //Similar to Java's obj.getClass().getName()
window.Number("1337"); //One of many built-in casting functions
window.eval("("+"{var1:1}"+")"); //Interprets string as code, used for JSON, etc.

//Finally, just cause I'd get looked at funny if I didn't mention it...
document.getElementById("html_id_name");
/*
This function and ones similar to it are the basis for interacting with
html elements  (the first major use of Javascript, known as DHTML).
However, we'll see below why using jQuery supersedes this or any
similar function of out-of-the-box Javascript.
*/

</script>

Javascript Variables

Yes, variables are very basic, but whenever you’re switching languages it’s always good to have a reference for initializing, scoping, boolean, and typing concerns…

<script type='text/javascript'>

//Initialization
   var x = 1; //Initialize block scope - use in functions, etc.
   this.z = 3; //Initialize object-scope - use in classes
   y = 1; //Initialize global scope - this is evil!

//Boolean vars
   var b_t = true;
   var b_f = false;
   console.log(b_t == 1); //"true"
   console.log(b_f == 0); //"true"
   console.log(b_t != 1); //"false"
   console.log(b_f != 0); //"false"
   console.log(b_t === 1); //"false"
   console.log(b_f === 0); //"false"
   console.log(b_t !== 1); //"true"
   console.log(b_f !== 0); //"true"

//"Loosely typed"
   var x = "yo";
   console.log(typeof(x)); //"string"
   x = 2; //This is fine
   console.log(typeof(x)); //"number"
   x = function(){console.log("hello");} //This is also fine
   console.log(window.typeof(x)); //"function"
   x(); //Alerts "hello"
   x = ["one","two","three"]; //An array, as you'd expect
   x = []; //An empty array
   x = new Array(3); //An array of size three
   console.log(window.typeof(x)); //"object"
   console.log(x instanceof Array); //"true"

</script>

Javascript Loops

(while, and do while are identical to Java)

<script type='text/javascript'>

for (var i = 0; i < var_arr.length; i++){}

/*
The for each loop is one of many reasons that prototypes are evil.
Just know, if you've used prototypes, this loop will not do what
you expect - especially on basic arrays.
*/
for (var obj in array_variable){}

</script>

Javascript Function Basics

      • Functions can be defined without a parent object, though if you’re used to Java, there’s no reason not to stick with strict OOP
      • Function names can be appended like strings
      • Functions are defined just like any other variable, and passed around as parameters
//If you don't make an explicit parent object, the object is "window"
window['func'+'tion'+1] = function(){ return "Hello, world"}
var y = ["Hello",123,function1];
alert(y[2]()); //alerts "Hello, world"

Javascript Classes

Unfortunately, while stripped down Java-style classes are possible in Javascript, they’re called functions, which just confuses everything. Here’s an example that should give you an idea of how to implement them:

<script type='text/javascript'>

function Foo(stringVariable){
//The constructor is implicit, all code just runs

//You don't need to initialize class vars, but it's good form
	this.stringVariable = ""; 

//Think of this like a member function (or an inner class (or both)).
    this.setStringVariable = function(stringVariable){
        this.stringVariable = stringVariable;
    }
    this.printStringVariable = function(){
      alert(this.stringVariable);
    }

/*
Since the class definition is the constructor,
this explicit constructor is fake and kludgy,
but if you're used to Java, it's nice and useful
and helps you feel at home :)
*/
    function constructor(obj,stringVariable){
	obj.stringVariable = stringVariable;
    }
    constructor(this,stringVariable); //Calling it cause it's fake

    //The new keyword does this anyway, but in case you forget to use it...
    return this;
}

foo = new Foo("Hello, World");
foo.printStringVariable(); //alerts "Hello, world"
foo.setStringVariable("Goodbye, Hal");
foo.printStringVariable(); //alerts "Goodbye, Hal"

</script>

JSON

Javascript Object Notation (json) takes advantage of Javascript’s immensely reflective nature by structuring the definition of every variable or function as a multi-dimensional associative array.

<script type='text/javascript'>
//Traditional definition
function ClassName () {
  this.x = "hello";
  this.y = 3;
  this.z = function(){
      return "Hello, world";
  }
}

//Identical object:
ClassName = {x : "hello", y : 3, z : function(){return "Hello, world"} };
</script>

As you can imagine, there are many exciting ramifications to this.

Some more in depth manipulation of JSON

//We'll have to use one jQuery function in this example
<script type="text/javascript" src="http://tinyurl.com/jquery-code">
</script>
<script type='text/javascript'>

//Syntax explanation through example
var foo = {bar:"bam"};
alert(foo.bar == foo['bar']); //true
alert(foo.bar == for["bar"]) //true
alert(foo.bar == foo[bar]) //ReferenceError: bar is not defined

//json as associative array fun
var json1 = {var1 : "W007" , var2 : "Weee"};
var json2 = {"var1":"W007","var2":"Weee"};
alert(json1.var1 == json2.var1); //"true"
json1 = json2; //Copies reference
json1.var2 = "Hello";
alert(json2.var2); //"Hello"
json1 = $.extend(true, {}, json2); //jQuery's deep copy method
json1.var2 = "the end";
alert(json2.var2) //"Hello";

//eval() is generally used upon receiving a json string from the server
var data_arr = "{ getData : function(){ alert('Hello, world') } }";
data_arr = eval('('+data_arr+')'); //Don't forget the extra parentheses
data_arr.getData(); //alerts "Hello, world"
</script>

jQuery

Javascript is great and all, however, it can get pretty kludgy pretty quickly when trying to use it to manipulate the DOM. Take the following line to do one of the most common tasks in Javascript programming:

document.getElementByTagName(‘p’)[0].getElementByClassName(‘title’)[0].innerHTML

If you’re familiar with CSS, you’ll notice that this is a longhand way of doing what CSS Selectors were designed to do concisely over a decade ago! Fortunately, the jQuery Javascript library lets us manipulate HTML the way it was built to be manipulated. As a counter-example:

$.(‘p:first-child > .par1′)[0].html()

The clever reader will note that we’ve twice seen how to add jQuery to our programming environment. In our first code example, the last code snippet added the jquery library. As a sanity check, here’s the full url: http://code.jquery.com/jquery-1.4.4.min.js. Any code added after it on the page will be able to access its functions.

Useful jQuery functions

<script type='text/javascript'>

/*
Our first and most important function grabs the html element(s)
that fit the parameter's CSS Selector. Unless you end the selector with
an id name, it will give you an array of results, which you can either
grab explicitly with array notation or loop over.
*/
$("#idName .className tagName")[0];//param is made of jQuery selectors

/*
The rest of the methods are appended to the end of the previous
method and let you interact with the element you've selected.
*/

each(function(){});//loop over selected elements
click(function(){});//respond to click event of HTML element
hide();//hide selected element(s)
show();//show selected element(s)
/*
The following two methods are useful as they allow you to
use multiple ids within one webpage, as long as the
two elements are never used together (e.g. tabbed browsing)
*/
detach();//remove selected elements from DOM
append($('#otherElement'));//add given elements to selected element

html("Hello, world"); //No params implies get(), one param implies set()
attr("id","newIdName"); //1 param implies get(), two params imply set()
hasClass("className"); //Returns boolean true or false
addClass("className"); //Add a class to an element
removeClass("className"); //Remove a class
/*
The last method in this set I would try to avoid.
It's very quick and useful, however, its almost always better to
use the previous two methods instead, as that implies the logic
of your interface was planned out in your CSS files.
*/
css("color","red");//One param implies get(), two params imply set()
</script>

And that’s it for Javascript. Comment to let me know what I should add, or move on to the AJAX crash course.

  • http://twitter.com/CianOMahony Cian O’Mahony

    Great stuff, thanks.