« Home | Data structures and algorithms. » | Chess client interface in YUI. » | Unicode, things to know. » | Differences between myisam and innodb » | Removing unnecessary .svn folders from » | Java collections and generics. » | Mysql cluster & replication. » | Finding prime numbers with in a given number n. » | Javascript performance. » | Sorting algorithms. » 

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 = {},

Problem with variable hosting:

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

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.