JSON.stringify(myObj, null, 4)

if(typeof myObj== "undefined" )
if( myObj ) === '[object Array]' ) {
    // alert( 'Array!' );

string is started and stopped with either single or double quotes.

Javascript & HTML

As Separate File

Separate JavaScript codes in a file named xxx.js . write your funtions or codes there, no tag required.
<script type="text/javascript" language="JavaScript" src="ee.js"></script>
<noscript> tag is used to define an alternate text if a script is NOT executed.


JavaScripts in the BODY section will be executed WHILE the page loads.
JavaScripts in the HEAD section will be executed when CALLED.


<script type="text/javascript">
<!--                                            To prevent the browsers that can not execute JavaScript from displaying the JavaScript codes, we should embed JavaScript codes in HTML comment tag <!-- -->
document.write("Hello World!");
//-->                                            The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.


To have more control over the execution of JavaScript codes, we make JavaScript methods in the <head> </head>

<script type="text/javascript">
function message()
alert("This alert box was called with the onload event");

<body onload="message()">

use // for single line comment or /* */ for multi-line comments.


UNTYPED: Variables are UNTYPED you can also redeclare or change the content of a variable to any data type.
GLOBAL: When a variable is implicitly declared WITHOUT a VAR keyword, it will be a global variable and will still be available even out of the block or method declaring it. 
SCOPE of variables is just within function, not any blocks of curly braces.

var x=5;

var scope = "global";
alert(scope);//displays "undefined" not "global"
scope = "local";

Objects as Window Properties

There is an instance of Window object for every JavaScript run-time that every top level variable (not included in another object) are implicitly a property of window object. In the same way, local objects are properties of the call object for each function. An important note is that, there can be several global objects(window object) and these objects can have access to properties of oen another via parent.frames[0].x this means that if you have your sensitive information on one browser window and another random site in another window, the random site can have access to the properties in your personally sensitive website. This should be prevented.
  • var foo = bar;
  • = bar;
  • foo = bar;
note that because bar is unqualified, it’s assumed to be a property on window.

To obtain the value of a variable a process called variable name resolution occurs. Every javascript execution context has a scope chain associated with it. To resolve the value, it first checks the deepest call object of the function, then the parent funtion and so on up to the global object properties scope. If it could not be resolved up to the global object it will be assigned as undefined.


<script type="text/javascript">
function show_alert()
alert("I am an alert box!");

<input type="button" onclick="show_alert()" value="Show alert box" />

<script type="text/javascript">

function show_confirm()

var r=confirm("Press a button");
if (r==true) 
document.write("You pressed OK!"); 
document.write("You pressed Cancel!"); 


<input type="button" onclick="show_confirm()" value="Show confirm box" />

<script type="text/javascript">
function show_prompt()
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
document.write("Hello " + name + "! How are you today?");


<input type="button" onclick="show_prompt()" value="Show a prompt box" />



function product(a,b)
return a*b;

for( in )

through elements of an array or properties of an object.

var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
  document.write(mycars[x] + "<br />");

try{} catch(err){}

Catch and handle JavaScript error messages, so you don't lose your audience. When users see errors, they often leave the Web page.

throw err

err can be a string, integer, Boolean or an object.
throw "Err1";


onload - onUnload: onload is used to check the browser type and version to display page properly. Often used to deal with cookies that should be set when a user enters or leaves a page.

onFocus, onBlur and onChange: blur is when object loses focus.

onSubmit: used to validate ALL form fields before submitting it.
<form method="post" action="xxx.htm" onsubmit="return checkForm()">             The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled.

onMouseOver - onMouseOut <a href="" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a>

Redirect to Another Webpage


Special Characters
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

Break Code LineYou can break up a code line within a text string with a backslash.

document.write("Hello \


.(property access) [](array index) ()(function arguments in function call) new(constructor call, create new object) ++(increment) --(decrement) -(negation) +(no-op) ~(bitwise complement) !(logical complement) delete(undefine a property) typeof(data type) void(return undefined value) +(plus) -(minus) *(multiply) /(devide) %(remainder) +(string concatenation) <<(bitwise left shift) >>(bitwise right shift with sign extension) >>>(bitwise right shift with zero extension) <(less than) <=(less than or equal) >(greater than) >=(greater than or equal) instanceof(check object type) in(check whether property exists) ==(equality) !=(inequality) ===(identity) !==(nonidentity) &(biwise AND) ^(biwise XOR) |(biwise OR) &&(logical AND) ||(logical OR) ?:(conditional operator) =(assignment) +=(assignment with operation) -= *= /= %= <<= >>= >>>= &= ^= |= ,(multiple evaluation)

Primitive Data Types

number, boolean, string, null, undefined, this, NAN, Infinity
Strings are immutable and passed by refernce to functions meanwhile non modifiable. On the other hand, strings are compared by value.

NAN, Infinity

Built-in Classes

No multi-dimensional array. BUT elements of array can be any data type even arrays of various lengths.
There can be undefined elements in an array, like var arr = [1,,,,5];
Defining an array:
var myCars=new Array("Saab","Volvo","BMW"); // condensed array

var myCars=["Saab","Volvo","BMW"]; // literal array

var myCars=new Array(); // regular array (add an optional integer argument to control array's size)

arr.join(); //put all the elements of an array into a string.
var b1=new Boolean( 0);
var b2=new Boolean(1);
var b3=new Boolean("");
var b4=new Boolean(null);
var b5=new Boolean(NaN);
var b6=new Boolean("false");

document.write("0 is boolean "+ b1 +"<br />"); //0 is boolean false
document.write("1 is boolean "+ b2 +"<br />"); //1 is boolean true
document.write("null is boolean "+ b4+ "<br />"); //null is boolean false
document.write("NaN is boolean "+ b5 +"<br />"); //NaN is boolean false
document.write("An empty string is boolean "+ b3 + "<br />"); //An empty string is boolean false
document.write("The string 'false' is boolean "+ b6 +"<br />"); //The string 'false' is boolean true

test(): searches a string for a specified value. Returns true or false
exec(): searches a string for a specified value. Returns the text of the found value. If no match is found, it returns null
compile() method is used to change the RegExp.can change both the search pattern, and add or remove the second parameter.

You can add a second parameter to the RegExp object, to specify your search. For example; if you want to find all occurrences of a character, you can use the "g" parameter ("global"). When using the "g" parameter, the exec() method works like this:
* Finds the first occurence of "e", and stores its position
* If you run exec() again, it starts at the stored position, and finds the next occurence of "e", and stores its position

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));

var myDate=new Date();
myDate.setDate(myDate.getDate()+5);    // If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!

Object Oriented Design

Objects are a collection of properties each of which consists of a name and a value. They are equal to a Java Map (or dictionary or hash) in concept.
Access Object Properties
var p = 'make'; ride[p];

Object Creation Ways
1. Create Template of an Object
You can also add some methods to the person object. This is also done inside the template:

function person(firstname,lastname,age,eyecolor)
this.newlastname=newlastname; //method

function newlastname(new_lastname)

myFather=new person("John","Doe",50,"blue"); myMother=new person("Sally","Rally",48,"green");

2. Incrementally Make an Arbitrary Object
var ride = new Object();
ride.make = 'Yamaha';
ride.model = 'V-Star Silverado 1100';
ride.year = 2005;
ride.purchased = new Date(2005,3,12);

3. Use JSON Notation (An Object Literal)
var ride = {
make: 'Yamaha',
model: 'V-Star Silverado 1100',
year: 2005,
purchased: new Date(2005,3,12),
owner: {
name: 'Spike Spiegel',
occupation: 'bounty hunter'

access a variable that is not defined
access a declared variable that is not initialized
null==undefined, to distinguish use the === identity equity or typeof operator. E.g, my.pop == null  --> true if my doesn't have a pop property or it is not initialized

this who owns that line of code that 'this' happens to be at? Default owner of a method is 'window', param1, param2, param3, ...) method.apply(onObj, [param1, param2, param3, ...]) : run method as if it belongs to the obj in its parameter list

var Person = {
name: "Tim",
age: 28,
greeting: function () {
return "Hello " + + ". Wow, you are " + this.age + " years old.";


var Alien = {
name: "Zygoff",
age: 5432
}; // a new object that doesn't even have a greeting function, but can still be used by it. (inject the object Alien as the "this" value.) 

Let's make a generic function that can work with any object that has age and name properties:
function makeOlder(years, newname) {
this.age += years;
if (newname) { = newname;
}, 2, "Old Tim");
makeOlder.apply(Dog, [1, "Shaggy"]);
console.dir({Person: Person, Dog: Dog}); 

    <title>Function Context Example</title>
      var o1 = {handle:'o1'};
      var o2 = {handle:'o2'};
      var o3 = {handle:'o3'};
      window.handle = 'window';      function whoAmI() {
        return this.handle;
      }      o1.identifyMe = whoAmI;      alert(whoAmI());
      alert(whoAmI.apply(o3));    </script>
  </head>  <body>
<html><head><title>Function Context Example</title><script>var o1 = {handle:'o1'};var o2 = {handle:'o2'};var o3 = {handle:'o3'};window.handle = 'window';
function whoAmI() {
return this.handle;
o1.identifyMe = whoAmI;
What is the result?
The result is window, o1, o2, o3.
the function acts like a method to o2, even though it has no association whatsoever—even as a property—with o2.

the function context is determined on a per invocation basis and that a single function can be called with any object acting as its context. It’s, therefore, probably never correct to say that a function is a method of an object. It’s much more correct to state:

A function f acts as a method of object o when o serves as the function context of the invocation of f.

The result is o3.
further emphasizing that it’s not how a function is declared but how it’s invoked that determines its function context.

What is the value of this at line A? Why?
<script type="text/javascript">
if (true) {
    // Line A
Line A is evaluated in the initial global execution context.
What is the value of this at line B when obj.staticFunction() is executed? Why?
<script type="text/javascript">
var obj = {
    someData: "a string"

function myFun() {
    // Line B

obj.staticFunction = myFun;

When calling a function on an object, ThisBinding is set to the object.
What is the value of this at line C? Why?
<script type="text/javascript">
var obj = {
    myMethod : function () {
        // Line C
var myFun = obj.myMethod;
In this example, the JavaScript interpreter enters function code, but because myFun/obj.myMethod is not called on an object, ThisBinding is set to window.
This is different from Python, in which accessing a method (obj.myMethod) creates a bound method object.
What is the value of this at line D? Why?
<script type="text/javascript">
function myFun() {
    // Line D
var obj = {
    myMethod : function () {

This one was tricky. When evaluating the eval code, this is obj. However, in the eval code, myFun is not called on an object, so ThisBinding is set to window for the call.
What is the value of this at line E?
<script type="text/javascript">
function myFun() {
    // Line E
var obj = {
    someData: "a string"
The line; is invoking the special built-in function, which accepts thisArg as the first argument.


Functions are objects in JavaScript. Can be:
  • Assigned to variables
  • Assigned as a property of an object
  • Passed as a parameter
  • Returned as a function result
  • Created using literals
A Function instance is a nameless object like the number 213 or any other JavaScript value. 
It’s named only by references that are made to it.
Function instances are values that can be assigned to variables, properties, or parameters just like instances of other object types.
And like those other object types, nameless disembodied instances aren’t of any use unless they’re assigned to a variable, property, or parameter through which they can be referenced.
Although a function can be made to act like a method of an object by setting the object as the function context, functions aren’t declared as methods of any single object. The way a method is invoked and the closure of the variables it requires determine the actual context of execution which can be called by any object which in case can lead to totally different behaviors.

obj.fieldG = 5;
func = function(myArgument){document.write(myArgument);}
obj.fieldG = func;
obj.fieldG("sample argument");  //as if calling the functions code but with different name.

Functions can be nested

a = function(){
var s=0;
b = function (){document.write(nested);}

Parameter Passing

Primitive datatypes (number, boolean, String) passed by value. 
objects and arrays passed by reference.


function hello() { alert('Hi there!'); }
  • setTimeout(hello,5000);
  • setTimeout(function() { alert('Hi there!'); },5000); //Function instance.

javascript prototype property allows you to add properties and methods to an object.
function employee(name,jobtitle,born)
var fred=new employee("Fred Flintstone","Caveman",1970);


Probably everybody knows about yield now, but some better documentation has come along. "Javascript's Future: Generators" by James Long has some good examples, including:

function foo(x) {
    while (true) {
        x = x * 2;
        yield x;

    "When you call foo, you get back a Generator object which has a next method."

var g = foo(2);; // -> 4; // -> 8; // -> 16

So yield is kind of like return: you get something back. return x returns the value of x, but yield x returns a function, which gives you a method to iterate toward the next value. Useful if you have a potentially memory intensive procedure that you might want to interrupt during the iteration.


Events are great for things that can happen multiple times on the same object — keyup, touchstart etc. With those events you don't really care about what happened before you attached the listener. 
img1.ready().then(function() {
  // loaded
}, function() {
  // failed

// and…
Promise.all([img1.ready(), img2.ready()]).then(function() {
  // all loaded
}, function() {
  // one or more failed

At their most basic, promises are a bit like event listeners except:
- A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa
- If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier

This is extremely useful for async success/failure, because you're less interested in the exact time something became available, and more interested in reacting to the outcome.
var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  else {
    reject(Error("It broke"));

//Here's how you use that promise:

promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"

//example XMLHttpRequest get request
function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();'GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));

    // Make the request

//Now let's use it:

get('story.json').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);