JavaScript Notes


JavaScript Notes

There are three ways of using JavaScript in HTML document.


  <!-- import JavaScript in head -->
  <script src="index.js"></script>
  <!-- import JavaScript in body -->
  <script src="index.js"></script>


  <script> // full form: <script type="text/javascript">
    <!-- JavaScript code here -->


    function showAlert()
        alert("Clicked on a button!")
  <!-- display an alert on button click -->
  <input type="button" value="aButton" onclick="alert('Whats up?')" />

  <!-- call another function -->
  <input type="button" value="anotherButton" onclick="showAlert()" />


Variables and Constants

var a = 10;
var b = 20, c = 30;
a = a + 1

// constants:
var DEBUG = 1;

Data Types

var number = 100;
var string1 = 'Single can be wrapped by single quote.'
var string2 = "String can also be wrapped by double quote."
var string3 = "String can have escape value like \" or \'."
if (number < 200) // boolean condition
    document.write("number is less than 200.")
// undefined:
var n;
// null value
var m = null;


Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% remainder
++ add one
minus one
= plain assignment
-= subtraction assignment
+= addition assignment
*= multiplication assignment
/= division assignment


Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to

Logic Operation

Operator Meaning
&& AND
|| OR

Condition Operation

var a = condition ? expression1 : expression2;

Type Conversion

Flow Control


if (condition) {
    // statement

if (condition) {
    // statement1
} else {
    // statement2

if (condition1) {
    // statement1
} else if (condition2) {
    // statement2
} else {
    // statement3


var day = 3;
var week;

switch (day)
    case 1:
        week = "Monday"; break;
    case 2:
        week = "Tuesday"; break;
    case 3:
        week = "Wednesday"; break;
    case 4:
        week = "Thursday"; break;
    case 5:
        week = "Friday"; break;
    case 6:
        week = "Saturday"; break;
        week = "Sunday";


while (condition)
    // statement executed when condition is true
    // statement
} while(condition);
for (initial expression; condition; post-loop expression)
    // ...

// e.g.
for (var i = 0 ; i < 5 ; i++)
    // ...


function name(argument1, argument2, , argumentN)
    // function body
    return value; // return a value if the function does have one
  // function that doesn't return
  function showMessage(msg)
  showMessage("Hi") // direct invocation

  // function that returns
  function addSum(a, b)
      var sum = a + b;
      return sum;
  var n = addSum(1, 2) + 100; // function call as part of expression

<!-- function call as hyperlink -->
<a href="javascript:showMessage('Hello, world!')">Click Me</a>

  <!-- function call as an event -->
  <input type="button" onclick="showMessage('Submitted')" value="Submit" />

String Operation

Please look for more detailed documents on this top, below are just a few operations for string.


To create an array in JavaScript:

var arrayName = new Array(element1, element2, , elementN); // full form
var arrayName = [element1, element2, , elementN]; // short form
var emptyArray = []; // empty array

arrayName[i] = value; // value assignment to index i

Date and Time

Create a new Date object:

var date = new Date();

Please refer to JavaScript documentation for functions of Date, basically it has a list of getXxx and setXxx for retrieving and setting details of the date.


In JavaScript we can use Math object to perform a list of mathematical calculations. It has constants commonly used in Maths like PI, and functions like abs(x), floor(x), ceil(x) and random().


DOM stands for Document Object Model, the document structure is modeled as an object, different parts of the document can be read and manipulated through the concept of “node”, with three commonly used nodes:

<div id="wrapper">text</div>

Element Node

<ul id="list">
  Favourite Fruit:
  <label><input type="radio" name="fruit" value="Apple" />Apple</label>
  <label><input type="radio" name="fruit" value="Orange" />Orange</label>
  <label><input type="radio" name="fruit" value="Banana" />Banana</label>

document.title and document.body

JavaScript provides an easy way to access the title and body of document:

<!DOCTYPE html>
  <meta charset="utf-8" />
    window.onload = function()
        document.title = "Title";
        document.body.innerHTML = "<p>A paragraph of text.</p>";

Create Element

In JavaScript we can dynamically create new elements and modify existings elements, this is called “Dynamic DOM Operation”.

Sample (add a strong text):

window.onload = function()
    var oDiv = document.getElementById("content");
    var oStrong = document.createElement("strong");
    var oText = document.createTextNode("Text");


Another sample, creating an image equivalent to HTML:

<img class="pic" src="images/photo.png" style="border:1px solid silver" />
window.onload = function()
    var oImg = document.createElement("img");
    oImg.className = "pic"; // className is used instead of class because class is a keyword
    oImg.src = "images/photo.png"; = "1px solid silver";

DOM Advanced

HTML Attributes

Access attribute of object via: obj.attr, consider the following HTML code:

<input id="btn" type="button" value="Submit" />

To retrieve the button:

// get the button and assign it `onclick` function
var button = document.getElementById("btn")
button.onclick = function()

To create the button dynamically:

var input = documenmt.createElement("input"); = "submit";
input.type = "button";
input.value = "Submit";

input.onclick = function()

For custom attribute we have to use getAttribute(name) and setAttribute(value, name), consider this code with custom attribute data:

<input id="btn" type="button" value="Insert" data="JavaScript" />

To retrieve data attribute:

var button = document.getElementById("btn");
// is undefined

DOM Traversal


In JavaScript, an event consists of three parts: Subject, Type and Action. Please refer to JavaScript documentation for list of events for different elements.

Event Invocation

Trigger event in script tag:

object.eventName = function()
    // event body


window.onload = function()
    // event body

Trigger event in element:

<input type="button" onclick="showAlert()" value="Alert" />

Event Listener

obj.addEventListener(type, function, false);
obj.removeEventListener(type, function, false);
window.onload = function()
    var button = document.getElementById("btn");
    button.addEventListener("click", function(){
        alert("First Click");
    }, false);
    button.addEventListener("click", function(){
        alert("Second Click");
    }, false);
    button.addEventListener("click", function(){
        alert("Third Click");
    }, false);

event object

An object for event is passed to event function.

Attribute Meaning
type type of event
keyCode code of key stroke
shiftKey if Shift key is pressed
ctrlKey if Ctrl key is pressed
altKey if Alt key is pressed

window object

In JavaScript, every browser window/tab is a window object, each window object has a list of sub-objects and methods. Please refer to JavaScript documentation for detailed explanation of children objects and methods.

Child objects of window:

sub object meaning
document document model of the page
location URL related object
navigator browser related object
history browsing history
screen screen related object

Methods of window:

method meaning
alert() show an alert dialog
confirm() show a confirmation dialog
prompt() show a prompt dialog
open() open a new window
close() close the window
setTimeout() turn on “once off” timer
clearTimeout() turn off “once off” timer
setInterval() turn on repeating timer
clearInterval() turn off repeating time