Saturday, January 7, 2012

JavaScript:Tips and Tricks -1

1) Try to find the output of following if statements:
a)        if (null)
                alert("null is  true");
            else {
                alert("null is false:");
            }
            if (0 == '') {
                alert("0 == '' is true");
            } else {
                alert("0 == '' is false");
            }
            if (0 == '0') {
                alert("0 == '0' is true");
            } else {
                alert("0 == '0' is false");
            }
            if (0 == false) {
                alert("0 == false is true");
            } else {
                alert("0 == false is false");
            }
            if (0 == null) {
                alert("0 == null is true");
            } else {
                alert("0 == null is false");
            }
            if (0 == undefined) {
                alert("0 == undefined is true");
            } else {
                alert("0 == undefined is false");
            }
            if (0 == '\t\r\n') {
                alert("0 == '\t\r\n' is true");
            } else {
                alert("0 == '\t\r\n' is false");
            }
            if (null == undefined) {
                alert("null == undefined is true");
            } else {
                alert("null == undefined is false");
            }

Answer:
null is false
0 == '' is true
0 == '0' is true
0 == false is true
0 == null is false
0 == undefined is false
0 == '\t\r\n' is true
null == undefined is true


b)         if (0 === '') {
                alert("0 === '' is true");
            } else {
                alert("0 === '' is false");
            }
            if (0 === '0') {
                alert("0 === '0' is true");
            } else {
                alert("0 === '0' is false");
            }
            if (0 === false) {
                alert("0 === false is true");
            } else {
                alert("0 === false is false");
            }
            if (0 === null) {
                alert("0 === null is true");
            } else {
                alert("0 === null is false");
            }
            if (0 === undefined) {
                alert("0 === undefined is true");
            } else {
                alert("0 === undefined is false");
            }
            if (0 === '\t\r\n') {
                alert("0 === '\t\r\n' is true");
            } else {
                alert("0 === '\t\r\n' is false");
            }
            if (null === undefined) {
                alert("null === undefined is true");
            } else {
                alert("null === undefined is false");
            }

Answer:
0 === '' is false
0 === '0' is false
0 === false is false
0 === null is false
0 === undefined is false
0 === '\t\r\n' is false
null === undefined is false


2) Use of || operator in  Javascript:
var myString = myString || "abc";
myString = myString || "abc2";
In this case as myString is not defined thus it will assign value “abc” to it and in second statement as it is already defined thus will keep value as abc.

3) Preferred way of declaring array and objects:
a)    Bad way - var person = new object();
       Preferred way - var person = {};
b)    Bad way - keys = new Array();
       Preferred way - Keys = [];
The line mentioned as bad way has overhead(space and time complexity), The new key word is just wrapped around native types, thus avoid using it.

4) Use of for...in statement.
bad habit -
var myArray = [], name;
myArray[5] = "test"; ,//myArray.length will be 6
for(name in myArray){
alert(name +  “” + myArray[name]);
//will print only 5, test
}

preferred one :
var myArray = [], name;
myArray[5] = "test"; ,//mylength will be 6
for(var i = 0, length = myArray.length; i
alert(name +  “” + myArray[name]);
//will print 0-4, undefined and then 5,test.
}

5) For…in statement with use of prototype
            var myArray = [], name;
            myArray[5] = "test";
            alert("myArray length - " + myArray.length);

            Array.prototype.NewKey = "New Value";
            for (name in myArray) {
                alert(name + " - " + myArray[name]);
                //will print only 5 - test
                //will print NewKey - New Value
            }

By using prototype, we are actually adding this key in the base class. Thus every variable of this type will have this Key and Value available.
To solve such issue prefer to use it in following way:

            var myArray = [], name;
            myArray[5] = "test";
            alert("myArray length - " + myArray.length);
            Array.prototype.NewKey = "New Value";
            for (name in myArray) {
                if (myArray.hasOwnProperty(name)) {
                    alert(name + " - " + myArray[name]);
                    //will print only 5 - test
                }
            }

6) Variable Hoisting.
            var isHungry = true;
            if (isHungry) {
                timeToWait = 10;
            }

            function chew() {
                alert("timeToWait:- " + timeToWait);
            }
            chew();
          
it will show timeToWait :- 10.

In JavaScript the variable scope is defined by “var” keyword. If we don’t use “var” key word then it is global by default, thus available in chew function as well.

            function testFunction() {
            var isHungry = true;
            if (isHungry) {
                timeToWait = 10;
            }
            function chew() {
                alert("timeToWait:- " + timeToWait);
            }
            chew();
        }

        function test2() {
            alert("timeToWait:- " + timeToWait);
        }
Execute test2 – error saying timeToWait undefined
Execute testFunction – timeToWait:- 10
Now Execute test2 – timeToWait:-10

So after testFunction got executed then timeToWait got defined globally and now available in test2 also.

Here is one more example:
          function testFunction() {
            var isHungry = true;
            if (isHungry) {
                var timeToWait = 10;
            }
            function chew() {
                alert("timeToWait:- " + timeToWait);
            }
            chew();
        }
        function test2() {
            alert("timeToWait:- " + timeToWait);
        }

Execute test2 – error saying timeToWait undefined
Execute testFunction – timeToWait:- 10
Now Execute test2 – error saying timeToWait undefined

The difference came because of var before timeToWait.
In short the scoping is defined by “var” keyword, else the scope will be global.

7) Function Hoisting:
            function testFunction() {
            try {
                sayHello();
            } // error because not defined
            catch (e) {
                alert(e);
            }
            sayGoodbye(); //GoodBye
        }
        testFunction();
        sayGoodbye();
        var sayHello = function () {
            alert("Hello");
        };

        function sayGoodbye() {
            alert("GoodBye");
        }

It is because Javascript interprets it in following way:
        var sayHello = undefined, sayGoodbye = undefined;
        sayGoodbye = function () {
            alert("Goodbye");
        }
        function testFunction() {
            try {
                sayHello();
            } // error because not defined
            catch (e) {
                alert(e);
            }
            sayGoodbye(); //GoodBye
        }
        testFunction();
        sayGoodbye();
        var sayHello = function () {
            alert("Hello");
        };
JavaScript copies whole function definition itself on top if we define it in form of function, if we are using variable it will treat it like variable, which is sequence dependent, thus you can use it after you defined it.
Best practice is to define everything on top.