{"id":1292,"date":"2015-04-01T05:35:57","date_gmt":"2015-04-01T05:35:57","guid":{"rendered":"http:\/\/www.nikola-breznjak.com\/blog\/?p=1292"},"modified":"2015-08-06T12:22:47","modified_gmt":"2015-08-06T12:22:47","slug":"codeschool-javascript-best-practices-notes","status":"publish","type":"post","link":"https:\/\/nikola-breznjak.com\/blog\/miscellaneou\/codeschool\/codeschool-javascript-best-practices-notes\/","title":{"rendered":"Codeschool JavaScript Best Practices Notes"},"content":{"rendered":"<p>I\u00a0finished the course at <a href=\"https:\/\/www.codeschool.com\/courses\/javascript-best-practices\">CodeSchool<\/a>, and below are my notes from it.<\/p>\n<h2>Level 1<\/h2>\n<p><strong>Ternary<\/strong> howto with SIAF<\/p>\n<pre class=\"lang:default decode:true\">var allPacked = true;\r\nvar readyToGo = true;\r\nvar adventureTime;\r\n\r\nadventureTime = allPacked &amp;&amp; readyToGo ?\r\n\r\n  function( ){\r\n    return \"Adventure time is now!\" ;\r\n  }()\r\n  :\r\n  function( ){\r\n    return \"Adventuring has been postponed!\" ;\r\n  }() ;\r\n\r\nconsole.log(adventureTime);<\/pre>\n<p><strong>Short-circuting<\/strong>, if the this.swords is not empty it takes it immediately, without looking at the thing after the ||<\/p>\n<pre class=\"lang:default decode:true \">this.swords = this.swords || [];<\/pre>\n<p>Same goes for &amp;&amp;, as soon as it finds a first falsy value &#8211; it returns that. If all falsy, it returns the last one.<\/p>\n<h2>Level 2<\/h2>\n<p>If you need lengthy, repetitive access to a value nested deep within a JS Object,\u00a0then cache the necessary value in a local variable.<\/p>\n<pre class=\"lang:default decode:true\">var numCritters = location.critters.length;\r\nfor(var i = 0; i &lt; numCritters; i++){\r\n      list += location.critters[i];\r\n}\r\n\r\n\/\/instead of\r\nfor(var i = 0; i &lt; location.critters.length; i++){\r\n      list += location.critters[i];\r\n}\r\n\r\n\/\/and even better\r\nfor(var i = 0, numCritters = location.critters.length; i &lt; numCritters; i++){\r\n    list += location.critters[i];\r\n}<\/pre>\n<p>Put script tag just before the ending body tag, or you can also leave them in the head section, but add <strong>async<\/strong> keyword. Use a list of variables after the keyword <strong>var<\/strong> all at once! Use function <strong>join()<\/strong>\u00a0on the array instead of concatenation. with +=. <strong>console.time(&#8220;string&#8221;)<\/strong> is the opening statement to a timer method that will help us measure how long our code is taking to perform. <strong>console.timeEnd(&#8220;string&#8221;)<\/strong> ends it and prints how long it took. &#8220;string&#8221; has to be the same in both cases.<\/p>\n<pre class=\"lang:default decode:true \">var now = new Date();\r\n\r\nconsole.log(+now) == console.log(new Number(now));<\/pre>\n<h2>\u00a0Level 3<\/h2>\n<p><strong>\u00a0===<\/strong> compares type and content. <strong>instanceof<\/strong> &#8211; userful to determine, well, the instance of some object \ud83d\ude42<\/p>\n<pre class=\"lang:default decode:true \">function Bird(){}\r\nfunction DatatypeBird(){}\r\nfunction SyntaxBird(){}\r\nDatatypeBird.prototype = Object.create(Bird.prototype);\r\nSyntaxBird.prototype   = Object.create(Bird.prototype);\r\n<\/pre>\n<p>Runtime error catching:<\/p>\n<pre class=\"lang:default decode:true \">try{\r\n   if(someVar === undefined)\r\n        throw new ReferenceError();\r\n}\r\ncatch(err){\r\n    if(err instanceof ReferenceError)\r\n        console.log(\"Ref err:\" + err);\r\n\r\n    \/\/TypeError\r\n}\r\nfinally{\r\n    \/\/this will execute no matter what\r\n}<\/pre>\n<p>Avoid <strong>eval<\/strong>, <strong>with<\/strong>.<\/p>\n<p>Use num.toFixed(2), parseFloat(), parseInt(num, radix). Radix can be from 2 &#8211; 36. typeof along with isNan to determine if the number is trully a number.<\/p>\n<h2>Level 4<\/h2>\n<p><strong>Namespace<\/strong> is an object that groups and protects related data and methods in JavaScript files.<\/p>\n<p>Say you have a code like this:<\/p>\n<pre class=\"lang:default decode:true\">var treasureChests = 3;\r\nvar openChest = function(){\r\n    treasureChests--;\r\n    alert(\"DA DADADA DAAAAAAA!\");\r\n};<\/pre>\n<p>you can use namespacing like this:<\/p>\n<pre class=\"lang:default decode:true\">var DATA = {\r\n\ttreasureChests : 3,\r\n\topenChest : function(){\r\n\t    this.treasureChests--;\r\n\t    alert(\"DA DADADA DAAAAAAA!\");\r\n\t}\r\n};<\/pre>\n<p>You then call the function like this: DATA.openChests().<\/p>\n<p><strong>Closures<\/strong>\u00a0are a\u00a0feature of JavaScript, used to cause some properties to be private, bound only to a surrounding function&#8217;s local scope, and some properties to be public, accessible by all holders of the namespace.<\/p>\n<p>Private\u00a0properties are created\u00a0in the local scope of the function expression.\u00a0Public\u00a0properties are built within the object\u00a0which is then returned\u00a0to become the namespace.\u00a0Access to private\u00a0data is thus possible only because of closure\u00a0within the larger module.<\/p>\n<p>Say you have a code like this:<\/p>\n<pre class=\"lang:default decode:true \">var CAVESOFCLARITY = {\r\n  stalactites: 4235,\r\n  stalagmites: 3924,\r\n  bats: 345,\r\n  SECRET: {\r\n    treasureChests: 3,\r\n    openChest: function(){\r\n      this.treasureChests--;\r\n      alert(\"DA DADADA DAAAAAAA!\");\r\n    }\r\n  }\r\n};<\/pre>\n<p>You would make it into a closure like this:<\/p>\n<pre class=\"lang:default decode:true \">var CAVESOFCLARITY = function () {\r\n\r\n  var treasureChests = 3;\r\n\r\n  return {\r\n    stalactites: 4235,\r\n    stalagmites: 3924,\r\n    bats: 345,\r\n    openChest: function () {\r\n        treasureChests--;\r\n        alert(\"DA DADADA DAAAAAAA!\");\r\n    }\r\n  };\r\n}();<\/pre>\n<p>If a module references globally-scoped variables, it&#8217;s a best practice to bring them into the scope of anonymous closure through the use of a specific technique called <strong>global imports<\/strong>.<\/p>\n<p>Say the code is like this and uses a global variable named globalAnswer:<\/p>\n<pre class=\"lang:default decode:true \">var MySomething = function () {\r\n  var a = 3;\r\n\r\n  return {\r\n    getA: function() {return a; },\r\n    summon: function(){\r\n      if(globalAnswer === \"42\"){\r\n        alert(\"YEP!\");\r\n      }\r\n      else{\r\n          alert(\"NOPE\");\r\n      }\r\n    }\r\n  };\r\n}();<\/pre>\n<p>You would rewrite this using global imports like this:<\/p>\n<pre class=\"lang:default decode:true \">var MySomething = function (answer) {\r\n  var a = 3;\r\n\r\n  return {\r\n    getA: function() {return a; },\r\n    summon: function(){\r\n      if(answer === \"42\"){\r\n        alert(\"YEP!\");\r\n      }\r\n      else{\r\n          alert(\"NOPE\");\r\n      }\r\n    }\r\n  };\r\n}(globalAnswer);<\/pre>\n<p>Your import ensures clarity of scope within a module.\u00a0By using a parameter, you protect the global\u00a0data that might have been overwritten.\u00a0All imported data becomes locally\u00a0scoped to the anonymous function, to be used in closure.\u00a0Thus, when compared with searching\u00a0the entire scope, import\u00a0are both clearer and faster.<\/p>\n<p><strong>Augmentation<\/strong>\u00a0is\u00a0the term for adding or changing properties in a module after the module has already been built.<\/p>\n<p>In simple augmentation, the module\u00a0file and the augmentation file do not\u00a0share their private state.\u00a0Augmented module properties may only access\u00a0the private\u00a0data from their file&#8217;s closure. Private\u00a0data from the original\u00a0closure will not\u00a0be lost, and will be accessible to all original properties\u00a0that referenced it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I\u00a0finished the course at CodeSchool, and below are my notes from it. Level 1 Ternary howto with SIAF var allPacked = true; var readyToGo = true; var adventureTime;&hellip;<\/p>\n","protected":false},"author":1,"featured_media":1351,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[10,27],"tags":[],"class_list":["post-1292","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-codeschool","category-javascript"],"_links":{"self":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1292","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/comments?post=1292"}],"version-history":[{"count":8,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1292\/revisions"}],"predecessor-version":[{"id":1352,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1292\/revisions\/1352"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media\/1351"}],"wp:attachment":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media?parent=1292"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/categories?post=1292"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/tags?post=1292"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}