Learning JavaScript

This page lists some common misconceptions and solutions to improve JavaScript performance or proper code in general. The intention is to speed up our code base and to make sure code does what it intends. For example  returns true, for starters.

Null or undefined
There are more than a dozen ways of comparing or looking at a variable to determine whether it is null or undefined (or either of them). Look at the following for actual performance numbers and decide for yourself what gives the best performance for your scenario:
 * http://jsperf.com/testing-undefined
 * http://jsperf.com/testing-null
 * http://jsperf.com/testing-null-or-undefined

Array
Arrays do not have a  "array". Nor do they validate as "instanceof Array" (atleast not consistently and cross-browser).

As of JavaScript 1.8.5, the array object constructor has an native object method (not a prototype) called "isArray". It can be used like this:

However this is new and not cross-browser yet. The other reliable way to do this to call " " and verify that it is equal to " ". However this is slightly slower.

jQuery has had a built-in object method called "isArray" that does the latter isString comparison that works cross-browser. As of jQuery 1.4 (up to atleast 1.6.1) it only does that if the, faster, native Array.isArray isn't available. The best of both.

So the safest and fastest way to check if a variable is an array is to use

http://jsperf.com/testing-array-type-speed-performance-comparison

WikiEditor
Some stuff Catrope discovered when optimizing EditToolbar. These may not be universally true, so when in doubt run both alternatives through the Firebug profiler or use http://jsperf.com


 * Building simple HTML that doesn't need stuff like .data or .click yourself and feeding it to .html or .append is literally about 100 times as fast (YMMV) as building it with jQuery
 * Even if you do need .data or .click, something like this is still faster (at least for 20-200 children, YMMV):
 * Avoid setting .data on hundreds of elements that have a common parent or near ancestor. Instead, add an empty object to the parent's .data and fill that through a reference using the child's rel property as keys. This reduces the number of .data calls a lot.
 * .text is faster than .html if you're only adding text
 * .addClass('foo') is faster than .attr('class', 'foo')
 * but in complex cases involving more attributes and multiple classes, .attr({ ... }); is faster

jQuery.size vs .length attribute
According to jQuery documentation, the .size method and the  property are functionally equivalent, but the   property saves a function call, improving efficiency as you can see on this performance comparison.