JavaScript Tutorial by Example

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

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

string.slice(index 1, index 2)

// 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

Join String

String join. Use +.

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

String Methods

JavaScript String Methods

JavaScript string is 16 bits byte sequence. 〔➤ JavaScript String is 16 Bits Byte Sequence

(String is not mutable. Any change to a string returns a new string.)

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

Assignment Operators

Assignment returns a value.

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

JavaScript also supports {x++,++x,x--,--x,X += y, …}. See: JavaScript Operators.

JavaScript Operators

List of JavaScript operators: JavaScript Operators

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: Convert Between String & Number

Variables

Variable Declaration

Use var name; to declare a variable.

// declare variable
var x;
var y;

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

// 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;
// declare multiple variables, some with value
var a, b = 2, c;

console.log(a); // undefined
console.log(b); // 2
console.log(c); // undefined

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

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

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

Local Variable

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).

Importance of JavaScript Objects

Note: it's important to know, that these are the only datatypes in JavaScript. String, Number, Boolean, are easily understood. null, underfine, are also easily understood. That left with “object”. Object includes Arrays and Functions. Object is the most important thing in JavaScript. It is just key/value pairs (called “property”), with inheritance feature. Key is string (string datatype), and value can be any object, including function.

This “hash table + inheritance + function as property value” is the heart of JavaScript. It is very simple, and vary powerful & flexible.

For a detailed account of JavaScript object system, see: Understanding JavaScript Object System

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 「===」

Note: == does automatic type conversion. === does not.

You should 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」

if/then/else Expression

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 Switch ≈ Goto

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

A basic way to go thru every element of array is using for loop.

// loop thru array
var aa = [3,7,4];

for (var i = 0; i < aa.length; i++) {
    console.log( aa[i]);
}

Apply a function to array elements:

// map a function to array
var ar = [1,2,3];
var ar2 = ar.map( function (x) { return x+1; } );

console.log(ar2); // [2,3,4]

Array Methods

JavaScript Array Methods

Array is Also a Object

Note: keep in mind, in JavaScript, array is also a object. It's a special object. The array index are just property names. 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

You should not to use array in this weird way. 〔➤ What's Object in JavaScript?

Key/Value Pairs (JavaScript Object)

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

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

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

// creating a object
var nn = {"mary":19, "jane":20, "john":25};

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

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

Change a property's value:

var obj =  {"1": "a", "2": "c"};

obj["2"] = "b";

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

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 pairs is called properties (name/value).

Property names are string type (they are automatically converted to string if you didn't use string syntax.). 〔➤ JavaScript: Property Names Are Strings

Property values can be any type, including any object. (function and array are both objects)

When you create hash table {…}, you are creating a JavaScript Object. 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.

One simple way to begin understanding JavaScript's object is to think of it as a specialized hash table, with inheritance. 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 property comes before inherited property.

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' ]

Nested Array & Key/Value

Because object's property's value can be any object datatype, so you can have any nested array and hash table. (because both array and object are objects)

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 JavaScript object. This is a JSON format. JSON is essentially a JavaScript object in string format.

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

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

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

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.

JavaScript is a functional language. The definition of a function returns a value of type “function” that represent the function. You can pass a function as argument into a function. Function can return a function. You can also have nested function. Understanding how functions can be passed around is essential, because it is heavily used in any non-trivial code. For detail, see:

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).

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

Each object automatically inherit parent object's properties.

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:

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

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

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 that has a value of function.

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