Sunday, September 16, 2012

JavaScript Tips and Tricks - 7

Avoid eval in javascript -
var string1 = "var num1 = 1; alert(num1);";
var string2 = "var num2 = 2; alert(num2);";
var string3 = "var num3 = 3; alert(num3);";
eval(string1);//--1
new Function(string2)(); // --2
(function(){
    eval(string3); // --3
}());
alert(typeof num1); //--4
alert(typeof num2); // --5
alert(typeof num3); // --6
Output-
(1) - 1
(2) - 2
(3) - 3
(4) - number
(5) - undefined
(6) - undefined
NOTE - eval interfere with the scope chain,if the scope where eval is called, is global then it will make the variable Global. To overcome such problem we can wrap eval in an immediate function.eval can also access and modify a variable in its outer scope,whereas function cannot.

Arrays - use [] instead of new Array() -
var a = [3];
alert(a.length); // --1
alert(a[0]); // --2
//---
var b = new Array(3);
alert(b.length); // --3
alert(b[0]); // --4
 //--
var c = [2.34]
alert(c[0]); // -- 5

output -
 (1) -1
 (2) - 3
 (3) - 3
 (4) - undefined
 (5) - 2.34
If we use new Array() to construct a new array and pass a integer number to it, it takes 1st parameter as its length, in every other case it behaves differently. Thus its always recommended to avoid new Array and use [] to construct an Array.

Wrapper Objects -
In javascript for primitive types number,string and boolean we have wrapper objects Number(), String() and Boolean() available.
example -
var a = 100;
typeof(a); --> number
var objA = new Number(100);
typeof(objA); --> object
There are few methods available on object, but if we execute them on primitive as well, it works -
var s = "hello";
s.toUpperCase();
It is because of primitive can act as an object when needed(similar to auto boxing).But it does not mean that primitive variable will itself converted into object and will remain object. For that particular function/method it will get convert to object and then back to primitive. Here is example -
var s = "hello";
alert(s.toUpperCase()); -- > HELLO
s.newmethod = function() {
    alert('new method');
}
s.newmethod(); --> ERROR


No comments:

Post a Comment