{"id":724,"date":"2015-04-15T08:02:17","date_gmt":"2015-04-15T17:02:17","guid":{"rendered":"http:\/\/blog.box.kr\/?p=724"},"modified":"2015-04-15T08:02:17","modified_gmt":"2015-04-15T17:02:17","slug":"%ed%8e%8c45-useful-javascript-tips-tricks-and-best-practices","status":"publish","type":"post","link":"https:\/\/blog.box.kr\/?p=724","title":{"rendered":"[\ud38c]45 Useful JavaScript Tips, Tricks and Best Practices"},"content":{"rendered":"<p><a href=\"http:\/\/modernweb.com\/2013\/12\/23\/45-useful-javascript-tips-tricks-and-best-practices\/\">http:\/\/modernweb.com\/2013\/12\/23\/45-useful-javascript-tips-tricks-and-best-practices\/<\/a><\/p>\n<p>&nbsp;<\/p>\n<h1 class=\"entry-title post-title\">45 Useful JavaScript Tips, Tricks and Best Practices<\/h1>\n<article>\n<div id=\"title-after\">\n<\/div>\n<div class=\"clear\">\n<\/div>\n<div class=\"st-format-standard-holder\"><img decoding=\"async\" loading=\"lazy\" class=\"attachment-post-image wp-post-image\" src=\"https:\/\/i0.wp.com\/fw008950-flywheel.netdna-ssl.com\/wp-content\/uploads\/2013\/12\/keep-calm-and-learn-javascript.jpg?resize=623%2C550\" alt=\"keep-calm-and-learn-javascript\" width=\"623\" height=\"550\" data-recalc-dims=\"1\" \/>\n<\/div>\n<div id=\"post-before\">\n<\/div>\n<div id=\"article\">\n<p><em>By <a href=\"http:\/\/modernweb.com\/authors\/saad-mousliki\">Saad Mousliki<\/a><\/em><\/p>\n<p>As you know, JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like <a href=\"http:\/\/phonegap.com\/\">PhoneGap<\/a> or <a href=\"http:\/\/www.appcelerator.com\/\">Appcelerator<\/a>), of the server side (like <a href=\"http:\/\/nodejs.org\/\">NodeJS<\/a> or<a href=\"http:\/\/wakanda.org\/\">Wakanda<\/a>) and has many other implementations. It\u2019s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using <a href=\"http:\/\/nodebots.io\/\">nodebot<\/a>, or <a href=\"http:\/\/semu.github.io\/noduino\/\">nodruino<\/a>). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.<\/p>\n<p>In this article, I\u2019ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser\/engine or the SSJS (Server Side JavaScript) interpreter.<\/p>\n<p>Note that the code snippets in this article have been tested in the latest Google Chrome version 30, which uses the V8 JavaScript Engine (V8 3.20.17.15).<\/p>\n<p><strong>1 \u2013 Don\u2019t forget <code>var<\/code> keyword when assigning a variable\u2019s value for the first time.<\/strong><\/p>\n<p>Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.<\/p>\n<p><strong>2 \u2013 use <code>===<\/code> instead of <code>==<\/code><\/strong><\/p>\n<p>The <code>==<\/code> (or <code>!=<\/code>) operator performs an automatic type conversion if needed. The <code>===<\/code> (or <code>!==<\/code>) operator will not perform any conversion. It compares the value and the type, which could be considered faster than <code>==<\/code>.<\/p>\n<pre><code>[10] === 10    \/\/ is false\n[10]  == 10    \/\/ is true\n'10' == 10     \/\/ is true\n'10' === 10    \/\/ is false\n []   == 0     \/\/ is true\n [] ===  0     \/\/ is false\n '' == false   \/\/ is true but true == \"a\" is false\n '' ===   false \/\/ is false <\/code><\/pre>\n<p><strong>3 \u2013 <code>undefined<\/code>, <code>null<\/code>, 0, <code>false<\/code>, <code>NaN<\/code>, <code>''<\/code> (empty string) are all falsy.<\/strong><br \/>\n<strong>4 \u2013 Use Semicolons for line termination<\/strong><\/p>\n<p>The use of semi-colons for line termination is a good practice. You won\u2019t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser. For more details about why you should use semi-colons, take a look to this artice:\u00a0<a href=\"http:\/\/davidwalsh.name\/javascript-semicolons\">http:\/\/davidwalsh.name\/javascript-semicolons<\/a>.<\/p>\n<p><strong>5 \u2013 Create an object constructor<\/strong><\/p>\n<pre><code>function Person(firstName, lastName){\n    this.firstName =  firstName;\n    this.lastName = lastName;\n}\n\nvar Saad = new Person(\"Saad\", \"Mousliki\");<\/code><\/pre>\n<p><strong>6 \u2013 Be careful when using <code>typeof<\/code>, <code>instanceof<\/code> and <code>constructor<\/code>.<\/strong><\/p>\n<ul>\n<li><em>typeof<\/em> : a JavaScript unary operator used to \u00a0return a string that represents the primitive type of a variable, \u00a0don\u2019t forget that <code>typeof null<\/code> will return \u201cobject\u201d, and for the majority of object types (Array, Date, and others) will return also \u201cobject\u201d.<\/li>\n<li><em>constructor<\/em> : is a property of the internal prototype property, which could be overridden by code.<\/li>\n<li><em>instanceof<\/em> : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it\u2019s found and false if not.<\/li>\n<\/ul>\n<pre><code>var arr = [\"a\", \"b\", \"c\"];\ntypeof arr;   \/\/ return \"object\"\narr  instanceof Array \/\/ true\narr.constructor();  \/\/[]\n<\/code><\/pre>\n<p><strong>7 \u2013 Create a Self-calling Function<\/strong><\/p>\n<p>This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, and has the following form:<\/p>\n<pre><code>(function(){\n    \/\/ some private code that will be executed automatically\n})();\n(function(a,b){\n    var result = a+b;\n    return result;\n})(10,20)<\/code><\/pre>\n<p><strong>8 \u2013 Get a random item from an array<\/strong><\/p>\n<pre><code>var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];\n\nvar  randomItem = items[Math.floor(Math.random() * items.length)];<\/code><\/pre>\n<p><strong>9 \u2013 Get a random number in a specific range<\/strong><\/p>\n<p>This code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.<\/p>\n<pre><code>var x = Math.floor(Math.random() * (max - min + 1)) + min;<\/code><\/pre>\n<p><strong>10 \u2013 Generate an array of numbers with numbers from 0 to max<\/strong><\/p>\n<pre><code>var numbersArray = [] , max = 100;\n\nfor( var i=1; numbersArray.push(i++) &lt; max;);  \/\/ numbers = [1,2,3 ... 100] <\/code><\/pre>\n<p><strong>11 \u2013 Generate a random set of alphanumeric characters<\/strong><\/p>\n<pre><code>function generateRandomAlphaNum(len) {\n    var rdmString = \"\";\n    for( ; rdmString.length &lt; len; rdmString  += Math.random().toString(36).substr(2));\n    return  rdmString.substr(0, len);\n\n}\n<\/code><\/pre>\n<p><strong>12 \u2013 Shuffle an array of numbers<\/strong><\/p>\n<pre><code>var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];\nnumbers = numbers.sort(function(){ return Math.random() - 0.5});\n\/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205]  *\/<\/code><\/pre>\n<p>A better option could be to implement a random sort order by code (e.g. : Fisher-Yates shuffle), than using the native sort JavaScript function. For more details take a look to <a href=\"http:\/\/stackoverflow.com\/questions\/962802\/is-it-correct-to-use-javascript-array-sort-method-for-shuffling\/962890#962890\">this discussion<\/a>.<\/p>\n<p><strong>13 \u2013 A string trim function<\/strong><\/p>\n<p>The classic trim function of Java, C#, PHP and many other language that remove whitespace from a string doesn\u2019t exist in JavaScript, so we could add it to the <code>String<\/code> object.<\/p>\n<pre><code>String.prototype.trim = function(){return this.replace(\/^s+|s+$\/g, \"\");};  <\/code><\/pre>\n<p>A native implementation of the trim() function is available in the recent JavaScript engines.<\/p>\n<p><strong>14 \u2013 Append an array to another array<\/strong><\/p>\n<pre><code>var array1 = [12 , \"foo\" , {name \"Joe\"} , -2458];\n\nvar array2 = [\"Doe\" , 555 , 100];\nArray.prototype.push.apply(array1, array2);\n\/* array1 will be equal to  [12 , \"foo\" , {name \"Joe\"} , -2458 , \"Doe\" , 555 , 100] *\/<\/code><\/pre>\n<p><strong>15 \u2013 Transform the <code>arguments<\/code> object into an array<\/strong><\/p>\n<pre><code>var argArray = Array.prototype.slice.call(arguments);<\/code><\/pre>\n<p><strong>16 \u2013 Verify that a given argument is a number<\/strong><\/p>\n<pre><code>function isNumber(n){\n    return !isNaN(parseFloat(n)) &amp;&amp; isFinite(n);\n}<\/code><\/pre>\n<p><strong>17 \u2013 Verify that a given argument is an array<\/strong><\/p>\n<pre><code>function isArray(obj){\n    return Object.prototype.toString.call(obj) === '[object Array]' ;\n}<\/code><\/pre>\n<p>Note that if the toString() method is overridden, you will not get the expected result using this trick.<\/p>\n<p>Or use\u2026<\/p>\n<pre><code>Array.isArray(obj); \/\/ its a new Array method<\/code><\/pre>\n<p>You could also use <code>instanceof<\/code> if you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.<\/p>\n<pre><code>var myFrame = document.createElement('iframe');\ndocument.body.appendChild(myFrame);\n\nvar myArray = window.frames[window.frames.length-1].Array;\nvar arr = new myArray(a,b,10); \/\/ [a,b,10]\n\n\/\/ instanceof will not work correctly, myArray loses his constructor\n\/\/ constructor is not shared between frames\narr instanceof Array; \/\/ false<\/code><\/pre>\n<p><strong>18 \u2013 Get the max or the min in an array of numbers<\/strong><\/p>\n<pre><code>var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];\nvar maxInNumbers = Math.max.apply(Math, numbers);\nvar minInNumbers = Math.min.apply(Math, numbers);<\/code><\/pre>\n<p><strong>19 \u2013 Empty an array<\/strong><\/p>\n<pre><code>var myArray = [12 , 222 , 1000 ];\nmyArray.length = 0; \/\/ myArray will be equal to [].<\/code><\/pre>\n<p><strong>20 \u2013 Don\u2019t use delete to remove an item from array<\/strong><\/p>\n<p>Use <code>splice<\/code>\u00a0instead of using <code>delete<\/code> to delete an item from an array. Using <code>delete<\/code> replaces the item with <code>undefined<\/code> instead of the removing it from the array.<\/p>\n<p>Instead of\u2026<\/p>\n<pre><code>var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];\nitems.length; \/\/ return 11\ndelete items[3]; \/\/ return true\nitems.length; \/\/ return 11\n\/* items will be equal to [12, 548, \"a\", undefined \u00d7 1, 5478, \"foo\", 8852, undefined \u00d7 1, \"Doe\", 2154,       119]   *\/<\/code><\/pre>\n<p>Use\u2026<\/p>\n<pre><code>var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];\nitems.length; \/\/ return 11\nitems.splice(3,1) ;\nitems.length; \/\/ return 10\n\/* items will be equal to [12, 548, \"a\", 5478, \"foo\", 8852, undefined \u00d7 1, \"Doe\", 2154,       119]   *\/<\/code><\/pre>\n<p>The delete method should be used to delete an object property.<\/p>\n<p><strong>21 \u2013 Truncate an array using length<\/strong><\/p>\n<p>Like the previous example of emptying an array, we truncate it using the <code>length<\/code> property.<\/p>\n<pre><code>var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];\nmyArray.length = 4; \/\/ myArray will be equal to [12 , 222 , 1000 , 124].<\/code><\/pre>\n<p>As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with <code>undefined<\/code> as a value. The array length is not a read only property.<\/p>\n<pre><code>myArray.length = 10; \/\/ the new array length is 10\nmyArray[myArray.length - 1] ; \/\/ undefined<\/code><\/pre>\n<p><strong>22 \u2013 Use logical AND\/ OR for conditions<\/strong><\/p>\n<pre><code>var foo = 10;\nfoo == 10 &amp;&amp; doSomething(); \/\/ is the same thing as if (foo == 10) doSomething();\nfoo == 5 || doSomething(); \/\/ is the same thing as if (foo != 5) doSomething();<\/code><\/pre>\n<p>The logical OR could also be used to set a default value for function argument.<\/p>\n<pre><code>function doSomething(arg1){\n    arg1 = arg1 || 10; \/\/ arg1 will have 10 as a default value if it\u2019s not already set\n}<\/code><\/pre>\n<p><strong>23 \u2013 Use the map() function method to loop through an array\u2019s items<\/strong><\/p>\n<pre><code>var squares = [1,2,3,4].map(function (val) {\n    return val * val;\n});\n\/\/ squares will be equal to [1, 4, 9, 16] <\/code><\/pre>\n<p><strong>24 \u2013 Rounding number to N decimal place<\/strong><\/p>\n<pre><code>var num =2.443242342;\nnum = num.toFixed(4);  \/\/ num will be equal to 2.4432<\/code><\/pre>\n<p>NOTE : the <code>toFixed()<\/code> function returns a string and not a number.<\/p>\n<p><strong>25 \u2013 Floating point problems<\/strong><\/p>\n<pre><code>0.1 + 0.2 === 0.3 \/\/ is false\n9007199254740992 + 1 \/\/ is equal to 9007199254740992\n9007199254740992 + 2 \/\/ is equal to 9007199254740994<\/code><\/pre>\n<p>Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard. For more explanation, take a look to <a href=\"http:\/\/www.2ality.com\/2012\/04\/number-encoding.html\">this blog post<\/a>.<\/p>\n<p>You can use <code>toFixed()<\/code> and <code>toPrecision()<\/code> to resolve this problem.<\/p>\n<p><strong>26 \u2013 Check the properties of an object when using a for-in loop<\/strong><\/p>\n<p>This code snippet could be useful in order to avoid iterating through the properties from the object\u2019s prototype.<\/p>\n<pre><code>for (var name in object) {\n    if (object.hasOwnProperty(name)) {\n        \/\/ do something with name\n    }\n}<\/code><\/pre>\n<p><strong>27 \u2013 Comma operator<\/strong><\/p>\n<pre><code>var a = 0;\nvar b = ( a++, 99 );\nconsole.log(a);  \/\/ a will be equal to 1\nconsole.log(b);  \/\/ b is equal to 99<\/code><\/pre>\n<p><strong>28 \u2013 Cache variables that need calculation or querying<\/strong><\/p>\n<p>In the case of a jQuery selector, we could cache the DOM element.<\/p>\n<pre><code>var navright = document.querySelector('#right');\nvar navleft = document.querySelector('#left');\nvar navup = document.querySelector('#up');\nvar navdown = document.querySelector('#down');<\/code><\/pre>\n<p><strong>29 \u2013 Verify the argument before passing it to <code>isFinite()<\/code><\/strong><\/p>\n<pre><code>isFinite(0\/0) ; \/\/ false\nisFinite(\"foo\"); \/\/ false\nisFinite(\"10\"); \/\/ true\nisFinite(10);   \/\/ true\nisFinite(undefined);  \/\/ false\nisFinite();   \/\/ false\nisFinite(null);  \/\/ true  !!! <\/code><\/pre>\n<p><strong>30 \u2013 Avoid negative indexes in arrays<\/strong><\/p>\n<pre><code>var numbersArray = [1,2,3,4,5];\nvar from = numbersArray.indexOf(\"foo\") ;  \/\/ from is equal to -1\nnumbersArray.splice(from,2);    \/\/ will return [5]<\/code><\/pre>\n<p>Make sure that the arguments passed to <code>splice<\/code> are not negative.<\/p>\n<p><strong>31 \u2013 Serialization and deserialization (working with JSON)<\/strong><\/p>\n<pre><code>var person = {name :'Saad', age : 26, department : {ID : 15, name : \"R&amp;D\"} };\nvar stringFromPerson = JSON.stringify(person);\n\/* stringFromPerson is equal to \"{\"name\":\"Saad\",\"age\":26,\"department\":{\"ID\":15,\"name\":\"R&amp;D\"}}\"   *\/\nvar personFromString = JSON.parse(stringFromPerson);\n\/* personFromString is equal to person object  *\/<\/code><\/pre>\n<p><strong>32 \u2013 Avoid the use of <code>eval()<\/code> or the <code>Function<\/code> constructor<\/strong><\/p>\n<p>Use of <code>eval<\/code> or the <code>Function<\/code> constructor are expensive operations as each time they are called script engine must convert source code to executable code.<\/p>\n<pre><code>var func1 = new Function(functionCode);\nvar func2 = eval(functionCode);<\/code><\/pre>\n<p><strong>33 \u2013 Avoid using <code>with()<\/code> (The good part)<\/strong><\/p>\n<p>Using <code>with()<\/code> inserts a variable at the global scope. Thus, if another variable has the same name it could cause confusion and overwrite the value.<\/p>\n<p><strong>34 \u2013 Avoid using for-in loop for arrays<\/strong><\/p>\n<p>Instead of using\u2026<\/p>\n<pre><code>var sum = 0;\nfor (var i in arrayNumbers) {\n    sum += arrayNumbers[i];\n}<\/code><\/pre>\n<p>\u2026it\u2019s better to use\u2026<\/p>\n<pre><code>var sum = 0;\nfor (var i = 0, len = arrayNumbers.length; i &lt; len; i++) {\n    sum += arrayNumbers[i];\n}<\/code><\/pre>\n<p>As a bonus, the instantiation of <code>i<\/code> and <code>len<\/code> is executed once because it\u2019s in the first statement of the for loop. Thsi is faster than using\u2026<\/p>\n<pre><code>for (var i = 0; i &lt; arrayNumbers.length; i++)<\/code><\/pre>\n<p>Why? The length of the array <code>arrayNumbers<\/code> is recalculated every time the loop iterates.<\/p>\n<p>NOTE : the issue of recalculating the length in each iteration was fixed in the latest JavaScript engines.<\/p>\n<p><strong>35 \u2013 Pass functions, not strings, to <code>setTimeout()<\/code> and <code>setInterval()<\/code><\/strong><\/p>\n<p>If you pass a string into <code>setTimeout()<\/code> or <code>setInterval()<\/code>, the string will be evaluated the same way as with <code>eval<\/code>, which is slow. Instead of using\u2026<\/p>\n<pre><code>setInterval('doSomethingPeriodically()', 1000);\nsetTimeout('doSomethingAfterFiveSeconds()', 5000);<\/code><\/pre>\n<p>\u2026use\u2026<\/p>\n<pre><code>setInterval(doSomethingPeriodically, 1000);\nsetTimeout(doSomethingAfterFiveSeconds, 5000);<\/code><\/pre>\n<p><strong>36 \u2013 Use a switch\/case statement instead of a series of if\/else<\/strong><\/p>\n<p>Using switch\/case is faster when there are more than 2 cases, and it is more elegant (better organized code). Avoid using it when you have more than 10 cases.<\/p>\n<p><strong>37 \u2013 Use switch\/case statement with numeric ranges<\/strong><\/p>\n<p>Using a switch\/case statement with numeric ranges is possible with this trick.<\/p>\n<pre><code>function getCategory(age) {\n    var category = \"\";\n    switch (true) {\n        case isNaN(age):\n            category = \"not an age\";\n            break;\n        case (age &gt;= 50):\n            category = \"Old\";\n            break;\n        case (age &lt;= 20):\n            category = \"Baby\";\n            break;\n        default:\n            category = \"Young\";\n            break;\n    };\n    return category;\n}\ngetCategory(5);  \/\/ will return \"Baby\"<\/code><\/pre>\n<p><strong>38 \u2013 Create an object whose prototype is a given object<\/strong><\/p>\n<p>It\u2019s possible to write a function that creates an object whose prototype is the given argument like this\u2026<\/p>\n<pre><code>function clone(object) {\n    function OneShotConstructor(){};\n    OneShotConstructor.prototype= object;\n    return new OneShotConstructor();\n}\nclone(Array).prototype ;  \/\/ []<\/code><\/pre>\n<p><strong>39 \u2013 An HTML escaper function<\/strong><\/p>\n<pre><code>function escapeHTML(text) {\n    var replacements= {\"&lt;\": \"&amp;lt;\", \"&gt;\": \"&amp;gt;\",\"&amp;\": \"&amp;amp;\", \"\"\": \"&amp;quot;\"};\n    return text.replace(\/[&lt;&gt;&amp;\"]\/g, function(character) {\n        return replacements[character];\n    });\n}<\/code><\/pre>\n<p><strong>40 \u2013 Avoid using try-catch-finally inside a loop<\/strong><\/p>\n<p>The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.<\/p>\n<p>Instead of using\u2026<\/p>\n<pre><code>var object = ['foo', 'bar'], i;\nfor (i = 0, len = object.length; i &lt;len; i++) {\n    try {\n        \/\/ do something that throws an exception\n    }\n    catch (e) {\n        \/\/ handle exception\n    }\n}<\/code><\/pre>\n<p>\u2026use\u2026<\/p>\n<pre><code>var object = ['foo', 'bar'], i;\ntry {\n    for (i = 0, len = object.length; i &lt;len; i++) {\n        \/\/ do something that throws an exception\n    }\n}\ncatch (e) {\n    \/\/ handle exception\n} <\/code><\/pre>\n<p><strong>41 \u2013 Set timeouts to <code>XMLHttpRequests<\/code><\/strong><\/p>\n<p>You could abort the connection if an XHR takes a long time (for example, due to a network issue), by using <code>setTimeout()<\/code> with the XHR call.<\/p>\n<pre><code>var xhr = new XMLHttpRequest ();\nxhr.onreadystatechange = function () {\n    if (this.readyState == 4) {\n        clearTimeout(timeout);\n        \/\/ do something with response data\n    }\n}\nvar timeout = setTimeout( function () {\n    xhr.abort(); \/\/ call error callback\n}, 60*1000 \/* timeout after a minute *\/ );\nxhr.open('GET', url, true);\n\nxhr.send();<\/code><\/pre>\n<p>As a bonus, you should generally avoid synchronous XHR calls completely.<\/p>\n<p><strong>42 \u2013 Deal with WebSocket timeout<\/strong><\/p>\n<p>Generally when a WebSocket connection is established, a server could time out your connection after 30 seconds of inactivity. The firewall could also time out the connection after a period of inactivity.<\/p>\n<p>To deal with the timeout issue you could send an empty message to the server periodically. To do this, add these two functions to your code: one to keep alive the connection and the other one to cancel the keep alive. Using this trick, you\u2019ll control the timeout.<\/p>\n<p>Add a <code>timerID<\/code>\u2026<\/p>\n<pre><code>var timerID = 0;\nfunction keepAlive() {\n    var timeout = 15000;\n    if (webSocket.readyState == webSocket.OPEN) {\n        webSocket.send('');\n    }\n    timerId = setTimeout(keepAlive, timeout);\n}\nfunction cancelKeepAlive() {\n    if (timerId) {\n        cancelTimeout(timerId);\n    }\n}<\/code><\/pre>\n<p>The <code>keepAlive()<\/code> function should be added at the end of the <code>onOpen()<\/code> method of the webSocket connection and the <code>cancelKeepAlive()<\/code> at the end of the <code>onClose()<\/code> method.<\/p>\n<p><strong>43 \u2013 Keep in mind that <a href=\"http:\/\/dev.opera.com\/articles\/view\/efficient-javascript\/?page=2#primitiveoperator\">primitive operations can be faster than function calls<\/a>. Use<a href=\"http:\/\/vanilla-js.com\/\">VanillaJS<\/a>.<\/strong><\/p>\n<p>For example, instead of using\u2026<\/p>\n<pre><code>var min = Math.min(a,b);\nA.push(v);<\/code><\/pre>\n<p>\u2026use\u2026<\/p>\n<pre><code>var min = a &lt; b ? a : b;\nA[A.length] = v;<\/code><\/pre>\n<p><strong>44 \u2013 Don\u2019t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live.<\/strong><\/p>\n<p><strong>45 \u2013 JavaScript is awesome: <a href=\"http:\/\/stackoverflow.com\/questions\/11246\/best-resources-to-learn-javascript\">Best Resources To Learn JavaScript<\/a><\/strong><\/p>\n<ul>\n<li>Code Academy JavaScript tracks:\u00a0<a href=\"http:\/\/www.codecademy.com\/tracks\/javascript\">http:\/\/www.codecademy.com\/tracks\/javascript<\/a><\/li>\n<li>Eloquent JavaScript by Marjin Haverbeke:\u00a0<a href=\"http:\/\/eloquentjavascript.net\/\">http:\/\/eloquentjavascript.net\/<\/a><\/li>\n<li>Advanced JavaScript by John Resig:\u00a0<a href=\"http:\/\/ejohn.org\/apps\/learn\/\">http:\/\/ejohn.org\/apps\/learn\/<\/a><\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>I know that there are many other tips, tricks and best practices, so if you have any ones to add or if you have any feedback or corrections to the ones that I have shared, please adda comment.<\/p>\n<h2>References<\/h2>\n<p>In this article I have used my own code snippets. Some of the snippets are inspired from other articles and forums:<\/p>\n<ul>\n<li><a href=\"http:\/\/developer.nokia.com\/Community\/Wiki\/JavaScript_Performance_Best_Practices\">JavaScript Performance Best Practices<\/a> (<a href=\"http:\/\/creativecommons.org\/licenses\/by-nc-sa\/2.5\/\">CC<\/a>)<\/li>\n<li><a href=\"https:\/\/code.google.com\/p\/jslibs\/wiki\/JavascriptTips\">Google Code JavaScript tips<\/a><\/li>\n<li><a href=\"http:\/\/stackoverflow.com\/questions\/724826\/javascript-tips-and-tricks-javascript-best-practices\">StackOverFlow tips and tricks<\/a><\/li>\n<li><a href=\"http:\/\/stackoverflow.com\/questions\/6888409\/settimeout-for-xhr-requests\">TimeOut for XHR<\/a><\/li>\n<\/ul>\n<\/div>\n<\/article>\n","protected":false},"excerpt":{"rendered":"<p>http:\/\/modernweb.com\/2013\/12\/23\/45-useful-javascript-tips-tricks-and-best-practices\/ &nbsp; 45 Useful JavaScript Tips, Tricks and Best Practices By Saad Mousliki As you know, JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJS orWakanda) and has many other implementations. It\u2019s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market. In this article, I\u2019ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser\/engine or the SSJS (Server Side JavaScript) interpreter. Note that the code snippets in this article have been tested in the latest Google Chrome version 30, which uses the V8 JavaScript Engine (V8 3.20.17.15). 1 \u2013 Don\u2019t forget var keyword when assigning a variable\u2019s value for the first time. Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"ngg_post_thumbnail":0,"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[15,16,5,7],"tags":[],"aioseo_notices":[],"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5q9Zn-bG","jetpack-related-posts":[{"id":89,"url":"https:\/\/blog.box.kr\/?p=89","url_meta":{"origin":724,"position":0},"title":"\ud398\uc774\uc9c0\ub85c\ub529\uc2dc \uba54\uc2dc\uc9c0 \ud45c\uc2dc","date":"2014-06-12","format":false,"excerpt":"\ud398\uc774\uc9c0\ub85c\ub529\uc2dc \uba54\uc2dc\uc9c0 \ud45c\uc2dc \uc5b4\ub5bb\uac8c \ub3d9\uc791\ud558\ub290\ub0d0..\ube0c\ub77c\uc6b0\uc838\uac00 \ud398\uc774\uc9c0\ub97c \uc77d\uc744\ub54c \ucc28\ub840\ub300\ub85c \uc77d\uc2b5\ub2c8\ub2e4.\uadf8\ub7ec\uba74 \uc18c\uc2a4\uc911 \ub9e8\uc704\uc5d0 \uc788\ub294\uac83\ubd80\ud130 \ubcf4\uc5ec\uc9c0\uac8c \ub418\uaca0\uc8e0.. 1\ubc88 \uc2a4\ud06c\ub9bd\ud2b8\uac00 \ub9e8\ucc98\uc74c \ubcf4\uc5ec \uc9d1\ub2c8\ub2e4.(\ub808\uc774\uc5b4 \ubcf4\uc784) \uadf8\ub7f0\ub2e4\uc74c \uc18c\uc2a4\uac00 \ub2e4\uc77d\ud600\uc9c0\uace0 2\ubc88\uc2a4\ud06c\ub9bd\ud2b8\uac00 \uc2e4\ud589\ub418\uba74 1\ubc88 \uc2a4\ud06c\ub9bd\ud2b8\uc5d0\uc11c \ubcf4\uc5ec\uc900 \ub808\uc774\uc5b4\uac00 \uc0ac\ub77c\uc9c0\uac8c \ub418\ub294\uac83\uc774\uc9c0\uc694.(\ub808\uc774\uc5b4 \uc228\uae40) \uadf8\ub7fc \uc0ac\uc6a9\ud574 \ubcf4\uc2ed\uc2dc\ub2e4. \uba3c\uc800 \uc544\ub798 1\ubc88 \uc2a4\ud06c\ub9bd\ud2b8\ub97c \uc18c\uc2a4\uc758 \ub9e8\uc704\uc5d0 \ub123\uc2b5\ub2c8\ub2e4. <!------------------------- \u2460\ubc88 \uc2a4\ud06c\ub9bd\ud2b8 ---------------------> <div id=\"suldowait\" height=\"\ub192\uc774\" width=\"\ub113\uc774\"\u2026","rel":"","context":"In &quot;javascript&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":93,"url":"https:\/\/blog.box.kr\/?p=93","url_meta":{"origin":724,"position":1},"title":"shift, ctrl (\uc26c\ud504\ud2b8, \ucee8\ud2b8\ub864)\ud0a4 \ud074\ub9ad\ud558\uba74 \uacbd\uace0\uba54\uc138\uc9c0 \ub744\uc6b0\uae30","date":"2014-06-12","format":false,"excerpt":"shift, ctrl (\uc26c\ud504\ud2b8, \ucee8\ud2b8\ub864)\ud0a4 \ud074\ub9ad\ud558\uba74 \uacbd\uace0\uba54\uc138\uc9c0 \ub744\uc6b0\uae30 <script language=\"JavaScript\"> < !-- www.tagin.net function click() { if((event.ctrlKey) || (event.shiftKey)) { alert('\ud0a4\ub97c \uc0ac\uc6a9\ud560 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.'); } } document.ommousedown=click; document.omkeydown=click; --> < \/script>","rel":"","context":"In &quot;javascript&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":97,"url":"https:\/\/blog.box.kr\/?p=97","url_meta":{"origin":724,"position":2},"title":"\ud504\ub808\uc784 \uc18c\uc2a4\ubcf4\uae30 \ub9c9\uae30","date":"2014-06-12","format":false,"excerpt":"\ud504\ub808\uc784 \uc18c\uc2a4\ubcf4\uae30 \ub9c9\uae30 <script language=\"JavaScript\"> if(parent.frames.length <= 0) { top.location.href=\"http:\/\/tagin.net\"; } < \/script> \ud504\ub808\uc784\uc744 \uc4f0\ub294 \ud648\ud398\uc774\uc9c0\uc5d0\uc11c \ud504\ub808\uc784 \ud398\uc774\uc9c0\uac00 \uc544\ub2cc \ud558\uc704 \ud504\ub808\uc784\uc73c\ub85c \uc9c1\uc811 \ub4e4\uc5b4\uac14\uc744 \ub54c http:\/\/tagin.net\uc73c\ub85c \uc774\ub3d9\ud558\ub294 \uc608\uc81c\uc785\ub2c8\ub2e4 head\uc5d0 \ub123\uc5b4\uc8fc\uc138\uc694","rel":"","context":"In &quot;javascript&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":91,"url":"https:\/\/blog.box.kr\/?p=91","url_meta":{"origin":724,"position":3},"title":"URL\uc8fc\uc18c \uc554\ud638\ud654","date":"2014-06-12","format":false,"excerpt":"URL\uc8fc\uc18c \uc554\ud638\ud654 <html> < head> < SCRIPT LANGUAGE=\"JavaScript\"> < !-- function encryptIt() { \/\/ the following letters are going to be encrypted. var letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"; var letterCode = new Array( '%61','%62','%63','%64','%65','%66','%67','%68','%69','%6a', '%6b','%6c','%6d','%6e','%6f','%70','%71','%72','%73','%74', '%75','%76','%77','%78','%79','%7a', '%41','%42','%43','%44','%45','%46','%47','%48','%49','%4a', '%4b','%4c','%4d','%4e','%4f','%50','%51','%52','%53','%54', '%55','%56','%57','%58','%59','%5a'); var _form = document.exf1; var _formIn = _form.input.value.split(\".\"); var output = _formIn[0]+\".\"; for(var\u2026","rel":"","context":"In &quot;javascript&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":210,"url":"https:\/\/blog.box.kr\/?p=210","url_meta":{"origin":724,"position":4},"title":"javascript ==, ===\uc758 \uc758\ubbf8","date":"2014-07-21","format":false,"excerpt":"0==false\/\/ true 0===false\/\/ false, because they are of a different type 1==\"1\"\/\/ true, auto type coercion 1===\"1\"\/\/ false, because they are of a different type","rel":"","context":"In &quot;JAVA&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":101,"url":"https:\/\/blog.box.kr\/?p=101","url_meta":{"origin":724,"position":5},"title":"\ud22c\uba85 \ub808\uc774\uc5b4 \uacf5\uc9c0\ucc3d","date":"2014-06-12","format":false,"excerpt":"\ud22c\uba85 \ub808\uc774\uc5b4 \uacf5\uc9c0\ucc3d <html> <head> <style type=\"text\/css\"> #demo {position:absolute; top:100; left:350; width:200; height:100; border:solid 2 gray; background:black; overflow:hidden; z-index:10; visibility:hidden; filter:alpha(opacity=30);} #text {position:absolute; top:100; left:350; width:200; height:100; border:solid 2 gray; color:beige; font-size:9pt; padding:5; overflow:hidden; z-index:11; visibility:hidden;} <\/style> <script language=javascript> function openmenu() { demo.style.visibility=\"visible\"; text.style.visibility=\"visible\";}function closemenu() { demo.style.visibility=\"hidden\"; text.style.visibility=\"hidden\";}<\/script> <\/head> <body\u2026","rel":"","context":"In &quot;javascript&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/blog.box.kr\/index.php?rest_route=\/wp\/v2\/posts\/724"}],"collection":[{"href":"https:\/\/blog.box.kr\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.box.kr\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.box.kr\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.box.kr\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=724"}],"version-history":[{"count":0,"href":"https:\/\/blog.box.kr\/index.php?rest_route=\/wp\/v2\/posts\/724\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.box.kr\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=724"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.box.kr\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=724"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.box.kr\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=724"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}