Skip to content

Instantly share code, notes, and snippets.

@abhayathapa
Created November 30, 2013 07:13
Show Gist options
  • Save abhayathapa/7716279 to your computer and use it in GitHub Desktop.
Save abhayathapa/7716279 to your computer and use it in GitHub Desktop.
JS and jquery best practise and hacks
/*
[Best Practices for Beginners](http://net.tutsplus.com/tutorials/JavaScript-ajax/24-JavaScript-best-practices-for-beginners/)
[Airbnb styleguides](https://github.com/airbnb/JavaScript)
[Write better query](http://flippinawesome.org/2013/11/25/writing-better-jquery-code/)
[Best practices guide for JavaScript](https://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md)
[The Essentials of Writing High Quality JavaScript](http://net.tutsplus.com/tutorials/JavaScript-ajax/the-essentials-of-writing-high-quality-JavaScript/)
[Increase your jquery performance](http://net.tutsplus.com/tutorials/JavaScript-ajax/10-ways-to-instantly-increase-your-jQuery-performance/)
*/
// Old - ifElse
if (success) {
obj.start();
} else {
obj.stop();
}
// New
var method = success ? obj.start() : obj.stop()
//Old String Join
"first" + "name"
//New
['first', 'name'].join(' ');
// default to 'No name' when myName is empty (or null, or undefined)
var name = myName || 'No name';
// Old
if (isThisAwesome) {
alert('yes'); // it's not
}
// New
isThisAwesome && alert('yes');
//Debug
var x = 1;
debugger; // Code execution stops here, happy debugging
x++;
//slow
for (var i = 0; i < a.length; i++);
//Fast
for (var i = a.length - 1; i >= 0; i--);
//JQUERY
//var caching
$element = $('#element');
// old
$first.click(function(){
$first.css('border','1px solid red');
});
//NEW Prefer ON
$first.on('click',function(){
$first.css('border','1px solid red');
})
//old
if(collection.length > 0){..}
//NEW
if(collection.length){..}
//old
var
$container = $('#container'),
$containerLi = $('#container li')
//NEW - Use Subqueries Caching Parents
var
$container = $('#container '),
$containerLi = $container.find('li')
// old - live is deprecated
$('#stuff').live('click', function() {
console.log('hooray');
});
// New
$('#stuff').on('click', function() {
console.log('hooray');
});
// Keep code readable
// Use chaining
// Use IDs Instead of Classes
// Use For Instead of Each
// Whenever your functions don’t return false, you jump to the top of the page.
// Load jQuery Code from a CDN
// Native JS functions are faster than libraries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment