JavaScript Tips and Best Practices-2

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]

Avoid using with()

Using with() inserts a variable at the global scope. Thus, if another variable has the same name it could cause confusion and overwrite the value.

Use a switch/case statement instead of a series of if/else

Using switch/case is faster when there are more than 2 cases, and it is more elegant (better organized code). Avoid using it when you have more than 10 cases.

Keep in mind that primitive operations can be faster than function calls

For example, instead of using

var min = Math.min(a,b);
A.push(v);

use

var min = a < b ? a : b;
A[A.length] = v;

Leave a comment

Your email address will not be published. Required fields are marked *