If you are like me and you procrastinated learning javascript until your kids were dependant on it to eat, then this quick refresher post might be of some value. To get things started, I have created a very simple page in jsfiddle. Feel free to copy the code from the following snippets and test it out at JsFiddle.
A word of caution, this is going to be a long long post. Let’s begin:
// Global variables
function add(first,second) {
// Change this to var a = first for it be local
a = first;
return a + second;
}
write("1 + 2 = " + add(1,2));
write("a = " + a);
write("3 + 4 = " + add(3,4));
write("a = " + a);
if(window.a)
write("a is global");
else
write("a is NOT global or is undefined");
// typeof
var streetNumber = 42;
var streetAddress = "123 address";
write(typeof streetNumber + " = " + streetNumber);
write(typeof streetAddress + " = " + streetAddress);
// Null evals false in bool comaprsion
var myValue = null;
if(!myValue)
write('null evals to false');
// Non null evals true in bool comparison
var hasValue = 1;
if(hasValue)
write('hasValue is NOT null');
// zero evals false in bool comparison
var zeroVal = 0;
if(!zeroVal)
write('zero value evals false in bool comparison');
var emptyString = "";
if(!emptyString)
write('empty string evals false in bool comparison');
// Undefined
var something;
write("Initial value of something = " + something);
if(!something)
write("undefined evaluates to false");
var person = { name : "Raghu" };
write("Name: " + person.name);
write("Age: " + person.age); // prints undefined
// Objects
// empty object
var empty = {};
write(typeof empty);
write(empty.toString());
// new keyword notation
var person = new Object();
person.name = "Raghu";
write(person.name);
// object literal notation
var john = { name : "John", age : 20 };
write(john.name);
write(john.age);
write(john.toString());
// write own implementation of toString
john.toString = function() {
return "Name = " + this.name + " Age = " + this.age;
};
write(john.toString());
// functions are also objects
write(write.toString());
// length of a function object returns the number of parameters
function add(one, two){
return one + two;
}
write(add.length);
// nested objects
var nestedObj = {
address : {
number : 1,
street : "brunswick"
}
};
write(nestedObj.address.street);
// Equality
// objects are equal to themselves
var joe = { name : "Joe" };
write("Object equals to itself : " + (joe === joe));
// + operator coercion : BE CAREFULL !!!!
var sameJoe = { name : "Joe" };
write("Object equals to itself (without braces): " + sameJoe === sameJoe);
// two separate objects are not equal
write("Two separate objects are equal : " + (joe === sameJoe));
// primtive types are equal if their values match
write("apple === apple :" + ("apple" === "apple"));
write("16 === 16 :" + (16 === 16));
// That's why you never use == operator
write(' "" == 0 : ' + ("" == 0));
// Function invocation
function reverse(a)
{
a = a.split('').reverse().join('');
return a;
}
function reversePersonName(p)
{
p.Name = reverse(p.name);
return p;
}
var name = "Tom";
write("Reversing string primitive = " + reverse(name));
write("Original string primitive = " + name);
var tom = new Object();
tom.name = "Tom";
write( reversePersonName(tom).name );
write( tom.name );
// Recursion
write(
(function factorial(n) {
if(n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
})(5));
// function's argument property
function add() {
var total = 0;
for(var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
write(add());
write(add(1,2));
write(add(10,20,30));
// Closures
var a = "a";
function outer() {
var b = "b";
function middle() {
var c = "c";
function inner() {
write(a + b + c);
}
inner();
}
middle();
}
outer();
Exception Handling
// Exception handling
function exceptionThrower()
{
throw { name: "KichooException", message: "Kichoo did something wronng" } ;
}
try{
exceptionThrower();
}
catch(kichooException){
write("Exception name = " + kichooException.name);
write("Exception message = " + kichooException.message);
}
// this keyword in an object
var myObj = { name : "Raghu",
showName : function () {
write(this.name);
}
};
myObj.showName();
// using the bind method to copy function to a global state
var myObj =
{ name : "Raghu",
showName : function () {
write(this.name);
}
};
myObj.showName();
// bind to top level window object
var sn = myObj.showName.bind(this);
// This will now print window object's name property
sn();
// Another example
function def() {
write(this.x);
}
var newDef = def.bind( { x: 123 } );
newDef();