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

Firefox web dev tool 2014-08-28
Firefox web dev tool

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

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, …}.

〔➤ 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

JavaScript Tutorial: Variable, Local Variable

Data Types

JavaScript Data Types

True & False

JavaScript: What's True or False?

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.

Branch Control: If Then Else, Switch

JavaScript Tutorial: Branch Control

Iteration; Loop

JavaScript Tutorial: Loop/Iteration

Array

JavaScript Tutorial: Array Basics

JavaScript: Understanding JavaScript Array

JavaScript Array Methods

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:

JavaScript Object

JavaScript Tutorial: Object Basics

Understanding JavaScript Object System

blog comments powered by Disqus