Javascript Basics Tutorial by Examples

Advertise Here

, 2009-01, …, 2011-10-09

This page is a brief, practical, tutorial of javascript language.

Running Javascript

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>
alert("hi ya!");
</script>

If you have more than a few lines of code, put them in a file, and call it like this:

<script src="mycode.js"></script>

Printing

To print, use alert or document.write.

/* this is comment */

// this is comment too.

document.write("<p>3<\/p>"); // prints 3 to browser

alert("3"); // popup a dialog

String

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”

Global and Local Variables

Variables should be declared using “var”. When declared with var, it is a variable in the current scope (e.g local to the function). If not declared, js will search the variable in outter scopes, until it reaches the global space.

Variables declared with “var” can be deleted using delete myvar;, but variable not declared with “var” cannot be deleted.

So, you should always declare variable with “var”, even for global variables.

Datatypes

typeof("abc"); // string

typeof(3);     // number
typeof(3.5);   // number
typeof(NaN);   // number

typeof(false); // boolean

typeof(null);  // object
typeof(undefined); // undefined

The null datatype is literal. You can set a variable or function's value to null to undefine them. This is the only purpose of “null”.

When a variable has not been assigned, its value is undefined. It is also a literal that represent the undefined datatype.

“NaN” means Not A Number. It's typically the result of divide by zero, overflow, etc.

True and False

The following are considered false, everything else is true.

// the following all return “false”. Everything else is true.
Boolean(false);
Boolean(0);
Boolean("");
Boolean(null);
Boolean(NaN);
Boolean(undefined);

If Then Else

if (3 < 4) {alert("yes");};
if (3 <= 4) {alert("yes");} else {alert("no");}
var x = 3;
if (x == 1) {alert("is 1");}
else if (x == 2) {alert("is 2");}
else if (x == 3) {alert("is 3");}
else {alert("not found");}

Iteration

for (var i=0; i < 9; i++) { document.write(i); }
var x = 0;
while (x != 5) { document.write(x); x++;} // prints 0 to 4
var x = 0;
do { document.write(x); x++} while (x != 5) // prints 0 to 4
for (var myVal in someObject) { … myVal …}

“continue” and “break”

“continue” exit the current iteration in a loop. “break” exits the loop completely.

for (var i=0; i < 9; i++) { 
    document.write("<p>"); 
    if (i==5) {continue;}
    if (i==8) {break;}
    document.write(i); 
    document.write("</p>"); 
}

List structure

List in js is called array. Example:

var myA = ["pa", "re", "ci"];
document.write(myA);

Example of assiging array items one at a time:

var myA = [];  // define a array
myA[0] = "zero"; // assign a value to a element
myA[1] = "one";
myA[3] = "more"; // non-existent element automatically extend the array

document.write("<pre>");
document.write("myA is:" + myA + "\n");           // prints “myA is:zero,one,,more”
document.write("length is:" + myA.length + "\n"); // show length
document.write("myA[3] is:" + myA[3] + "\n");     // access a element
document.write("</pre>");

Nested Array

Array can be nested.

var myA = ["pa", ["deep", [4,5]], 3];
document.write(myA[1][1][0]); // prints 4

Key/Value Pairs

Keyed list (aka hash, dictionary, associative array, associative list) example:

var names = {"mary":19, "jane":20, "john":25};
document.write(names["mary"]); // 19
document.write(names.mary); // Dot notation also works

Mixed Nested Array and Hash

Array and hash can be mixed and nested:

var x ={"a":19, "b":20, "c":[3,4]};
document.write( x["c"][0]); // prints 3

var y = [3,4];
x = {"a":19, "b":20, "c":y}; // eval var inside ok
document.write( x["c"][0] ); // prints 3

// complex nesting and get val ok
document.write( {"a":19, "b":20, "c":[3,4]} ["c"][0] ); // prints 3

Defining A Function

Example of defining a function:

function ff(nn) { return nn+1;}
alert(ff(3)); // 4

If the function does not have a “return” statement, its returns the builtin value “undefined”.

Objects

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";

document.write(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";
document.write("Color is: " + myObj["color1"]); // prints “Color is: red”

Creating a Object Prototype

You can define 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 several “person” objects
var mary = new person("Mary", "blonde", "150");
mary = new person("Mary", "blonde", "150");
jane = new person("Jane", "brunette", "156");
document.write("mary.namee is: " + mary.name); // prints “mary.namee is: Mary”
blog comments powered by Disqus