Last active
December 10, 2015 20:08
-
-
Save sophie-eihpos/4485645 to your computer and use it in GitHub Desktop.
JavaScript Best Practices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Use === and !== Instead of == and != | |
2. Eval = Bad | |
3. Do not use short-hand, for example: omitting curly braces and semi-colons | |
4. Utilize http://www.jslint.com/ | |
5. Place Scripts at the Bottom of Your Page | |
6. Declare Variables Outside of the For Statement | |
7. The Fastest Way to Build a String - Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative. | |
8. Reduce Globals | |
9. Comment Your Code | |
10. Embrace Progressive Enhancement. Always compensate for when JavaScript is disabled. | |
11. Do not Pass a String to "SetInterval" or "SetTimeOut" | |
12. Do not Use the "With" Statement, use var object | |
13. Use {} Instead of New Object() | |
14. Use [] Instead of New Array() | |
16. Optimize loops. One of the most common mistake is to read the length attribute of an array at every iteration. | |
var names = ['George','Ringo','Paul','John']; | |
var all = names.length; | |
for(var i=0;i<all;i++){ | |
doSomeThingWith(names[i]); | |
} | |
OR...... | |
var names = ['George','Ringo','Paul','John']; | |
for(var i=0,j=names.length;i<j;i++){ | |
doSomeThingWith(names[i]); | |
} | |
15. Long List of Variables? Omit the "Var" Keyword and Use Commas Instead | |
17. Always, Always Use Semicolons | |
18. "For in" Statements. When looping through items in an object, you might find that you will also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information. | |
19. Use Firebug "Timer" Feature to Optimize Your Code | |
function TimeTracker(){ | |
console.time("MyTimer"); | |
for(x=5000; x > 0; x--){} | |
console.timeEnd("MyTimer"); | |
} | |
21. Self-Executing Functions | |
(function doSomething() { | |
return { | |
name: 'jeff', | |
lastName: 'way' | |
}; | |
})(); | |
22. Raw JavaScript Can Always Be Quicker Than Using a Library. jQuery "each" method is great for looping, but using a native "for" statement will always be an ounce quicker. | |
23. Crockford JSON.Parse | |
var response = JSON.parse(xhr.responseText); | |
var container = document.getElementById('container'); | |
for(var i = 0, len = response.length; i < len; i++) { | |
container.innerHTML += '<li>' + response[i].name + ' : ' + response[i].email + '</li>'; | |
} | |
24. Remove "Language" | |
<script type="text/javascript" language="javascript"> | |
... | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment