Wednesday, May 01, 2013 

Javascript patterns / thoughts.

Single var pattern:

The single var pattern looks like this:
function func() {
var a = 1,
b = 2,
sum = a + b,
myobject = {},
i,
j;
//
}


Problem with variable hosting:

myname = "global"; // global variable
function func() {
alert(myname); // "undefined"
var myname = "local";
alert(myname); // "local"
}
func();

The first alert gives undefined instead of "global" because there is a local variable - var myname defined and because of hoisting, it would be hoisted to the top of function and is assigned to "undefined" and hence the alert gives "undefined"

Function declaration and expressions:
Difference between declaration and function expression.



// Named function expression.
var xyz = function abc(){};
xyz is going to be defined as usual, abc is undefined in all browsers but IE — do not rely on it being defined. But it will be defined inside its body:
var xyz = function abc(){
  // xyz is visible here
  // abc is visible here
}
// xyz is visible here
// abc is undefined here
JSon does not have comments normally:
But there are libraries which support them. Use JSon.minify() to remove comments before you pass it to json.parse.
https://github.com/getify/JSON.minify