JavaScript Tutorial by Example

, , …,

This page will quickly get you started on JavaScript the language. You need to have basic understanding of the language before you can script the DOM/web.

Running JavaScript

To evaluate a piece of JavaScript 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!");
</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>

Use Browser's Web Developer Console

A fast way to try JavaScript code is to use browser's console.

There, type 1+1, press Enter ↵, then it'll show 2.

Using node.js

Another good way to run JavaScript code is node.js. With node.js, you can run JavaScript like shell scripts in terminal.

On Linux, install by sudo apt-get install nodejs. Or get it at http://nodejs.org/.

You can run it interactively. Type node to start the interactive prompt. Type 【Ctrl+d】 to exit.

You can also run it as shell script. Save a JavaScript code in a file ⁖ “myscript.js”. Then, you can run the script in shell like this: node myscript.js. (For emacs users, get this tool: Emacs Lisp: a Command to Execute/Compile Current File)

Printing

To print, use alert or console.log.

/* this is comment */

// this is comment too.

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

console.log("yes"); // print to browser's console

Semicolon can be omitted most of the time, but you should always add a semicolon, because if you don't, the compiler sometimes will get it wrong, resulting hard-to-find bugs.

String

Quoting string, use double quote or single quote. There's basically no difference between the two.

var s1 = "jane's cat";  // double quote
var s2 = 'jane\'s cat'; // single quote, with escape

Use \n for newline.

// use \n for newline
var ss = "cat\ndog";

console.log(ss); // prints 2 lines

Literal newline in string is not allowed. Use backslash to continue a line.

// illegal syntax. Literal newline is not allowed
var s = "a
b";

// use backslash to continue a line
var s = "c\
d";

console.log(s); // prints cd

String length.

"abc".length; // ⇒ 3

Note: no parenthesis after “length”, because it's a property, not method.

Substring, use string.slice(index 1, index 2). Index start at 0. Think of the index as between elements, not “on” the element. Argument can be negative, when negative, it counts from right.

// get substring example using .slice()

var ss = "01234";

console.log(ss.slice(1));       // → 1234

console.log(ss.slice(1,3));     // → 12

console.log(ss.slice(1,-1));    // → 123

console.log(ss.slice(1,0));     // → "" empty

console.log(ss.slice(-3,-1));   // → 23

String join. Use +.

// string join
console.log( "tiger" + "rabbit"); // tigerrabbit

There's no “interpolation” to embed a variable inside a string. Just use "some" + varname + "apples". There's no “printf” neither.

More at JavaScript String Methods.

Arithmetic Operators

Basic arithmetic.

3 + 4;      // 7
3 - 4;      // -1
3 * 4;      // 12
3 / 4;      // 0.75

10 % 3;     // 1 → remainder
-(3+4);     // -7 → negation

Math.pow(2,3);    // 8 → exponential
Math.pow(2,1/2);  // 1.4142135623730951 → square root

Increment & Decrement assignment.

// ++x is same as x = x + 1. It returns the new value of x
var x = 3;
console.log(++x);               // 4
console.log(x);                 // 4

// y++ is same as y = y + 1, but returns the old value of y
var y = 3;
console.log(y++);               // 3
console.log(y);                 // 4

// you can also use --x and x--

Assignment returns a value.

// assignment returns a value
var z = 5; // returns 5
console.log((z = 5)*2); // 10

Number

JavaScript doesn't have int/float distinction. They are just type “number”. It's similar to other language's “float”.

console.log(typeof 3); // prints number
console.log(typeof 3.028487); // prints number

You can use {Math.ceiling(), Math.floor(), Math.round()} on number to get integer.

var x = 3.5847;

var f = Math.floor( x );
var c = Math.ceil( x );

console.log(f); // prints 3
console.log(c); // prints 4

console.log(Math.round( 3.54 )); // prints 4
console.log(Math.round( 3.55 )); // prints 4

String/Number Conversion

JavaScript automatically convert number to string. Adding a string to number results string.

var x = 3 + "4";

console.log(x); // 34

console.log(typeof x); // string

Convert String to Number

Use parseInt(string,radix) or parseFloat(string,radix) to convert a string to number.

// string to number
parseInt("324");  // prints 324

// input starting with “0x” are considered as hexadecimal
parseInt("0xff");  // prints 255

// binary, using explicit radix
parseInt("10",2);  // prints 2

Convert Number to String

Use (number).toString(radix) method to convert a number to string.

// number to string
console.log(
    (30).toString()
);                              // 30

// 3 to binary
console.log(
    (3).toString(2)
);                              // 11

// 16 to hex
console.log(
    (16).toString(16)
);                              // 10

var x = 4;
console.log(
    x.toString()
);                              // 4

Note: there's no “format” or “sprint” function in JavaScript.

Variables

Variable Declaration

Use var name; to declare a variable.

Multiple variables can be declared on the same line, separated by comma var name1, name2, name3 …;

// declare variable, use 「var」
var x;
var y;

// multiple variables can be declared on the same line, separated by comma
var a, b, c;

Multiple variables can be declared and assigned at the same time.

// declare variable and assign
var x = 4;

// declare variable and assign multiple variables
var a = 1, b = 2, c = 3;

When a variable is declared but not assigned, the default value is undefined:

var x;
console.log(x); // prints 「undefined」

When a variable is assigned but not declared, it has global scope. Undeclared variable are called “implied global variable”. It is not technically the same as a variable declared with var outside any nesting, because declared global variable are actually a property of the global object. (don't worry about this. Just ALWAYS declare your variables.)

When a variable is not declared nor assigned, and you try to access it, you get ReferenceError.

var x;
console.log(x); // prints 「undefined」
console.log(y); // ReferenceError: y is not defined

You should ALWAYS declare variables. It is harmless if you declared a variable redundantly multiple times.

var x;
console.log(x);                 // undefined
var x;
console.log(x);                 // undefined

var y = 3;
console.log(y);                 // 3
var y;
console.log(y);                 // 3

Variable Assignment

Variable assignment returns a value.

// variable assignment returns a value
var xx;
console.log(xx = 3);            // 3

So, variable assignment can be chained.

var xx;
var yy;

console.log(xx = yy = 3);       // 3
console.log(xx);                // 3
console.log(yy);                // 3

Variable Scope

Variable declared inside a function is local to the function. This is the only way to create a scope. Variable inside a curly bracket does not create a scope.

var n = 2;

function f ()  {
    var n = 3;
    {
        var n = 4;
    }
    console.log(n);
};

f(); // prints 4

When variable is declared, it is a variable in the current scope (⁖ local to the function, or local to the inner-most nested function.). If not declared, JavaScript will search the variable in outer scopes, until it reaches the global space.

Datatypes

Variable doesn't have type. Value has type.

JavaScript has these types:

Use typeof value to check a value's type.

typeof "abc"; // ⇒ string

typeof 3;     // ⇒ number
typeof 3.5;   // ⇒ number
typeof NaN;   // ⇒ number
typeof Infinity;   // ⇒ number

typeof false; // ⇒ boolean
typeof null;  // ⇒ object. (this is Historical baggage. Should be “null”)

typeof undefined; // ⇒ undefined
typeof {}; // ⇒ object

// “function” is a special object
typeof function () {return 3;}; // ⇒ function

// “array” is a special object
typeof [3,4]; // ⇒ object

Note: “typeof” is a technically a operator, not a function or method. This means, you can write typeof 3 instead of typeof(3).

Primitive Values Are Converted to Object Temporarily

String or number are not objects, why do they have methods?

When using a property/method of a number (or string), the primitive value is converted to object temporarily on the fly. That's why string primitive has methods.

Here's how you can create number or string objects yourself. (but they are rarely needed.)

new String("char sequence") → convert a string primitive to string object.

new Number(number form) → convert a number primitive to number object.

new Boolean(true or false) → convert a boolean primitive to boolean object.

{null, undefined} don't have wrapper objects.

var xx = new String("abc") ;

console.log(xx);  // { '0': 'a', '1': 'b', '2': 'c' }

console.log(typeof xx); // object

True & False

The following are false, everything else is true.

// the following all eval to false. Everything else is true.
console.log( Boolean(false) );  // false
console.log( Boolean(0) );      // false
console.log( Boolean(0.0) );    // false
console.log( Boolean("") );     // false
console.log( Boolean(null) );   // false
console.log( Boolean(undefined) ); // false
console.log( Boolean(NaN) );    // false
console.log( Boolean(1) );        // true
console.log( Boolean(-1) );       // true
console.log( Boolean(Infinity) ); // true
console.log( Boolean({}) );       // true  empty object

Logic Operators

true && true // ⇒  true. The “and” operator

true || true // ⇒  true. The “or” operator

!true // ⇒ false. The “negation” operator

Comparison Operators

3 < 4;         // ⇒ true
3 > 4;         // ⇒  false

3 == 3;        // ⇒ true.
3 == "3";      // ⇒ true.  note: 「==」 does automatic type conversion
3 === "3";     // ⇒ false.  True if both sides are same type and equal

3 != 4;        // ⇒ true. The 「!=」 is the negation of 「==」
3 !== 4;       // ⇒ true. The 「!==」 is the negation of 「===」

I recommend that you always use === instead of ==. When testing for boolean, always be as explicit as possible. Don't rely on what the language considers as true.

If Then Else

Simple “if” statement.

if (3 < 4) {console.log("yes");};

“if else” statement.

if (3 <= 4) {console.log("yes");}
else {console.log("no");}

“else if” chain.

var x = 3;
if (x == 1) {console.log("is 1");}
else if (x == 2) {console.log("is 2");}
else if (x == 3) {console.log("is 3");}
else {console.log("not found");}

Curly brackets {} is optional if there's just one statement, but semicolon is still required.

if (3 > 4) console.log("yes"); else console.log("no"); // prints 「no」

JavaScript also supports if/then/else EXPRESSION. (aka “ternary expression”)

test ? expr1 : expr2 → if test eval to true, then eval expression expr1, else expr2.

var y = (4 > 5) ? "yes" : "no";

console.log(y); // prints "no"

Switch

Switch statement.

// example of switch statement.
var x = "a"; // change the value to test

switch(x) {
    case "w":
        console.log("is w");
        break; // without “break”, it'll continue to run rest without testing
    case "a":
        console.log("is a");
        break;
    case 3:
        console.log("is 3");
        break;
    default:
        console.log("none of the above");
}

switch uses === for comparison.

JavaScript's “switch” does fall-through. It'll jump to a matching point and run all of the rest of case code without testing. Think of JavaScript switch as goto.

// JavaScript's “switch” jumps to a point and continue from there.
var x = "w";

switch(x) {
    case "w":
        x += "1";
    case 32:
        x += "2";
    default:
        x += "3";
}
console.log(x); // w123

Iteration; Loop

“for” loop.

for (var i=0; i < 9; i++) { console.log(i); }

“while” loop.

var x = 0;
while (x != 5) { console.log(x); x++;} // prints 0 to 4

“do…while” loop.

var x = 0;
do { console.log(x); x++} while (x != 5) // prints 0 to 4

“continue” and “break”

for (var i=0; i <= 5; i++) {
    if (i==3) {continue;}       // skip 3
    console.log(i);
}                               // prints 0 to 5, but not 3
for (var i=0; i < 5; i++) {
    console.log(i);
    if (i===3) {break;}
}                               // prints 0 to 3

Array

Creating a array. [element 0, element 1, element 2, …]

var aa = ["one", "two", 3];
console.log(aa); // [ 'one', 'two', 3 ]

Example of assigning array items one at a time:

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

console.log(aa);           // [ 'zero', 'one', , 'more' ]

// value of aa[2] is “undefined”

array.length returns the number of elements in array.

var aa = [7, 8, 2];  // define a array

console.log(aa.length); // 3

Access a element. array[index]

var aa = [2, 4, 1];

// access a element
console.log(aa[0]);     // 2

Modify a element.

var aa = [2, 4, 1];

aa[0]= "no";

console.log(aa);     // [ 'no', 4, 1 ]

Nested Array

Array can be nested.

var aa = ["pa", ["deep", [4,5]], 3];
console.log(aa[1][1][0]); // prints 4

Loop thru Array

Most basic way of going thru array.

// loop thru arry
aa = [3,7,4];
for (var i in aa) {
    console.log(aa[i]);
}

Array Methods

JavaScript has many methods for array, such as {map, filter, reduce, sort, push, pop, …}. See: JavaScript Array Methods.

Key/Value Pairs ≈ Object

A set of key/value pairs (aka hash, dictionary, associative array), is technically a Object data type. Each key/value pair is called the object's property. Example:

var nn = {"mary":19, "jane":20, "john":25};

To access elements, use brackets array["property name"] or dot notation array.property name.

// creating a hash table (technically, creating a JavaScript Object)
var nn = {"mary":19, "jane":20, "john":25};

// Accessing elements.
nn["mary"]              // ⇒ 19, bracket notation
nn.mary                 // ⇒ 19, Dot notation also works

〔☛ JavaScript: Dot Notation vs Bracket Notation for Accessing Properties

To delete a property, use the operator delete.

var nn = {"mary":19, "jane":20, "john":25};

delete nn["mary"]  // delete a property

console.log(nn);   // { jane: 20, john: 25 }

Note: in JavaScript, key/value pairs such as {"mary":19, "john":25} is a JavaScript object. JavaScript object IS key/value pairs, and the syntax {…} is the most common way to create a object. key/value is called properties (name/value).

Property names are string type (they are automatically converted to string if not.).

When you use a hash table {…}, you are basically using object as data structure. It is the most common use of JavaScript object. In JavaScript, key/value pairs IS object. This concept of “object” is very different from {Java, Python, Ruby, PHP}'s object oriented programing model, but the sooner you get used to it, the faster you'll become JavaScript expert. 〔☛ Understanding JavaScript Objects

Loop-Thru Object's Properties

To loop thru a object's properties, use for (var x in object) {…}. The x will be the value of each property in the loop body.

var nn = {"a":19, "c":20, "b":25};

for (var x in nn) {
console.log(x);     // prints each key
console.log(nn[x]); // prints each value
}

Note: JavaScript object has inherihance. The for (var x in obj) {…} will include parent or ancestor's enumerable properties. But, if you just created your object as in var myobj = {…}, you don't need to worry about this, because, newly created object using {…} by default has parent Object.prototype, and Object.prototype does not have enumerable properties. 〔☛ Understanding JavaScript Objects

Note: order is not guaranteed, but usually, older property comes first, and object's own properties comes before inherited properties.

Note: the for (var x in object) {…} will only go thru properties whose attribute “enumerable” is true. 〔☛ JavaScript: Property, Prototype Chain, Enumerable: Accessing & Listing Properties

Get All Keys

Use the Object.keys(obj) method.

var j = {"a":19, "c":20, "b":25};

console.log( Object.keys(j) );     // prints [ 'a', 'c', 'b' ]

Mixed Nested Array & Key/Value

Array and hash can be nested and mixed arbitrarily.

Key/Value, with one value being array:

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

Example of key/value with one value being a variable that eval to array:

var y = [3,4];
var x = {"a":19, "b":20, "c":y}; // the y is array
console.log( x["c"][0] ); // prints 3

The syntax for accessing elements can be chained.

// syntax for accesing array/hash can be chained
console.log(
 {"a":19, "b":20, "c":[3,4]}["c"][0]
);
 // prints 3

Following is another example of data structure. This is a typical JSON format. The popular format JSON, is a JavaScript hash table whose elements are arbitrarily nested hash table or arrays.

var myStructure = {
  name: {
    first: "Mary",
    last: "Smith"
  },
  age: 19,
  hobbies: [ "shopping", "dancing" ]
};

Array is Also a Object

Note: technically, in JavaScript, array is also a object. It's a special object. The array index are just property names (and they are also string type, automatically converted). The .length property is a magic property that automatically gets updated. Because, array is a object, that means you can add arbitrary properties like any other object. Example:

// JavaScript array is technically a JavaScript object
// 「for … in ‹array›」 loop goes thru array properties

aa = [3,7];
aa["h"] = "whoa!";
aa["x"] = "huh?";

for (var i in aa) { console.log(aa[i]); }

// prints
// 3
// 7
// whoa!
// huh?

console.log(aa);                // [ 3, 7, h: 'whoa!', x: 'huh?' ]

console.log(aa.length);         // 2

I recommend not to use array in this weird way. 〔☛ What's Object in JavaScript?

Regex (Regular Expressions for String Pattern Matching)

JavaScript's regex syntax is a subset of Perl's. If you've used any of Python or Ruby's regex, the regex syntax is basically the same except some rarely used advanced features. 〔☛ Python Regex Syntax

JavaScript regex uses slash as delimiter, like this: /…/, which creates a regex object. If you use string "…", it'll be automatically converted to a regex object EXCEPT with the string method string.replace(…). When the string.replace(…) gets a string instead of regex object, it'll do literal replacement (no regex). (detail at JavaScript Regex Tutorial.)

Here's a basics example.

// check if a pattern matches

var xx = "jane@example.com";

console.log(xx.search(/@.+com/)); // 4

console.log(xx.search(/z/)); // -1  not found

Here's JavaScript string's regex methods.

syntaxdescription
s.search(/…/)Return the index of first char of matched string. If no match, returns -1.
s.replace(/…/,replace)Return a new string. The replace can be a string or function. If function, it'll receive args: matched string, match group 1, match group 2, …. If no match, the original string is returned.
s.replace("…",replace)Literal string replacement. (no regex)
s.match(/…/)Return array of captured patterns. Index 0 is the whole matched string, index 1 is first captured pattern, …. Or, return null if no match.
s.match(/…/g)Return a array of all occurrences of matched string (note the g flag for global), or null if no match.

Typical use of regex in “if” statement.

var xlink = "http://google.com/";

var search_result = xlink.search(/oo/);

if ( search_result !== -1) {
    console.log("found match");
    console.log(search_result); // 8 ← the index of match
} else {
    console.log("not found");
}

Regex replacement.

// example of regex replace
// add a alt attribute to a HTML image tag.

var x1 = '<img src="cat.jpg">';

var x2 = x1.replace(/<img src="([-_\w]+)\.jpg">/, '<img src="$1.jpg" alt="$1">');

console.log(x2); // prints <img src="cat.jpg" alt="cat">

Example of match without global flag. Get all captured patterns.

// example of regex “match” method, capture groups
// capture the attribute values in a image tag
var xx = '<img class="pict" src="cat.jpg" alt="my cat" width="600" height="400">';

var result = xx.match(/<img class="([^"]+)" src="([^"]+)" alt="([^"]+)" width="([^"]+)" height="([^"]+)">/);

console.log(result[0]); // <img class="i" src="cat.jpg" alt="my cat" width="600" height="400">
console.log(result[1]); // pict
console.log(result[2]); // cat.jpg
console.log(result[3]); // my cat
console.log(result[4]); // 600
console.log(result[5]); // 400

For detail, see: JavaScript Regex Tutorial.

Define Function

Example of defining a function:

function ff(x, y) { return x + y;}
console.log(ff(3, 4)); // 7

If the function does not have a return statement, it returns undefined.

Function Parameters/Arguments

To define function with unspecified number of arguments, use predefined variable name arguments. It is a predefined array-like object inside the function.

function ff() {
    return arguments[0]; // returns the first argument
}

console.log(ff(3,4,5)); // prints 3

JavaScript is a functional language. The definition of a function returns a value. You can pass a function as argument into another function. You can also have nested function. Understanding how functions can be passed around is important, because it is used frequently. For detail, see: Functional Programing in JavaScript.

Objects

JavaScript's concept of object is a set of key/value pairs (aka hash table, dictionary, associative array.). It is unordered and dynamic (that is, values can be changed anytime, and items can be added or removed). This key/value pairs have inheritance, like other language's objects, but the model is completely different Java/C++ classes.

Each key/value pair of a object is called property (property name, property value). The property name is a string type, property value can be any type, including function and object.

Technically, a object in JavaScript is any value that is not a {string, number (NaN, Infinity) , true, false, null, undefined}. Array, Function, Date, Regex, and others are special objects. (and, yes, they are all just key/value pairs, but with special behavior or features.) For detail, see: What's Object in JavaScript?.

The literal expression to create a object is the curly bracket {}. Example:

// creating a object.
var bb = {};
console.log(typeof bb);         // → 「"object"」

// creating a object with some properties
var cc = {"p1":1, "p2":2};
console.log(typeof cc);         // → 「"object"」
console.log(cc);                // → { p1: 1, p2: 2 }

Creating a empty object, then assign some properties:

oj = {};     // creating a object
oj.c1= 3;    // creating a “property” c1 for object oj
oj.c2= 4;

console.log(oj.c1); // prints 3

Those {c1, c2} are called properties of the object.

There are 2 syntax for accessing properties:

oj = {"p1":1};                  // creating a object with property p1
oj.p2 = 2;                      // creating a property p2
oj["p3"] = 3;                   // creating a property p3

console.log(oj);                // { p1: 1, p2: 2, p3: 3 }
console.log(oj.p1);             // 1
console.log(oj["p2"]);          // 2
console.log(oj["p3"]);          // 3

For detail, see: Javascript: Dot Notation vs Bracket Notation.

Define Method

A method is just a property whose value is a function. Like this:

j = {};                            // create a object
j.m = function (x) {return x + 1;} // create a method named m

// calling the method
var y = j.m(3);

console.log(y);                 // prints 4

When a function is called as a method, there's a special behavior. Any this keyword inside the function definition is evaluated to the object the method is attached to.

// create a object, with one property p1
var oo = {"p1":3};

// set property p2 to a function, which simply return 「this」
oo.p2 = function () { return this; };

// show oo
console.log( oo )               // { p1: 3, p2: [Function] }

console.log( oo === oo.p2() )   // true

// returns true because p2 is a function that returns 「this」, which is oo

JavaScript object model is very different from Java or Python. In typical object oriented languages, you have class & object. Class is like a factory, and it creates objects. JavaScript's OO model is nothing like that. Instead, you have just objects, which is basically a hash table, and object inherits its parent's properties. For detail, See:

blog comments powered by Disqus