Javascript
Basic Javascript
Formatting
Spacing
It’s a good idea from a readability standpoint to give your code room to breath. This means spacing around comparison operators as well as before and after braces:
// Bad
if(foo==="bar"){
doBaz();
}
// Good
if(foo === "bar") {
doBaz();
}
Braces
Please do not put braces on their own lines:
// Bad
if(foo)
{
bar();
}
// Good
if(foo) {
bar();
}
jQuery
jQuery Variables
Anytime you place a jQuery object into a variable, prepend the variable with “$”. This is an accepted jQuery convention that lets us know we’re dealing with a jQuery object and not a native object.
var foo = document.getElementById("foo"); // native object var $foo = $("foo"); // jQuery object
Cache Whenever Possible
If there’s the possibility you’ll need dom element or it’s children more than once, be sure to cache it to a variable to prevent querying the dom multiple times.
var $something = $('#something');
$something.bind("click", doStuff);
$something.children("li").fadeOut();