Skip to main content
5 Tips
For Better




             @toddanglin
<TODO: HAPPY PLACE IMAGE>
@toddanglin
 Brought to you by @KendoUI
Why
JavaScript?


WHY?!
It‟s the first?
It‟s the best?
It‟s the easiest?
It‟s the fastest?
It‟s everywhere.
No, really.
Brendan Eich.
Netscape.
“JS had to 'look like Java'
  only less so, be Java‟s
dumb kid brother or boy-
 hostage sidekick. Plus, I
   had to be done in ten
days or something worse
    than JS would have
        happened”
:
::
:
Aug 1996
       Microsoft
                     Mar 1999                        Firefox
                      XHR                             Safari
                                                     Chrome
                                                     Mobile
                                     //
Sept 1995
Netscape
                          Aug 2001
                            IE6
              June 1997
             ECMAScript
                                          Feb 2005
                                            Ajax
JavaScript won by
       default.
   If you're the last man left on
 earth, it doesn't matter how ugly
you are when the women come to
       re-populate the planet.

                           Scott Koon
Can‟t Beat „em,
Join „em.
Modern JavaScript
  Faster. Easier. Better.
Attwood‟s Law:
Any application that can be
 written in JavaScript, will
 eventually be written in
         JavaScript
            2007
MOST COMMON PROBLEMS
1. Slow Execution
2. Memory leaks
3. Poor Code Organization
4. Lack of Understanding
5(ISH) TIPS
From real
masters:
  Jordan
   Ivan
Tsvetomir
 Atanas
  Burke
   John
 Brandon
TIP #1
jQuery is a friend…
 …that will stab you in the back.




                                    Prove It
CACHE OBJECTS

                                     BAD
$("#myDiv").css("color","red");
$("#myDiv").css("opacity",1);

                                  BETTER
$("#myDiv").css("color","red")
           .css("opacity",1);

                                    BEST*
var $myDiv = $("#myDiv");
$myDiv.css("color","red");
$myDiv.css("opacity",1);          Prove It
NATIVE LOOPS

                                      BAD
$.each(arr, function (i) {i / 2;});


                                  BETTER
arr.forEach(function (i) {i / 2;});

                                      BEST*
var i = 0, len = arr.length;
for (i = 0; i < len; i += 1) {
   i / 2;
}                                Prove It
TIP #2
Avoid Global Variables
     They're slow & rude.
function add(num1, num2){
            return num1 + num2;
        }

        var result = add(5, 10);    Prove It
16:39
BAD
        var name = "Todd";
        function sayHello(){
           alert(name);
        }

                                BETTER
        function sayHello(){
           var name = "Todd";
           alert(name);
        }



16:39
Closures & Module Pattern
BEST(ISH)
        var app = (function(){
             var _name = "Todd";

            return{
               sayHello: function(){
               alert(_name);
            }
          }
        }());

        app.sayHello();

16:39
SUPER PATTERN
         Self-Executing Anonymous Functions + Global Imports
                             + Prototype


(function(window,$,c){
     var _private = "Todd";
     function privateClass(){}

     function myWidget(){}
     myWidget.prototype.doSomething =
function(){}

     window.myWidget = myWidget;
}(window,jQuery,console);
                                              Prove It
TIP #3
Bind to Events & Pub/Sub
          Just listen.
BAD
        <button id="btn" onclick="sayHello();">
        Click Me
        </button>



                                             BETTER
        $(function(){
           $(“#btn").on("click",sayHello);
        });



16:39
BEST
        $(document).on("click",
                   "button", sayHello);




                        Why?


16:39
UNBINDING EVENTS

$(document).off("click","button");
                 OR
$(document).remove("button");
BAD
        function doSomthing{
           ...
           doSomethingElse();

            doOneMoreThing();
        }




16:39
BETTER
        function doSomething{
           ...
           $.trigger("DO_SOMETHING_DONE");
        }

        $(document).on("DO_SOMETHING_DONE",
           function(){
              doSomethingElse();
           });



16:39
ALSO BETTER
        function doSomething(){
           var dfd = new $.Deferred();

            //Do something async, then...
            //dfd.resolve();

            return dfd.promise();
        }

        function doSomethingElse(){
           $.when(doSomething()).then(//The next
        thing);
        }
16:39
TIP #4
Don't fondle the DOM.
       Go with the flow.
My Awesome Page
               Lorem ipsumy samplish
               jibber jabbish text only
               meant to serve as a
               placeholder, and much like
               Pi, should never repeat or
               be read much beyond the
               first few characters.




            Copyright Fo'eva
BAD
 function doSomething{
    ...
    var $list = $("body").append("<ul>");
    for(var i = 0; i < 10; i++){
       $list.append("<li>"+ i +"</li>")
    }
 }




16:39
BETTER
 function doSomething{
    ...
    var $domChunk = $("<ul>");
    for(var i = 0; i < 10; i += 1){
       $domChunk.append("<li>"+ i +"</li>");
    }
    $("body").append($domChunk);
 }




16:39
DOM SPEED WITH
       STRINGS & INNERHTML
function doSomething{
   ...
   var domString = "<ul>";
   for(var i = 0; i < 10; i += 1){
      domString += "<li>"+ i +"</li>";
   }
   domString += "</ul>"
   $("body")[0].innerHTML = domString;
}
                                    Prove It
BEST
 <script type="text/x-kendo-template" id="tmp">
    <ul>
       #for(var i = 0; i < data.length; i += 1){#
           <li>#= data[i] #</li>
       #}#
    </ul>
 </script>

 function doSomething(){
    var myData = [1,..,10];
    var template = kendo.template($("#tmp").html());
    $("body").append(template(myData));
 }

16:39
                                                Prove It
TIP #5
Learn a module pattern.
        And use it.
PERFORMANCE   CONVENIENCE
Manual (index.html)
A.js
       <script src="B.js"></script>
       <script src="A.js"></script>
       <script src="main.js"></script>


       Module Loader (main.js)
B.js
       require(["A","B"], function(){
           //Dependencies are loaded
       });
USE JSLINT
        Guaranteed to Hurt Your Feelings™


         MINIFY YOUR JS
             Words are for humans.


        MASTER BROWSER
           DEV TOOLS
           Debug JavaScript where it runs.

16:39
Debugging
console.log()
Fix IE
   <script type="text/javascript">
      <!--Console global variable fix for IE-->
      if (!this.console) {
        window.console = {
             log: function() {}
        };
      }
   </script>




16:39
Resources for Study
• Books
        – JavaScript: The Good Parts (Crockford)
        – JavaScript: The Definitive Guide (Flanagan)
        – JavaScript Patterns (Stefanov)
        – High Performance JavaScript (Zakas)




16:39
console.clear();
A&Q

anglin@telerik.com | @toddanglin
       www.KendoUI.com