How not to write Javascript

Great tips & tricks from an javascript expert:
http://www.sitepoint.com/google-closure-how-not-to-write-javascript/

Highlights:


When checking if a variable is undefined:

var undefined;
return val !== undefined



When using strings in a switch: 

// use hash instead
obj[key] = 1;
if obj.hasOwnProperty(key);



When looping:
for (var i=0; j=arr.length; i



When converting functions to string for function name:
// str = String(foo);
str = (foo + "");



When checking for string type:
// typeof new String("a string") == 'object'
typeof (new String("a string") + "") == 'string'



When using float points:
// 1.0 - 0.25
1 - 0.25



When initializing arrays it is unnecessary to pre-allocate 'space':
// arr = new Array(25);
arr = [];



In JS, variable scope is declared by functions, and not blocks. That is:
if (a) { var x = 25; } console.log(x); // prints 25 just fine



The difference between:
var foo = function() {} and function bar() {} is that the latter is a function with the name 'bar'. The former is an anonymous function without a 'name'



Arrays are very powerful:
Acting as a queue: push, shift (unshift)
Acting as a stack: push, pop
Acting as array: arr[index], delete arr[index] (sets index content to undefined)
Splicing array: adding & removing elements with arr.splice(index,count,objs...)



Using regex:
var regex = '/regex_exp/i';
regex.test(haystack);



Using enumerative for-loops the right way:
for (var p in pages) { if (pages.hasOwnProperty(p)) { /* do something awesome */ } };
Use the hasOwnProperty method to prevent against enumerating over inherited properties



Don't use document.write(str);
Don't use browser sniffing code, ie. navigator.appName == 'Microsoft IE'
Don't use eval(str)
Don't use pseudo-protocols, ie. link




No comments: