Xah Lee, 2009-01
This page is a brief, practical, tutorial of JavaScript the language.
To evaluate a piece of js code, you need to call it in a html file and view the file in browser.
Here's how to embed JavaScript into HTML. If you just have few lines of code, do:
<script type="application/javascript"> alert("hi ya!"); </script>
The “type="application/javascript"” is the technically correct way to do it. For compatibility, use “type="text/javascript"”. (see Internet media type, http://tools.ietf.org/html/rfc4329)
If you have a lot code, then put them in a file, and call it like this:
<script type="application/javascript" src="mycode.js"></script>
Alternatively, you can install a command line app SpiderMonkey. Once this is installed, you can run it in a terminal, like this: “js file.js”. Note that SpiderMonkey does not include DOM (Document Object Model) for scripting web pages, but it is convenient if you just want to learn the language.
If you are a emacs user, you can try Steve Yegge's ejacs. It is Ecma-262 compliant JavaScript interpreter written entirely in Emacs Lisp.
To print, use “alert()” or “document.write()”. If you are in SpiderMonkey, you can just use “print()”.
/* this is comment */ // this is comment too. document.write("<p>3<\/p>"); // prints 3 to browser alert("3"); // popup a dialog
/* SpiderMonkey */ print(3); // prints 3.
var s1 = "once upon a time"; var s2 = 'there are meat'; // single quote ok // getting single char s1.charAt(0); // return “o” // getting substring s1.substring(1,3); // return “nc” // string join var s3 = s1 + s2; // return “once upon a timethere are meat”
print (typeof("abc")); // string print (typeof(3)); // number print (typeof(3.5)); // number print (typeof(NaN)); // number print (typeof(false)); // boolean print (typeof(null)); // object print (typeof(undefined)); // undefined
The “null” datatype can be assigned to function or variable to undefine them.
When a variable has not been assigned, it is “undefined”.
In js, there are several builtin datatypes, including: “true”, “false”, and also “null”, “NaN”, “undefined”.
The following are considered false: false, empty string, 0, null, NaN, undefined. Everything else is true.
// the following all return “false” Boolean(false); Boolean(0); Boolean(""); Boolean(null); Boolean(NaN); Boolean(undefined); // the following all return “true” Boolean(true); Boolean(1); Boolean(1.5); Boolean(2);
javascript supports “if”, “if ... else ...”, and also “ ... else if ...”.
if (3 < 4) {print("yes");}; if (3 <= 4) {print("yes");} else {print("no");}
var x = 3; if (x == 1) {print("is 1");} else if (x == 2) {print("is 2");} else if (x == 3) {print("is 3");} else {print("not found");}
for (var i=0; i<10; i++) { print(i); }
var x = 0; while (x != 5) { print(x); x++;} // prints 1 to 4
var x = 0; do {print(x); x++} while (x != 5) // prints 0 to 4
for (var myVal in someObject) { ... myVal ...}
“continue” exit the current iteration in a loop. (that is, start the next iteration at the beginning of loop)
A list structure in js is called a array. Example:
var myA = ["pa", "re", "ci"]; // array has square brackets print(myA);
Example of assiging array items one at a time:
var myA = []; // define a array myA[0] = "one"; // assign values to elements myA[1] = "two"; myA[3] = "more"; // out of bound reference automatically extend the array print("myA is :" + myA); // print array print("length is :" + myA.length); // show length print("myA[3] is :" + myA[3]); // access a element
Array can be nested in any way.
var myA = ["pa", ["deep", [4,5]], 3]; print(myA[1][1][0]); // prints 4
Keyed list (hash, dictionary, associative array) example:
var names = {"mary":19, "jane":20, "john":25}; print(names["mary"]); // 19 print(names.mary); // returns 19. Dot donation also works
Array and hash can be mixed and nested:
var x ={"a":19, "b":20, "c":[3,4]}; print( x["c"][0]); // prints 3 var y = [3,4]; x = {"a":19, "b":20, "c":y}; // eval var inside ok print( x["c"][0] ); // prints 3 // complex nesting and get val ok print( {"a":19, "b":20, "c":[3,4]} ["c"][0] ); // prints 3
Example of defining a function:
function hii(firstName) { return "Dear " + firstName + ",";} print(hii("Vicky"));
If the function does not have a “return” statement, its return value is undefined.
Here's a sample code of creating a object:
var myObj= new Object(); // creating a object myObj.color1="red"; // creating a “property” of color1 myObj.color2="blue"; print(myObj.color1); // prints red
In the above code, myObj is a user created object, and it has color1 as one of its property. It is assigned the value “red”. One can create other properties by simply assiging it a value, such as “myObj.color2="blue"”.
JavaScript's Object property is basically like a keyed list in most languages. (aka: dictionary, hash, associative list) You can also access properties like a list:
var myObj = new Object(); myObj["color1"]="red"; print("Color is: " + myObj["color1"]);
You can define a prototype of a object. That is, a object with predefined “properties” (elements). Example:
// define a object prototype “person” with properties: name, hair, height. function person(a1,a2,a3) { this.name = a1; // creates a property named “name” this.hair = a2; this.height = a3; } // create objects “person” var mary=new person("Mary","blonde", "150"); mary=new person("Mary","blonde", "150"); jane=new person("Jane","brunette", "156"); print("mary.namee is:" + mary.name); // prints mary's name.
References: