SlideShare ist ein Scribd-Unternehmen logo
1 von 40
“JavaScript: It is the language that
people use without bothering to
learn it first”
                       Douglas Crockford
Coding
Use ‘===‘ instead of ‘==‘
 However, when working with == and !=, you’ll run into
  issues when working with different types. In these
  cases, they’ll try to coerce the values, unsuccessfully.

var x = 1, y = "1";
console.log(x == y);     //true
console.log(x === y);    //false

var x, y = null;
console.log(x == y);     //true
console.log(x === y);    //false

var x = ["", null, undefined];
console.log(x == ",,"); //true
console.log(x === ",,"); //false
Eval is Bad
 Not only will this decrease your script’s performance
  substantially, but it also poses a huge security risk
  because it grants far too much power to the passed in
  text. Avoid it!
var func = {
          method: function () {
                    console.log('test');
          }
};

var whatToDo = "method";

//Static
func.method();

//Dynamic - DON'T USE
eval("func." + whatToDo + "()");

//Dynamic - This is the right way
func[whatToDo]();
Don’t declare global variables
 “By reducing your global footprint to a single name,
 you significantly reduce the chance of bad interactions
 with other applications, widgets, or libraries.“
                                      Douglas Crockford
var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name);
Always declare your variables using var
 If you declare a variable, without using "var", the
  variable always becomes GLOBAL.



function test(){
     name = "Jean"; //this is global
}

test();
console.log(name) // “Jean”
Declare Variables on top
 variables should be declared on top of each function
 because of what is known as JavaScript Hoisting
var name = 'sarfraz';

function test(){
     console.log(name);
     var name = 'nawaz';
     console.log(name);
}

​test();​
Declare Variables Outside of the For
Statement
 When executing lengthy “for” statements, don’t make
 the engine work any harder than it must.

var someArray = [1, 2, 3, 4];
for (var i = 0; i < someArray.length; i++) {
      var container = "what";
      console.log(i);
}

var names = ['George','Ringo','Paul','John'];

for(var i=0,j=names.length;i<j;i++){
  doSomeThingWith(names[i]);
}
String Concatenation…
 Not easy to decide…
var str = "";
for (var i = 30000; i > 0; i--) {
  str += "String concatenation. ";
}
var str = "", sArr = [];
for (var i = 30000; i > 0; i--) {
  sArr[i] = "String concatenation. ";
}
str = sArr.join("");

var str = "";
for (var i = 30000; i > 0; i--) {
  str = str.concat("String concatenation. ");
}
String Concatenation (cont.)
 http://jsperf.com/javascript-string-concatenation
Use [] Instead of New Array()
 "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
var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

var a = ['Joe','Plumber'];
"For in" Statements
 When looping through items in an object, you might find
  that you'll also retrieve method functions as well. In order
  to work around this, always wrap your code in an if
  statement which filters the information
 Don’t use “for in” to loop a array – slow performance

for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}
Use SetTimeOut instead SetInterval
 SetInterval will execute the code every [x] milliseconds
 no matter what.
window.setInterval(function() {
     ajax_Call();
  }, 500);
setTimeout(function foo() {
    call_Ajax(y, function() {
        if (++y < 10) {
            setTimeout(foo, 100);
        }
    });
}, 100);
Starting Curly Brace On The Same Line
 That's one of the pitfalls of javascript: automatic
  semicolon insertion
function myFunc()
{
      return;
      {
            name: 'sarfraz'
      };
}

var f = myFunc();
console.log(f); <--- ???
Don't use try-catch-finally inside performance-
critical functions
 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.
 Exception handling should be done at as high level in the script where
  it does not occur frequently, for example outside a loop.
 Or if possible, avoid try-catch-finally completely
var object = ['foo', 'bar'], i;
for (i = 0; i < object.length; i++) {
   try {
      // do something that throws an exception
   } catch (e) {
      // handle exception
   }
}


var object = ['foo', 'bar'], i;
try {
    for (i = 0; i < object.length; i++) {
        // do something
    }
} catch (e) {
    // handle exception
}
new
 The new operator is required when calling a Constructor
  function.
 If new is omitted, the global object is clobbered by the
  constructor.
 There is no compile-time or run-time warning.

​var x = function(){
     alert(this);
 }

var y = x(); //Window Object

var z = new x(); //x Object
Debugging
console.log(
     firstVariable,
     secondVariable,
     xVariable);

console.clear();
Function Declaration vs.
Function Expression
 The function_expression form indicates that function are
  first-class objects, you can do anything with them like a
  variable.
 The only difference between them is that all function
  declarations are hoisted to the top of the scope which may
  matter in certain cases.

function function_declaration() {
     …
}​

var function_expression = function() {
     ...
}
Comment as much as needed but not more
 It might seem unnecessary at first, but trust me, you WANT to
  comment your code as best as possible.
 Comments don’t hurt anybody if you do them right. We’ll come back to
  that in the last point of this article, but let’s say that if your comments
  end up in the code that end users see then something is not going
  right.

// Cycle through array and echo out each name.
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}
Patterns
Cache values
 Notice how we must determine the length of the array
  for each iteration, and how we traverse the DOM to
  find the "container" element each time -- highly
  inefficient!
for(var i = 0; i < someArray.length;
i++) {
     …
}
var $myDiv = $("#myDiv");
$myDiv.css("color","red");
$myDiv.css("opacity",1);
Self-Executing Functions
 Rather than calling a function, it's quite simple to make a
  function run automatically when a page loads, or a parent
  function is called. Simply wrap your function in
  parenthesis, and then append an additional set, which
  essentially calls the function.

(function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();
Modularize — one function per task
 This is a general programming best practice — making sure
  that you create functions that fulfill one job at a time makes
  it easy for other developers to debug and change your code
  without having to scan through all the code to work out
  what code block performs what function.
function addLink(text,url,parentElement){
  var newLink = document.createElement('a');
  newLink.setAttribute('href',url);
  newLink.appendChild(document.createTextNode(text));
  if(parentElement.id === 'menu'){
    newLink.className = 'menu-item';
  }
  if(url.indexOf('mailto:')!==-1){
    newLink.className = 'mail';
  }
  parentElement.appendChild(newLink);
}
Separate config data
function validate(value) {
    if (!value) {
        alert("Invalid value");
        location.href = "/errors/error.php";
    }
}

var config = {
    urls: {
        invalid: "/errors/invalid.php"
    },
    strs: {
        invalidmsg: "Invalid value"
    }
};

function validate(value) {
    if (!value) {
        alert(config.strs.invalidmsg);
        location.href = config.urls.invalid;
    }
}
Module Pattern
   Designate a single namespace for your application
var App = (function () {
    'use strict';

    var settings;

    return {
                                        (function (app) {

         init: function(initialSettings){
                                     // Private methods:

             settings = initialSettings;
                                     function find(query) {
         },                              // Perform search
                                            }

                                      function verifyQuery(query)          {
         getVersion: function (){         // Verify query
             return settings.version; }
         }                            // Public methods:

                                            app.search = {
    };                                          find: find,
                                                verifyQuery: verifyQuery
}());                                       };

                                        }(App));
ECMA5
Use 'use strict'
 Strict Mode is a new feature in ECMAScript 5 that allows you to
  place a program, or a function, in a "strict" operating context.
 This strict context prevents certain actions from being taken and
  throws more exceptions (generally providing the user with more
  information and a tapered-down coding experience).
 Strict mode helps out in a couple ways:
    It catches some common coding bloopers, throwing exceptions.
    It prevents, or throws errors, when relatively "unsafe" actions are
     taken (such as gaining access to the global object).
    It disables features that are confusing or poorly thought out.

function imStrict(){
  "use strict";
  myVar = “test” // thrown exception
}
Use JSON object
 JSON is syntax for storing and exchanging text
  information
 JSON is smaller than XML, and faster and easier to
  parse.


var response = JSON.parse(xhr.responseText);

console.log(response.email);
Other Good Practices
Is jQuery your friend?
 http://jsperf.com/id-vs-class-vs-tag-selectors
Don’t Mix Js And Html
 One of the most important best practices is to always
 separate JS code from HTML and go unobtrusive
<a href="#" onclick="doSomething()">
     Some Action
</a>


<a href="#" id="link">Some Action</a>

<script type="text/javascript">
var link = document.getElementById('link');

link.addEventListener(“click”, function(){
 // do something
}, false);
Scripts at the Bottom of Your Page or use “async”
or “defer”
 If you have JS files whose only purpose is to add
  functionality — for example, after a button is clicked — go
  ahead and place those files at the bottom, just before the
  closing body tag. This is absolutely a best practice.
 Async: Specifies that the script is executed asynchronously
  (only for external scripts)
 Defer: Specifies that the script is executed when the page
  has finished parsing (only for external scripts)
Deploying
Utilize JS Lint
 “JSLint takes a JavaScript source and scans it. If it finds a problem, it
  returns a message describing the problem and an approximate location
  within the source. The problem is not necessarily a syntax error,
  although it often is. JSLint looks at some style conventions as well as
  structural problems. It does not prove that your program is correct. It
  just provides another set of eyes to help spot problems.”
Unit Testing
 http://coding.smashingmagazine.com/2012/06/27/intr
  oduction-to-javascript-unit-testing/
 http://stackoverflow.com/questions/300855/looking-
  for-a-better-javascript-unit-test-tool

 Qunit
 Jasmine
 Other???

 http://docs.jquery.com/Qunit
 http://qunitjs.com/cookbook/
 https://github.com/pivotal/jasmine/
Unify + Minify…bundeling



            Build
Finishing
Tiny Tips
 Use Developer Tool - Chrome
    JavaScript Profiling
    Do more with Chrome Developer Tools
 JavaScript Errors Notifier
Read…Read…Read…
 http://javascript.crockford.com/
 http://ejohn.org/blog
 http://paulirish.com/category/javascript/

 http://dsheiko.com/weblog/learning-javascript-from-the-code
 http://www.slideshare.net/toddanglin/5-tips-for-better-javascript
 http://2011.wakanday.org/wp-content/uploads/2011/09/Crockford-
  JavaScript-Misunderstood.pdf


 http://www.youtube.com/watch?v=v2ifWcnQs6M
 http://www.youtube.com/watch?v=hQVTIJBZook

 http://www.youtube.com/user/yuilibrary
 http://www.youtube.com/user/ChromeDevelopers
 http://www.youtube.com/user/jeresig

Weitere ähnliche Inhalte

Mehr von Sebastian Pederiva

Mehr von Sebastian Pederiva (6)

ECMAScript 2015
ECMAScript 2015ECMAScript 2015
ECMAScript 2015
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React Together
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Tips for Angular Applications
Tips for Angular ApplicationsTips for Angular Applications
Tips for Angular Applications
 
Sencha Touch
Sencha TouchSencha Touch
Sencha Touch
 
HTML5 Graphics
HTML5 GraphicsHTML5 Graphics
HTML5 Graphics
 

Java script best practices

  • 1.
  • 2. “JavaScript: It is the language that people use without bothering to learn it first” Douglas Crockford
  • 4. Use ‘===‘ instead of ‘==‘  However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully. var x = 1, y = "1"; console.log(x == y); //true console.log(x === y); //false var x, y = null; console.log(x == y); //true console.log(x === y); //false var x = ["", null, undefined]; console.log(x == ",,"); //true console.log(x === ",,"); //false
  • 5. Eval is Bad  Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it! var func = { method: function () { console.log('test'); } }; var whatToDo = "method"; //Static func.method(); //Dynamic - DON'T USE eval("func." + whatToDo + "()"); //Dynamic - This is the right way func[whatToDo]();
  • 6. Don’t declare global variables  “By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.“ Douglas Crockford var DudeNameSpace = { name : 'Jeffrey', lastName : 'Way', doSomething : function() {...} } console.log(DudeNameSpace.name);
  • 7. Always declare your variables using var  If you declare a variable, without using "var", the variable always becomes GLOBAL. function test(){ name = "Jean"; //this is global } test(); console.log(name) // “Jean”
  • 8. Declare Variables on top  variables should be declared on top of each function because of what is known as JavaScript Hoisting var name = 'sarfraz'; function test(){ console.log(name); var name = 'nawaz'; console.log(name); } ​test();​
  • 9. Declare Variables Outside of the For Statement  When executing lengthy “for” statements, don’t make the engine work any harder than it must. var someArray = [1, 2, 3, 4]; for (var i = 0; i < someArray.length; i++) { var container = "what"; console.log(i); } var names = ['George','Ringo','Paul','John']; for(var i=0,j=names.length;i<j;i++){ doSomeThingWith(names[i]); }
  • 10. String Concatenation…  Not easy to decide… var str = ""; for (var i = 30000; i > 0; i--) { str += "String concatenation. "; } var str = "", sArr = []; for (var i = 30000; i > 0; i--) { sArr[i] = "String concatenation. "; } str = sArr.join(""); var str = ""; for (var i = 30000; i > 0; i--) { str = str.concat("String concatenation. "); }
  • 11. String Concatenation (cont.)  http://jsperf.com/javascript-string-concatenation
  • 12. Use [] Instead of New Array()  "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 var a = new Array(); a[0] = "Joe"; a[1] = 'Plumber'; var a = ['Joe','Plumber'];
  • 13. "For in" Statements  When looping through items in an object, you might find that you'll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information  Don’t use “for in” to loop a array – slow performance for(key in object) { if(object.hasOwnProperty(key) { ...then do something... } }
  • 14. Use SetTimeOut instead SetInterval  SetInterval will execute the code every [x] milliseconds no matter what. window.setInterval(function() { ajax_Call(); }, 500); setTimeout(function foo() { call_Ajax(y, function() { if (++y < 10) { setTimeout(foo, 100); } }); }, 100);
  • 15. Starting Curly Brace On The Same Line  That's one of the pitfalls of javascript: automatic semicolon insertion function myFunc() { return; { name: 'sarfraz' }; } var f = myFunc(); console.log(f); <--- ???
  • 16. Don't use try-catch-finally inside performance- critical functions  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.  Exception handling should be done at as high level in the script where it does not occur frequently, for example outside a loop.  Or if possible, avoid try-catch-finally completely var object = ['foo', 'bar'], i; for (i = 0; i < object.length; i++) { try { // do something that throws an exception } catch (e) { // handle exception } } var object = ['foo', 'bar'], i; try { for (i = 0; i < object.length; i++) { // do something } } catch (e) { // handle exception }
  • 17. new  The new operator is required when calling a Constructor function.  If new is omitted, the global object is clobbered by the constructor.  There is no compile-time or run-time warning. ​var x = function(){ alert(this); } var y = x(); //Window Object var z = new x(); //x Object
  • 18. Debugging console.log( firstVariable, secondVariable, xVariable); console.clear();
  • 19. Function Declaration vs. Function Expression  The function_expression form indicates that function are first-class objects, you can do anything with them like a variable.  The only difference between them is that all function declarations are hoisted to the top of the scope which may matter in certain cases. function function_declaration() { … }​ var function_expression = function() { ... }
  • 20. Comment as much as needed but not more  It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible.  Comments don’t hurt anybody if you do them right. We’ll come back to that in the last point of this article, but let’s say that if your comments end up in the code that end users see then something is not going right. // Cycle through array and echo out each name. for(var i = 0, len = array.length; i < len; i++) { console.log(array[i]); }
  • 22. Cache values  Notice how we must determine the length of the array for each iteration, and how we traverse the DOM to find the "container" element each time -- highly inefficient! for(var i = 0; i < someArray.length; i++) { … } var $myDiv = $("#myDiv"); $myDiv.css("color","red"); $myDiv.css("opacity",1);
  • 23. Self-Executing Functions  Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function. (function doSomething() { return { name: 'jeff', lastName: 'way' }; })();
  • 24. Modularize — one function per task  This is a general programming best practice — making sure that you create functions that fulfill one job at a time makes it easy for other developers to debug and change your code without having to scan through all the code to work out what code block performs what function. function addLink(text,url,parentElement){ var newLink = document.createElement('a'); newLink.setAttribute('href',url); newLink.appendChild(document.createTextNode(text)); if(parentElement.id === 'menu'){ newLink.className = 'menu-item'; } if(url.indexOf('mailto:')!==-1){ newLink.className = 'mail'; } parentElement.appendChild(newLink); }
  • 25. Separate config data function validate(value) { if (!value) { alert("Invalid value"); location.href = "/errors/error.php"; } } var config = { urls: { invalid: "/errors/invalid.php" }, strs: { invalidmsg: "Invalid value" } }; function validate(value) { if (!value) { alert(config.strs.invalidmsg); location.href = config.urls.invalid; } }
  • 26. Module Pattern  Designate a single namespace for your application var App = (function () { 'use strict'; var settings; return { (function (app) { init: function(initialSettings){ // Private methods: settings = initialSettings; function find(query) { }, // Perform search } function verifyQuery(query) { getVersion: function (){ // Verify query return settings.version; } } // Public methods: app.search = { }; find: find, verifyQuery: verifyQuery }()); }; }(App));
  • 27. ECMA5
  • 28. Use 'use strict'  Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context.  This strict context prevents certain actions from being taken and throws more exceptions (generally providing the user with more information and a tapered-down coding experience).  Strict mode helps out in a couple ways:  It catches some common coding bloopers, throwing exceptions.  It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).  It disables features that are confusing or poorly thought out. function imStrict(){ "use strict"; myVar = “test” // thrown exception }
  • 29. Use JSON object  JSON is syntax for storing and exchanging text information  JSON is smaller than XML, and faster and easier to parse. var response = JSON.parse(xhr.responseText); console.log(response.email);
  • 31. Is jQuery your friend?  http://jsperf.com/id-vs-class-vs-tag-selectors
  • 32. Don’t Mix Js And Html  One of the most important best practices is to always separate JS code from HTML and go unobtrusive <a href="#" onclick="doSomething()"> Some Action </a> <a href="#" id="link">Some Action</a> <script type="text/javascript"> var link = document.getElementById('link'); link.addEventListener(“click”, function(){ // do something }, false);
  • 33. Scripts at the Bottom of Your Page or use “async” or “defer”  If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.  Async: Specifies that the script is executed asynchronously (only for external scripts)  Defer: Specifies that the script is executed when the page has finished parsing (only for external scripts)
  • 35. Utilize JS Lint  “JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
  • 36. Unit Testing  http://coding.smashingmagazine.com/2012/06/27/intr oduction-to-javascript-unit-testing/  http://stackoverflow.com/questions/300855/looking- for-a-better-javascript-unit-test-tool  Qunit  Jasmine  Other???  http://docs.jquery.com/Qunit  http://qunitjs.com/cookbook/  https://github.com/pivotal/jasmine/
  • 39. Tiny Tips  Use Developer Tool - Chrome  JavaScript Profiling  Do more with Chrome Developer Tools  JavaScript Errors Notifier
  • 40. Read…Read…Read…  http://javascript.crockford.com/  http://ejohn.org/blog  http://paulirish.com/category/javascript/  http://dsheiko.com/weblog/learning-javascript-from-the-code  http://www.slideshare.net/toddanglin/5-tips-for-better-javascript  http://2011.wakanday.org/wp-content/uploads/2011/09/Crockford- JavaScript-Misunderstood.pdf  http://www.youtube.com/watch?v=v2ifWcnQs6M  http://www.youtube.com/watch?v=hQVTIJBZook  http://www.youtube.com/user/yuilibrary  http://www.youtube.com/user/ChromeDevelopers  http://www.youtube.com/user/jeresig

Hinweis der Redaktion

  1. http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/
  2. http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/
  3. http://sarfraznawaz.wordpress.com/2012/02/19/842/