JavaScript Proven Practises
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

JavaScript Proven Practises

on

  • 1,019 views

 

Statistics

Views

Total Views
1,019
Views on SlideShare
668
Embed Views
351

Actions

Likes
0
Downloads
8
Comments
0

4 Embeds 351

http://www.sadev.co.za 337
http://sadev.co.za 6
http://www.dynamicsexchange.com 4
http://feeds.feedburner.com 4

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

CC Attribution-ShareAlike LicenseCC Attribution-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • What happens if someone else writes a method with the same name in the global scope?Does the person using my code need to see all that?Stolen “keywords”

JavaScript Proven Practises Presentation Transcript

  • 1. JavaScript Proven Practices20 June 2012
  • 2. AgendaCover proven practices about how to write betterJavaScriptLots of slides (50+) but a lot are code we will talk aboutand see what is right & what is wrongAssumption: You can read JavaScript (or fake it)
  • 3. JavaScript is a sloppylanguage, but inside itthere is an elegant,better language. Douglas Crockford -
  • 4. Situation 1code 1. var i=0; 2. function demo(){ 3. for (i=0; i<10; i++){ 4. // do stuff 5. } 6. } 7. demo(); 8. // what is i?output 10
  • 5. Situation 1 cont.code 1. function demo(){ 2. i = 50; 3. } 4. demo(); 5. // what is i?output 50
  • 6. Always use varVariables have scope Global FunctionUsing var helps keep the scope straight
  • 7. Always use var - fixes1. var i=0;2. function demo(){3. var i = 0;4. for (i=0; i<10; i++){5. print("demo");6. }7. }8. demo();9. // what is i?
  • 8. Always use var - fixes1. var i =0;2. function demo(){3. for (var i=0; i<10; i++){4. print("demo");5. }6. }7. demo();8. // what is i?
  • 9. Situation 2code 1. function setspan(num, text) 2. { 3. eval("myspan" + num + ".innerText = " + text + ""); 4. }data 1. myspan1.innerText = it aint what you do, its the way thacha do it;output //syntax error
  • 10. Situation 2 cont.code 1. eval("var a = awesome;"); 2. print(a);output awesome
  • 11. Avoid evaleval is hard to get right and there are many manysituations out of your control you need solveeval runs code – so you are saying you trust the userto write codeModern browsers pre-compile JavaScript, eval doesn’tbenefit from this!
  • 12. Situation 3code 1. function doSomething(someValue){ 2. //... 3. } 4. 5. setTimeout("doSomething(3 seconds elapsed. Time is up.);", 3000);code 1. var sum = new Function(op1, op2, return op1 + op2;); 2. var result = sum(10, 20); // ==> 30
  • 13. Avoid eval part 2eval can appear in sneaky locations in JavaScript Timers – SetTimeout & SetInterval Function contstructors
  • 14. Avoid Eval Part 2 Fixed1. setTimeout(function(){2. doSomething(3 seconds elapsed. Time is up.);3. }, 3000);1. function sum(op1, op2){2. return op1 + op2;3. }
  • 15. Situation 4code 1. var total = variable1 + variable2; 2. print(total);data 1. var variable1 = "1"; 2. var variable2 = "2";output 1. 12I’d never be so stupid to add strings? 1. var variable1 = document.elements["inputA"].value;
  • 16. Situation 4code 1. var total = parseInt(variable1) + parseInt(variable2); 2. print(total);data 1. var variable1 = "1"; 2. var variable2 = "2";output 3data 1. var variable1 = "064"; 64 base 8 = 52 base 10 2. var variable2 = "032"; 32 base 8 = 26 base 10output 52 + 26 = 78 78
  • 17. Unary OperatorJavaScript has one type for numbersOther primitives: Object, string & boolean, RegExp,Math, Array, Date, Error, NativeError (mostly)parseInt & parseFloat require you to set the numericbase the number is in – else it will try and guess
  • 18. Unary Operator(+<variable>) is the right way to get an numberEven though braces are optional - you should alwayshave them, else it is hard to work out what is additionand what is unary
  • 19. Unary Operator Fixedcode 1. var total = (+variable1) + (+variable2); 2. print(total);data 1. var variable1 = "1"; 2. var variable2 = "2";output 3data 1. var variable1 = "064"; 2. var variable2 = "032";output 96
  • 20. Unary Operator vs. parseIntcode 1. parseInt("567Gb");output 567code 1. +"567Gb";output NaN
  • 21. Situation 51. function validate (idNumber) {2. var year = getYear(idNumber);3. // omitted4. }5.6. function getYear(idNumber) {7. // omitted8. }
  • 22. NamespacesGroup things into namespaces, so that they areproperly scoped.Expose only what you need to expose.There are at least 5 different ways to do namespaces –pick one as a team. I’m going to show you my favouritenext – the Self-Executing Anonymous Function Public& Private.
  • 23. Namespaces Fixed1. (function (idNumbers, undefined) {2.3. idNumbers.validate = function (idNumber) {4. var year = getYear(idNumber);5. // omitted6. }7.8. function getYear(idNumber) {9. // omitted10. }11. }(window.idNumbers = window.idNumbers || {}));
  • 24. Namespaces Fixed1. idNumbers.validate(""); // works2. idNumbers.getYear(""); // undefined
  • 25. Namespaces Fixed1. (function (idNumbers, $, undefined) {2.3. // omitted4. }(window.idNumbers = window.idNumbers || {}, jQuery));
  • 26. Separation of concerns Taking namespaces further – practise separation of concerns Put JavaScript into separate files – do not inline in the HTML file. Build as much of your JavaScript do it is not tied to HTML or CSS Let HTML do what it is good at (organisation of content), CSS do what it is good at (presentation style) & JavaScript do what it is good atbad 1. itemX.color = "#fff"; 2. itemX.font-family = "Consolas";good 1. itemX.style = "codeBlock";
  • 27. Situation 6code 1. with (document.forms["mainForm"].elements) { 2. input1.value = "junk"; 3. input2.value = "junk"; 4. }data 1. <html> 2. <body> 3. <form id="mainForm"> 4. <input id="input1" type="text"> 5. <input id="input2" type="text"> 6. </form> 7. </body> 8. </html>
  • 28. Situation 6 cont.code 1. with (document.forms["mainForm"].elements) { 2. input1.value = "junk"; 3. input2.value = "junk"; 4. }data 1. <html> 2. <body> 3. <form id="mainForm"> 4. <input id="input1" type="text"> 5. </form> 6. </body> 7. </html>
  • 29. Situation 6 cont.code 1. var input2; 2. with (document.forms["mainForm"].elements) { 3. input1.value = "junk"; 4. input2.value = "junk"; 5. }data 1. <html> 2. <body> 3. <form id="mainForm"> 4. <input id="input1" type="text"> 5. </form> 6. </body> 7. </html>
  • 30. Avoid WithNo way to really know who/what will be changed
  • 31. Avoid with - Fixed1. var o = document.forms["mainForm"].elements;2. o.input1.value = "junk";3. o.input2.value = "junk";
  • 32. Situation 7code 1. var o = new Object(); 2. o.name = Jeffrey; 3. o.lastName = Way; 4. o.someFunction = function() { 5. console.log(this.name); 6. }
  • 33. Prefer object literalsPREFERAllows for more flexibility, cleaner code (noconstructors) & you don’t need to worry aboutconstructor parameter ordering.
  • 34. Prefer object literals - fixed1. var o = {2. name : Jeffrey,3. lastName : Way,4. someFunction : function() {5. console.log(this.name);6. }7. };1. var o = {};
  • 35. Situation 8code 1. var a = new Array(); 2. a[0] = "Robert"; 3. a[1] = "MacLean";
  • 36. Prefer object literalsApplies to arrays just as well
  • 37. Prefer object literals - fixed1. var o = ["Robert", "MacLean"]; A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object. Douglas Crockford
  • 38. Situation 9code 1. var x = "123"; 2. var y = 123; 3. x == y;output 1. true
  • 39. Situation 9 cont.1. == 0 false2. 0 == true3. false == false false4. false == 0 true5. false == undefined false6. false == null false7. null == undefined true8. trn == 0 true
  • 40. Use === rather than ==== is equality=== is identityEquality checks type, if type differs will convert andthen check valuesIdentity checks type, if type differs will return false
  • 41. Use === rather than == - fixed1. "123" === 123; // false2. === 0 // false3. 0 === // false4. false === false // false5. false === 0 // false6. false === undefined // false7. false === null // false8. null === undefined // false9. trn === 0 // false
  • 42. Situation 10code 1. function x(){ 2. return 3. 6 4. } 5. x();output
  • 43. ALWAYS end with semicolonSemicolon is a statement separator in JavaScriptPutting semicolon’s in is optional – but then JavaScriptwill guess where the statements will be separatedBe consistent
  • 44. ALWAYS end with semicolon - fixedcode 1. function x(){ 2. return 6; 3. } 4. x();output 6
  • 45. Situation 11code 1. var a = 1,2; 2. var b = 1,2,3; 3. var c = 99+1,99output 2 3 99
  • 46. Avoid the comma operatorComma operator – not the comma separator in arrays– can lead to very tricky to understand code.Unless you are 100% sure about it – don’t use itEven when you are 100% sure – add comments for therest of us
  • 47. Comma Operator - Fixed1. var r = [], n = 0, a = 0, b = 1, next ;2. function nextFibonacci() {3. next = a + b;4. return b = (a = b, next);5. }6. while(n++ < 10) {7. r.push(nextFibonacci());8. }9. r; //[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  • 48. Situation 121. foo = "awesome";1. var foo = "awesome";2. delete foo;1. var o = { foo: 123, foo: 456 };1. function eval() { }1. eval("var a = false;");2. print(a);1. with
  • 49. Turn Strict mode ONAll code runs in the strict context which makes yourcode more stable, finds more coding problems andraises more exceptions.Can define strict in a function
  • 50. Turn Strict mode ONWhat does it do? ECMAScript 3 deprecated methods raise exceptions Unassigned variables throw exceptions Delete throws exceptions Duplicate properties throw exceptions Hijacking eval throws exceptions Eval code is sandboxed With is gone MORE!!!Full info: http://dmitrysoshnikov.com/ecmascript/es5-chapter-2-strict-mode/
  • 51. Turn Strict mode ONFor this talk it helps with: Situation 1 – always use var. Undeclared variables will syntax error Situation 4 – parseInt defaults to decimal in strict mode Your mileage may vary here: Chrome 19 does it wrong  IE 10 does it right  Situation 6 – with. Always gives syntax error
  • 52. Turn Strict mode ON - Fixed1. "use strict";1. function demo(){2. "use strict";3. // more4. }1. foo = "awesome"; // exception2. var bar = "awesome";3. delete bar; // exception4. var o = { foo: 123, foo: 456 }; // exception5. function eval() { } // exception6. eval("var a = false;");7. print(a); // undefined8. with //syntax error
  • 53. Questions?
  • 54. Next week: Toolsincluded will be tools that solve all these issues
  • 55. Sourceshttp://www.javascripttoolbox.com/bestpracticeshttp://net.tutsplus.com/tutorials/javascript-ajax/24-javascript-best-practices-for-beginners/http://stackoverflow.com/http://www.crockford.com/http://www.jslint.com/lint.html#optionshttp://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/