SlideShare a Scribd company logo
1 of 57
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

More Related Content

What's hot

iFunEngine: 30분 만에 게임 서버 만들기
iFunEngine: 30분 만에 게임 서버 만들기iFunEngine: 30분 만에 게임 서버 만들기
iFunEngine: 30분 만에 게임 서버 만들기iFunFactory Inc.
 
What is the merge window?
What is the merge window?What is the merge window?
What is the merge window?Macpaul Lin
 
Valgrind tutorial
Valgrind tutorialValgrind tutorial
Valgrind tutorialSatabdi Das
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
ElasticSearch at berlinbuzzwords 2010
ElasticSearch at berlinbuzzwords 2010ElasticSearch at berlinbuzzwords 2010
ElasticSearch at berlinbuzzwords 2010Elasticsearch
 
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들DongMin Choi
 
자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012
자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012
자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012Esun Kim
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event LoopDesignveloper
 
온라인 게임과 소셜 게임 서버는 어떻게 다른가?
온라인 게임과 소셜 게임 서버는 어떻게 다른가?온라인 게임과 소셜 게임 서버는 어떻게 다른가?
온라인 게임과 소셜 게임 서버는 어떻게 다른가?Seok-ju Yun
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Android kotlin coroutines
Android kotlin coroutinesAndroid kotlin coroutines
Android kotlin coroutinesBipin Vayalu
 
Python debugging techniques
Python debugging techniquesPython debugging techniques
Python debugging techniquesTuomas Suutari
 
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindBetter Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindRigels Gordani
 

What's hot (20)

Core java
Core javaCore java
Core java
 
Introduction to Eclipse IDE
Introduction to Eclipse IDEIntroduction to Eclipse IDE
Introduction to Eclipse IDE
 
iFunEngine: 30분 만에 게임 서버 만들기
iFunEngine: 30분 만에 게임 서버 만들기iFunEngine: 30분 만에 게임 서버 만들기
iFunEngine: 30분 만에 게임 서버 만들기
 
JQuery UI
JQuery UIJQuery UI
JQuery UI
 
What is the merge window?
What is the merge window?What is the merge window?
What is the merge window?
 
Valgrind tutorial
Valgrind tutorialValgrind tutorial
Valgrind tutorial
 
GraphQL 적용기
GraphQL 적용기GraphQL 적용기
GraphQL 적용기
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
ElasticSearch at berlinbuzzwords 2010
ElasticSearch at berlinbuzzwords 2010ElasticSearch at berlinbuzzwords 2010
ElasticSearch at berlinbuzzwords 2010
 
Express js
Express jsExpress js
Express js
 
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
 
자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012
자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012
자동화된 소스 분석, 처리, 검증을 통한 소스의 불필요한 #if - #endif 제거하기 NDC2012
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
온라인 게임과 소셜 게임 서버는 어떻게 다른가?
온라인 게임과 소셜 게임 서버는 어떻게 다른가?온라인 게임과 소셜 게임 서버는 어떻게 다른가?
온라인 게임과 소셜 게임 서버는 어떻게 다른가?
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Android kotlin coroutines
Android kotlin coroutinesAndroid kotlin coroutines
Android kotlin coroutines
 
Python debugging techniques
Python debugging techniquesPython debugging techniques
Python debugging techniques
 
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindBetter Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
 

Viewers also liked

The Rich Standard: Getting Familiar with HTML5
The Rich Standard: Getting Familiar with HTML5The Rich Standard: Getting Familiar with HTML5
The Rich Standard: Getting Familiar with HTML5Todd Anglin
 
Let’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElementLet’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElementMarian Rusnak
 
High Performance Kick Ass Web Apps (JavaScript edition)
High Performance Kick Ass Web Apps (JavaScript edition)High Performance Kick Ass Web Apps (JavaScript edition)
High Performance Kick Ass Web Apps (JavaScript edition)Stoyan Stefanov
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
JavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a TreeJavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a TreeJenn Lukas
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-frameworkSakthi Bro
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSArmin Vieweg
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework Sakthi Bro
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsVolodymyr Voytyshyn
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocketsametmax
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Languageguestceb98b
 

Viewers also liked (18)

The Rich Standard: Getting Familiar with HTML5
The Rich Standard: Getting Familiar with HTML5The Rich Standard: Getting Familiar with HTML5
The Rich Standard: Getting Familiar with HTML5
 
Let’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElementLet’s talk about JavaScript - WebElement
Let’s talk about JavaScript - WebElement
 
High Performance Kick Ass Web Apps (JavaScript edition)
High Performance Kick Ass Web Apps (JavaScript edition)High Performance Kick Ass Web Apps (JavaScript edition)
High Performance Kick Ass Web Apps (JavaScript edition)
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
JavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a TreeJavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a Tree
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJS
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design Patterns
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 

Similar to 5 Tips for Better JavaScript

Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Peter Higgins
 
Guidelines to clean coding
Guidelines to clean codingGuidelines to clean coding
Guidelines to clean codingJanak Porwal
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done rightPawel Szulc
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDBartłomiej Kiełbasa
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Knowgirish82
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachablePamela Fox
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Defensive programming in Javascript and Node.js
Defensive programming in Javascript and Node.jsDefensive programming in Javascript and Node.js
Defensive programming in Javascript and Node.jsRuben Tan
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tipsanubavam-techkt
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonMLRiza Fahmi
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsMike Hagedorn
 

Similar to 5 Tips for Better JavaScript (20)

JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
Guidelines to clean coding
Guidelines to clean codingGuidelines to clean coding
Guidelines to clean coding
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done right
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More Approachable
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Txjs
TxjsTxjs
Txjs
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Defensive programming in Javascript and Node.js
Defensive programming in Javascript and Node.jsDefensive programming in Javascript and Node.js
Defensive programming in Javascript and Node.js
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 

More from Todd Anglin

NativeScript: Cross-Platform Mobile Apps with JavaScript and Angular
NativeScript: Cross-Platform Mobile Apps with JavaScript and AngularNativeScript: Cross-Platform Mobile Apps with JavaScript and Angular
NativeScript: Cross-Platform Mobile Apps with JavaScript and AngularTodd Anglin
 
Making HTML5 Work Everywhere
Making HTML5 Work EverywhereMaking HTML5 Work Everywhere
Making HTML5 Work EverywhereTodd Anglin
 
Developing a Modern Mobile App Strategy
Developing a Modern Mobile App StrategyDeveloping a Modern Mobile App Strategy
Developing a Modern Mobile App StrategyTodd Anglin
 
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptHTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptTodd Anglin
 
HTML5 Mullet: Forms & Input Validation
HTML5 Mullet: Forms & Input ValidationHTML5 Mullet: Forms & Input Validation
HTML5 Mullet: Forms & Input ValidationTodd Anglin
 
50in50: Resources for HTML5, CSS3, & JavaScript Developers
50in50: Resources for HTML5, CSS3, & JavaScript Developers50in50: Resources for HTML5, CSS3, & JavaScript Developers
50in50: Resources for HTML5, CSS3, & JavaScript DevelopersTodd Anglin
 
Using HTML5 to Build Mobile Apps
Using HTML5 to Build Mobile AppsUsing HTML5 to Build Mobile Apps
Using HTML5 to Build Mobile AppsTodd Anglin
 
HTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use TodayHTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use TodayTodd Anglin
 
HTML5 for Tablets and Mobile
HTML5 for Tablets and MobileHTML5 for Tablets and Mobile
HTML5 for Tablets and MobileTodd Anglin
 
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersAccelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersTodd Anglin
 
Doing More with LESS for CSS
Doing More with LESS for CSSDoing More with LESS for CSS
Doing More with LESS for CSSTodd Anglin
 
Building RESTful Applications with OData
Building RESTful Applications with ODataBuilding RESTful Applications with OData
Building RESTful Applications with ODataTodd Anglin
 
Building a Testable Data Access Layer
Building a Testable Data Access LayerBuilding a Testable Data Access Layer
Building a Testable Data Access LayerTodd Anglin
 
HTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use TodayHTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use TodayTodd Anglin
 
What’s New in ASP.NET 4
What’s New in ASP.NET 4What’s New in ASP.NET 4
What’s New in ASP.NET 4Todd Anglin
 

More from Todd Anglin (16)

NativeScript: Cross-Platform Mobile Apps with JavaScript and Angular
NativeScript: Cross-Platform Mobile Apps with JavaScript and AngularNativeScript: Cross-Platform Mobile Apps with JavaScript and Angular
NativeScript: Cross-Platform Mobile Apps with JavaScript and Angular
 
Edge of the Web
Edge of the WebEdge of the Web
Edge of the Web
 
Making HTML5 Work Everywhere
Making HTML5 Work EverywhereMaking HTML5 Work Everywhere
Making HTML5 Work Everywhere
 
Developing a Modern Mobile App Strategy
Developing a Modern Mobile App StrategyDeveloping a Modern Mobile App Strategy
Developing a Modern Mobile App Strategy
 
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptHTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
 
HTML5 Mullet: Forms & Input Validation
HTML5 Mullet: Forms & Input ValidationHTML5 Mullet: Forms & Input Validation
HTML5 Mullet: Forms & Input Validation
 
50in50: Resources for HTML5, CSS3, & JavaScript Developers
50in50: Resources for HTML5, CSS3, & JavaScript Developers50in50: Resources for HTML5, CSS3, & JavaScript Developers
50in50: Resources for HTML5, CSS3, & JavaScript Developers
 
Using HTML5 to Build Mobile Apps
Using HTML5 to Build Mobile AppsUsing HTML5 to Build Mobile Apps
Using HTML5 to Build Mobile Apps
 
HTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use TodayHTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use Today
 
HTML5 for Tablets and Mobile
HTML5 for Tablets and MobileHTML5 for Tablets and Mobile
HTML5 for Tablets and Mobile
 
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersAccelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
 
Doing More with LESS for CSS
Doing More with LESS for CSSDoing More with LESS for CSS
Doing More with LESS for CSS
 
Building RESTful Applications with OData
Building RESTful Applications with ODataBuilding RESTful Applications with OData
Building RESTful Applications with OData
 
Building a Testable Data Access Layer
Building a Testable Data Access LayerBuilding a Testable Data Access Layer
Building a Testable Data Access Layer
 
HTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use TodayHTML5 and CSS3 Techniques You Can Use Today
HTML5 and CSS3 Techniques You Can Use Today
 
What’s New in ASP.NET 4
What’s New in ASP.NET 4What’s New in ASP.NET 4
What’s New in ASP.NET 4
 

Recently uploaded

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 

5 Tips for Better JavaScript

  • 1. 5 Tips For Better @toddanglin
  • 2.
  • 4. @toddanglin Brought to you by @KendoUI
  • 12. “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”
  • 14. Aug 1996 Microsoft Mar 1999 Firefox XHR Safari Chrome Mobile // Sept 1995 Netscape Aug 2001 IE6 June 1997 ECMAScript Feb 2005 Ajax
  • 15. 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
  • 17. Modern JavaScript Faster. Easier. Better.
  • 18.
  • 19.
  • 20. Attwood‟s Law: Any application that can be written in JavaScript, will eventually be written in JavaScript 2007
  • 22. 1. Slow Execution 2. Memory leaks 3. Poor Code Organization 4. Lack of Understanding
  • 24. From real masters: Jordan Ivan Tsvetomir Atanas Burke John Brandon
  • 25. TIP #1 jQuery is a friend… …that will stab you in the back. Prove It
  • 26. 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
  • 27. 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
  • 28. TIP #2 Avoid Global Variables They're slow & rude.
  • 29. function add(num1, num2){ return num1 + num2; } var result = add(5, 10); Prove It 16:39
  • 30. BAD var name = "Todd"; function sayHello(){ alert(name); } BETTER function sayHello(){ var name = "Todd"; alert(name); } 16:39
  • 31. Closures & Module Pattern
  • 32. BEST(ISH) var app = (function(){ var _name = "Todd"; return{ sayHello: function(){ alert(_name); } } }()); app.sayHello(); 16:39
  • 33. 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
  • 34. TIP #3 Bind to Events & Pub/Sub Just listen.
  • 35. BAD <button id="btn" onclick="sayHello();"> Click Me </button> BETTER $(function(){ $(“#btn").on("click",sayHello); }); 16:39
  • 36. BEST $(document).on("click", "button", sayHello); Why? 16:39
  • 37. UNBINDING EVENTS $(document).off("click","button"); OR $(document).remove("button");
  • 38. BAD function doSomthing{ ... doSomethingElse(); doOneMoreThing(); } 16:39
  • 39. BETTER function doSomething{ ... $.trigger("DO_SOMETHING_DONE"); } $(document).on("DO_SOMETHING_DONE", function(){ doSomethingElse(); }); 16:39
  • 40. 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
  • 41. TIP #4 Don't fondle the DOM. Go with the flow.
  • 42. 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
  • 43. BAD function doSomething{ ... var $list = $("body").append("<ul>"); for(var i = 0; i < 10; i++){ $list.append("<li>"+ i +"</li>") } } 16:39
  • 44. BETTER function doSomething{ ... var $domChunk = $("<ul>"); for(var i = 0; i < 10; i += 1){ $domChunk.append("<li>"+ i +"</li>"); } $("body").append($domChunk); } 16:39
  • 45. 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
  • 46. 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
  • 47. TIP #5 Learn a module pattern. And use it.
  • 48. PERFORMANCE CONVENIENCE
  • 49. 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 });
  • 50. 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
  • 53. Fix IE <script type="text/javascript"> <!--Console global variable fix for IE--> if (!this.console) { window.console = { log: function() {} }; } </script> 16:39
  • 54. Resources for Study • Books – JavaScript: The Good Parts (Crockford) – JavaScript: The Definitive Guide (Flanagan) – JavaScript Patterns (Stefanov) – High Performance JavaScript (Zakas) 16:39
  • 56.

Editor's Notes

  1. 5 Tips for Better JavaScript Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript. You will also learn techniques for testing, debugging, and profiling JavaScript apps.
  2. anglin@telerik.comKendo UI: Everything you need to build sites &amp; mobile apps with HTML and JavaScript (http://www.kendoui.com)
  3. AGENDA:- Why JavaScript? Why?!- Most Common JS Problems- TIPS- Future of JavaScript
  4. JavaScript uses syntax influenced by that of C. JavaScript copies many names and naming conventions from Java, but the two languages are otherwise unrelated and have very different semantics. The key design principles within JavaScript are taken from the Self and Scheme programming languages.http://en.wikipedia.org/wiki/JavaScript
  5. NOTES:HistoryEvolutionThe IE Connection (IE6 memory)Modern JS EnginesBOTTOM LINE: Only Cross Platform Language Solution
  6. Netscape also wanted a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers, like Microsoft&apos;s VB
  7. Credit: Brendan Eich via WikipediaSource: http://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1021Brendan further said that JavaScript saved the world from VBScripthttp://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1049
  8. Java is to JavaScriptASCar is to CarpetNetscape was going to release JavaScript as “LiveScript.” Last minute change produced JavaScript.
  9. HOW DID JAVASCRIPT BECOME UBIQUITOUS?Netscape shipped first in Netscape 2Microsoft support added in IE3 (“JScript”)Other environments adopted JavaScript-like script languages: ActionScript (Flash), PDFs, Qt
  10. http://www.codinghorror.com/blog/2007/05/javascript-the-lingua-franca-of-the-web.html
  11. Contributing factors:New JS engines (V8)CPU speed (more local processing power)Better debugging toolsBetter understanding of language (closures, patterns, functional programming, JSLint)
  12. Chrome is 10x faster than IE7 (IE6 too old to test)Used crude relative test: http://jsbenchmark.celtickane.com
  13. http://geekmontage.com/firefox-vs-chrome-vs-ie/
  14. http://www.codinghorror.com/blog/2007/07/the-principle-of-least-power.htmlThe Principle of Least Power
  15. Jordan Ilchev, Icenium Team LeadIvan Ivanov, Sr DeveloperBurke Holland, Evangelist, Kendo UIJohn Bristowe, Evangelist, Kendo UITsvetomirTsonev, Sr Developer, Kendo UI
  16. jQuery built for convenience, not for performance.PERF PROOF: http://jsperf.com/id-vs-class-vs-tag-selectors/46Note: This in general is applicable to native JavaScript methods too, like document.getElementById()  not limited to jQuery only objects DOM lookups are slow especially if DOM is huge.Instead of this:$(&apos;#test&apos;).bind(&apos;click&apos;, function() { /**/ });$(&apos;#test&apos;).css(&apos;border&apos;, &apos;1px solid #999&apos;);Better use jQuery Method chaining:$(&apos;#test&apos;).bind(&apos;click&apos;, function() {/**/ })                 .css(&apos;border&apos;, &apos;1px solid #999&apos;);Or cache jQuery object:var $test = $(&apos;#test&apos;);$test.bind(&apos;click&apos;, function() {/**/ });$test.css(&apos;border&apos;, &apos;1px solid #999&apos;);(Performance comparison here: http://jsperf.com/jquery-chaining/12) (~+30% here, but it stacks on each additional method call)
  17. PRO TIP CONVENTION: Name jQuery variables with $ (ie $myObject)PERF TEST: http://jsperf.com/caching-jquery-objects-perfhttp://jsbin.com/udizam/2
  18. PERF TEST: http://jsperf.com/for-vs-foreach-vs-each/3- Caching the array length improves perf by about 15% (http://jsperf.com/for-vs-foreach-vs-each/24)- Technically a reverse (count down) for loop is faster (15%) than count-up loop, but much harder to read/use
  19. Global variables pollute the JS app and are slower to use in code. Harder to be a good JS &quot;neighbor&quot; with global variables (collide with other JS code).Better to use local variables, cached variable, or closures
  20. Chart credit: http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.htmlPERF TEST: http://jsperf.com/global/2
  21. Pattern sometimes referred to as: MODULE EXPORThttp://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-DepthBE CAREFUL WITH CLOSURES: Most common source of memory leaks in modern appshttps://developers.google.com/speed/articles/optimizing-javascriptCircular Reference Memory Leaks: http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53028.aspx
  22. PERF TEST: http://jsperf.com/prototype-vs-closures/20Suppose you develop a widget. The widget has a number of axillary classes. If you just define them globally they will pollute the global window class, meaning they will be available from everywhere. Instead consider the following definition:             (function (window) {                        function classA () {}                        function classB () {}                                               function myWidget () {}                        myWidget.prototype.method1 = function ()                        {                        }                                               window.myWidget = myWidget;                                   }) (window, undefined); This is the pattern which jQuery follows. Now the only available global definition will be of myWidget. classA and classB remain hidden in the anonymous function. If you look closely in the definition, you will see the that window and undefined are passed to the anonymous function. Passing anonymous guaranties that undefined will be available in the scope of this function and will prevent you from someone who accidentally did something like: undefined = true; before your function. Also, if you use some minifier, it will replace all occurrences of window with some shorter name. Of course you can pass as much params as you wish, thus assuring that these objects exist in the scope of your anonymous function.
  23. - Binding to delegates is less brittle, easier to avoid memory leaks- Pub/Sub is super flexible, less coupling
  24. The scope of an inline event bind is GLOBAL!Inline event handlers can also cause memory leaks in IE: https://developers.google.com/speed/articles/optimizing-javascript
  25. Old jQuery syntax: .delegate
  26. Every time you need to dispose a DOM element, make sure you unbind all of its events, unless you want to come up with a memory leak.Whenever you bind an event handler to an event, you tell the processor to allocate memory for it. The more event handlers you have running at the same time, the more memory you are using. This is why it&apos;s important to unbind or detach your event handlers soon as you no longer need them.http://www.learnjquery.org/newsletter/Tutorial-3-jquery-events.html
  27. Event listening PUB/SUB
  28. Reducing the time spent changing the DOM improvesperf. Using templates improves readability/maintainability.Instead of this:var $list = $(&apos;#mylist&apos;).append(&apos;&lt;ul&gt;&apos;);for (var i = 0, l = itemlist.length; i &lt; l; i++) {       $list.append(&apos;&lt;li&gt;&apos; + itemlist[i] + &apos;&lt;/li&gt;&apos;);}better this:var $list = $(&apos;&lt;ul&gt;&apos;);for (var i = 0, l = itemlist.length; i &lt; l; i++) {       $list.append(&apos;&lt;li&gt;&apos; + itemlist[i] + &apos;&lt;/li&gt;&apos;);}$(&apos;#mylist&apos;).append($list);(Performance comparison here: http://jsperf.com/jquery-dom-manipulation/3) (up to x5 in this case)
  29. PERF TEST: http://jsperf.com/jquery-dom-manipulation/4When you want to dynamically build html, prefer string concatenation like: var html = ’&lt;p&gt;some paragraph&lt;/p&gt;’;html += ‘&lt;p&gt;another paragraph&lt;/p&gt;’;$(“#placeHolder”).html(html); over DOM object creation and appending/prepending like:             var p1 = document.createElement(&apos;p&apos;);            p1.innerHTML = &quot;some paragraph&quot;;            document.body.appendChild(p1);             var p2 = document.createElement(&apos;p’);            p2.innerHTML = &quot;another paragraph&quot;;            document.body.appendChild(p2);      assigning directly to the innerHTML proves to be the fastest method for html creation.
  30. PERF TEST: http://jsperf.com/jquery-dom-manipulation/5
  31. Common Examples:RequireJS, CommonJSApplications of any size are painful to manage without a module pattern.
  32. We want to reduce JavaScript files for performance (fewer network requests), BUT…One large JS file is hard to maintain. We&apos;d really prefer more modular files.
  33. JSLint – by Douglas CrockfordCode quality tool for JavaScripthttp://www.jslint.com/
  34. More complete fix by Paul Irish: http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/