JavaScript


JSON.stringify(myObj, null, 4)

if(typeof myObj== "undefined" )
if( Object.prototype.toString.call( 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.

Inline

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

<html>

<body>
<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.
</script>
</body>

</html>

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

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

<body onload="message()">
</body>
</html>

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

Variables

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;
carname="Volvo";

var scope = "global";
b=function(){
alert(scope);//displays "undefined" not "global"
scope = "local";
alert(scope);
}

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;
  • window.foo = 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.

Dialogs

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

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

</body>
</html>
 confirm
<html>
<head>
<script type="text/javascript">

function show_confirm()
{

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

</script>
</head>
<body>

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

</body>
</html>
 prompt
<html>
<head>
<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?");
}
}

</script>
</head>
<body>

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

</body>
</html>

function

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.
try{
throw "Err1";
.
.
}catch(er){
if(er=="Err1"){
}
}

Events

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="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a>

Redirect to Another Webpage

if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/";
}

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 \
World!");





Operators

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

Array
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)
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

Methods
document.write(arr);
parents.concat(children);
arr.join(); //put all the elements of an array into a string.
arr.join(',');
arr.sort();
Boolean
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

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


Date
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
ride.make
ride['make']
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.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.newlastname=newlastname; //method
}

function newlastname(new_lastname)
{
this.lastname=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'
}
};

null
undefined
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'
method.call(onObj, 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 " + this.name + ". Wow, you are " + this.age + " years old.";
}
};

Person.greeting();

var Alien = {
name: "Zygoff",
age: 5432
}

Person.greeting.call(Alien); // 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) {
this.name = newname;
}
}
makeOlder.call(Person, 2, "Old Tim");
makeOlder.apply(Dog, [1, "Shaggy"]);
console.dir({Person: Person, Dog: Dog}); 


 
<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;      alert(whoAmI());
      alert(o1.identifyMe());
      alert(whoAmI.call(o2));
      alert(whoAmI.apply(o3));    </script>
  </head>  <body>
  </body>
</html>
<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;
alert(whoAmI());alert(o1.identifyMe());alert(whoAmI.call(o2));alert(whoAmI.apply(o3));</script></head><body></body>
</html>
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.

alert(o1.identifyMe.call(o3));
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
}
</script>
window
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;

obj.staticFunction();
</script>
obj
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;
myFun();
</script>
window
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 () {
        eval("myFun()");
    }
};
obj.myMethod();
</script>
window

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"
};
myFun.call(obj);
</script>
obj
The line myFun.call(obj); is invoking the special built-in function Function.prototype.call(), which accepts thisArg as the first argument.

Function

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.field=func;
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);}
b();
}
a();

Parameter Passing

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

callback

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

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



yield

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);
g.next(); // -> 4
g.next(); // -> 8
g.next(); // -> 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.


promises

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. 
promises 
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();
    req.open('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
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

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

    // Make the request
    req.send();
  });
}

//Now let's use it:

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

http://bahmutov.calepin.co/linking-promises.html


Comments