Friday, April 15, 2011

TOP JavaScript Mistakes And Solutions

TOP JavaScript Mistakes

1.Usage of for..in to iterate Arrays

Solution : always use regular for loops to iterate arrays

2.Array dimensions
Solution :Use literal notation to initialize arrays. Do not predefine array length

3. Undefined properties

Solution: if you want to explicitly declare a uninitialized properties
inside an object, mark them as null

4. Misuse of Closures

See JavaScript Closures FAQ ( http://jibbering.com/faq/notes/closures/) for an awesome explanation about closures and contexts.

Solution: use closures to simplify your code

5. Closures in loops

See JavaScript Closures FAQ for an awesome explanation about closures and contexts.

Solution: use a second function to pass the correct value.

6. Memory leaks with DOM objects

Solution: avoid those closures or undo the circular reference inside the function

7. Differentiate float numbers from integer numbers

Solution: don’t use decimals to “convert” numbers to floats

8. Usage of with() as a shortcut

See JavaScript Closures FAQ for an awesome explanation about closures and contexts.

Solution: don’t use with() for shortcuts. Only for context injection when you really need it.

9. Usage of strings with setTimeout/setInterval

Solution: never use strings for setTimeout()or setInterval()

10. Usage of setInterval() for heavy functions

Solution: avoid setInterval(), use setTimeout(

11. Misuse of ‘this’

* Regular function: myFunction(‘arg1’);

this points to the global object, wich is window for all browers.

* Method: someObject.myFunction(‘arg1’);

this points to object before the dot, someObject in this case.

* Constructor: var something = new myFunction(‘arg1’);

this points to an empty Object.

* Using call()/apply(): myFunction.call(someObject, ‘arg1’);


12. Usage of eval() to access dynamic properties

Solution: use square bracket notation instead of eval()

13. Usage of undefined as a variable

Solution: use typeof when checking for undefined


1 comment: