Making Javascript Good :)

Somethings I learnt from Crockford :)
Keep it right always :)
function a()  //Seems to be working but not :)
{
    return
    {
        name: 'a'
    };    
}
console.log(a().name);

function a() {  //Keep braces always right. It works :)
    return {
        name: 'a'
    };    
}
console.log(a().name);

There is no concept of block level scoping in javascript but the syntax exists. So, the former falls in that block hole and returns undefined.

It's not c or c++
var i = 'tamil';
for(var i = 0;i < 10;i++){
    
}
console.log(i);

This is misleading because declaring 'var i' @ initialization of for-loop doesn't mean 'i' has the scope of the loop & it doesn't interfere with the one out.
There is no other scope than function scope in javascript. All our declarations are hoisted up to function scope no matter where ever they are. So, don't get misleaded :)

All you spend is 0 but you get a lot :)
function sample() {
    ....do something
    var j = 10;
    ....do something
}

As I mentioned earlier there are no other scopes other than functions. So, what happens here is
function sample() {
    var j = undefined; // Hoisted to the top always. Better we do it meaningfully as var j = 10;
    ....do something
    j = 10;
    ....do something
}

Keep the declarations @ the beginning always. It costs you nothing but it might save your time in future :)

You might know what you are doing :)
if(a = b) { //1
    
}

if(a == b) a(); c(); //2

You might know what you are doing, but don't expect others
I might think for 1, It as either
if(a == b) { //typo
    
}
//or 
a = b;
if(a) {
    
}

For 2
if(a == b) {
    a();
    c();
}
//or
if(a == b) {
    a();
}
c();

Be clear for others too :) It helps

ALL is always bigger than LOT :) U gotta believe :P
0 == false //true
'0'==false //true
'false'==false //false

These might not affect in lots of places but lot !== all :P So, Always use
0 === false //false
'0' === false //false
'false' === false //false


Without with
var test = {    //1
             name: 'xxx',
             age: 12
}
var age = 100;
with(test) {
    age = 200;
} 
console.log(test.age);
console.log(age);

var test = {    //2
             name: 'xxx',
}
var age = 100;
with(test) {
    age = 200;
} 
console.log(test.age);
console.log(age);

1 & 2 are not the same. So, don't rely on unreliable things out there :)

I think I'm becoming Crockford's fan :)

Comments

Popular posts from this blog

Headless Chrome/Firefox Selenium Java in Amazon EC2

Cassandra PHPCassa & Composite Types

Selenium Webdriver in Nodejs + Javascript