MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaLang DesignEmacsUnicode ♥

JavaScript Basics 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 is to use 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, see: 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

JavaScript's syntax is similar to C or Java.

Semicolon can be omitted most of the time, but you should always add a semicolon, because there are complications.

String

Quoting string.

var s1 = "cat"; // double quote
var s2 = 'cat'; // single quote ok

There's no difference between the two, except that if you use double quote, then you need to escape any double quote inside. Same for single quote.

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

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.

"123".length; // ⇒ 3

// Note: no paren after “length”, because it's a property, not method/function

Substring.

var ss = "abcd";

// get a character
console.log(ss.charAt(0));  // prints t

// get substring.
// substring(‹fromIndex›), to the end of string
console.log(ss.substring(1));  // prints bcd

// substring(‹fromIndex›, ‹toIndex›)
// but not including the end
console.log(ss.substring(1,3));  // prints bc

String join. Use +.

var s1 = "tiger";
var s2 = "rabbit";

// string join
console.log(s1 + s2); // tigerrabbit

Arithmetic Operators

basic arithmetic.

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

10 % 3; // 1 remainder
-3;   // -3 regation

Increment/Decrement assignment.

// 「++x」 is same as 「x = x + 1」, but returns the new value of x
var x = 3;
console.log(++x) // returns 4
console.log(x); // prints 4

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

// similarly for 「++x」 and 「--x」

Assignment returns a value.

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

Adding a number and string results string.

var x = 3 + "4";

console.log(x); // prints "34"

console.log(typeof(x)); // prints string

Number (not int/float)

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

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

You can ceiling/floor/round a real number to 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

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

// string to number
console.log(parseInt("324"));  // prints 324

// input starting with “0x” are considered hex automatically
console.log(parseInt("0xff"));  // prints 255

// explicit radix
console.log(parseInt("ff",16));  // prints 255

// binary
console.log(parseInt("10",2));  // prints 2

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

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

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

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

Global & Local Variables

Variables should be declared using “var”. When declared with var, it is a variable in the current scope (⁖ local to the function). If not declared, JavaScript will search the variable in outer 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.

Variable Scope

Variable inside a function is local to the function. However, variable inside a curly bracket does not create extra scope.

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

f(); // prints 4

However, you can emulate block scope. See: JavaScript Variable Scope: Function Level vs Block Level.

Datatypes

Variable doesn't have type. Value has type. JavaScript has these types:

Call typeof() 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({}); // ⇒ object

// quirk. When the object is callable, typeof returns “function”
typeof(function () {return 3;}); // ⇒ function

// Historical baggage. Should be “array”
typeof([3,4]); // ⇒ object
// Historical baggage. Should be “null”
typeof(null);  // ⇒ object

typeof(undefined); // ⇒ undefined

The null is the only value of the “null” datatype. 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 (Not A Number) and Infinity are special values. It's typically the result of divide by zero, overflow, etc.

True & 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);

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

It's recommended 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

if (3 < 4) {console.log("yes");};
if (3 <= 4) {console.log("yes");}
else {console.log("no");}
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");}

JavaScript also supports if/then/else EXPRESSION.

var x = 4;

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

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

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

JavaScript's “switch” does fallthrough. 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”

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

//prints 0 to 7
for (var i=0; i < 9; i++) {
    if (i==5) {continue;}
    if (i==8) {break;}
    console.log(i);
}

Array

Example:

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”

length.

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

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

Access a element.

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

Array Methods

Those with a star ★ modifies the variable.

CodePurpose
‹array›.pop()remove and returns the last item. ★
‹array›.push(‹new1›, ‹new2›, …]adds one or more items to the end. ★
‹array›.shift()remove and return the first item. ★
‹array›.unshift(‹new›)prepend to the beginning. ★
CodePurpose
‹array›.sort()Sorts. ★
‹array›.sort(‹comparison function›) sort with ‹comparison function›. ★
‹array›.reverse()
CodePurpose
‹array›.concat(‹new1›, ‹new2›, …])add items at end.
‹array›.slice(‹start›, ‹end›)Return subarray.
‹array›.splice(‹start›, ‹delete count›, ‹new new1›, ‹new new2›, …])replace subarray. ★
CodePurpose
‹array›.toString()
‹array›.join(‹sep›) convert to string

Here's code for testing.

var a = [6,3,2,5];
var b = a.sort();

console.log(a);
console.log(b);

Loop thru Array

Most basic way of going thru array.

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

Here's functional programing operations on array.

CodePurpose
‹array›.map(‹f(i)›)apply ‹f› to every element. Returns a new array.
‹array›.filter(‹f(i)›)returns a new array, with only elements that if f(i) is true.
CodePurpose
‹array›.forEach(‹f(i)›)apply ‹f› to each element. Return undefined
‹array›.every(‹f(i)›)Return true if every ‹f(i)› is true.
‹array›.some(‹f(i)›)Return true if one ‹f(i)› is true.
‹array›.reduce(‹f(x,y)›)Accumulatively Apply ‹f› to neighbor elements (from left to right), returns a single value.
‹array›.reduceRight(‹f›)like reduce, but from right to left.

Example:

var a = [7,3,4];

b = a.map( function (x) {return x + 1} );

console.log(a); // prints [ 7, 3, 4 ]
console.log(b); // prints [ 8, 4, 5 ]

Key/Value Pairs

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

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

Accessing elements. Can use brackets or dot notation.

console.log(nn["mary"]); // 19
console.log(nn.mary); // Dot notation also works

Loop-Thru Key/Value Pairs

Using for loop.

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
}

Using the “Object.keys()” method.

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

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

Mixed Nested Array & Key/Value

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

Another example of data structure.

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

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 the builtin value undefined.

To define function with many arguments, use the special variable arguments. It is a predefined array 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 in JavaScript is critical, because it is often used. For detail, see: Functional Programing in JavaScript.

Objects

Most things in JavaScript are objects. Example:

var a = {};     // creating a object. literal syntax

console.log(typeof(a)); // prints 「object」
console.log(typeof(b)); // prints 「object」

Creating a object and give it 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. JavaScript's “Properties” are just elements of the object. JavaScript's Object is basically like a keyed list in most languages. (aka: dictionary, hash, associative array)

Accessing properties is either done with dot notation ‹obj›.‹name› or brackets, like this:

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

console.log(oj["c1"]); // prints 3

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

Function Object with Properties

function f(x, y)
{
    // define properties
    this.a = x;
    this.b = y;

    // define a method
    this.c = function () { return this.a + this.b;};

}

// create a new object of f
var g = new f(3, 4);

// access the property
console.log( g.a ) // 3

// call a method
console.log( g.c() ) // 7
blog comments powered by Disqus