Thursday, 30 January 2014

JavaScript best practices

1 – Don’t forget var keyword when assigning a variable’s value for the first time.
      Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.
2- Use strings accumulator-style: Using + operator a new string is created in memory and the concatenated value is assigned to it. Only after this the result is assigned to a variable.
Example:

a='A'+'B';   // slower

Faster :
a+='A';
a+='B';

3- Primitive operations can be faster than function calls: Consider using alternative primitive operation over function calls in performance critical loops and functions.

Slow:
var min = Math.min(a, b);
arr.push(val);

Faster:
var min = a < b ? a : b;
arr[arr.length] = val;

4-Maximize object resolution speed and minimize scope chain:
Inefficient way:
var url = location.href;

Efficient one:
var url = window.location.href;

5-use === instead of == : The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.

[10] === 10    // is false
[10]  == 10    // is true
'10' == 10     // is true
'10' === 10    // is false


6-Use Semicolons for line termination: It is a best practice to use semi-colons for line termination.You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser.

7- Create a Self-calling Function: 
(function(){
    // some private code that will be executed automatically
})(); 

(function(a,b){
    var result = a+b;
    return result;
})(10,20)

this function is self called function and the code will execute automatically.

8-Get a random number in a specific range:

var x = Math.floor(Math.random() * (max - min + 1)) + min;

9-Generate an array of numbers with numbers from 0 to maxvar numbersArray = [] , max = 100;

10-Append an array to another array:
var arr = [1 , "foo" , {name "Joe"} , -28];

var arr2 = ["Dog" , 5 , 100];
Array.prototype.push.apply(arr, arr2);
/* array1 will be equal to  [1 , "foo" , {name "Joe"} , -28 , "Dog" , 5 , 100] */

11-Verify that a given argument is a number:

function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

12-Verify that a given argument is an array:

Array.isArray(obj);

13-Get the max or the min in an array of numbers:

var  numbers = [5, 4 , 12 , -21 , 28 , 400 , 122205, -8511];
var maximum = Math.max.apply(Math, numbers); // 122205
var minimum = Math.min.apply(Math, numbers);  // -8511

14-Empty an array:
var myArray = [13 , 22 , 100 ]; 
myArray.length = 0; // myArray will be equal to [].

15-Don’t use delete to remove an item from array: Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

16-Truncate an array using length:
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; 
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

17-Use the map() function method to loop through an array’s items:
var squares = [1,2,3,4].map(function (val) { 
    return val * val; 
});
// squares will be equal to [1, 4, 9, 16]

18-Rounding number to N decimal place:

var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432

NOTE : the toFixed() function returns a string and not a number.

19-Floating point problems:
0.1 + 0.2 === 0.3 // is false

Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit.

20-Avoid negative indexes in arrays:
var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ;  // from is equal to -1
numbersArray.splice(from,2);    // will return [5]

if we using splice method with negative index then it will delete last element from the array.

21-Pass functions, not strings, to setTimeout() and setInterval():
If you pass a string into setTimeout() or setInterval(), the string will be evaluated the same way as with eval, which is slow.

Instead of using…

setInterval('doSomethingPeriodically()', 1000); 
setTimeout('doSomethingAfterFiveSeconds()', 5000);

…use…

setInterval(doSomethingPeriodically, 1000); 
setTimeout(doSomethingAfterFiveSeconds, 5000);



for more detail  Click Here





No comments:

Post a Comment