SlideShare a Scribd company logo
JS Best Practices
Created by Johannes Hoppe
My Goal
Higher code qualitiy. Pragmatic solutions.
             No fancy stuff.
Know Your
 MS Tools
Visual Studio 2010/2012
JScript Editor Extensions
Resharper 7.1
JSHint
Chutzpah
Firebug / F12
Know the
 pitfalls
Implied globals
               Forgetting var

vrfo=fnto( {
 a o   ucin)
   br=1
   a   ;
};
Boolean type conversion
         To Truthy or to Falsy. That is the only question!

vre =dcmn.eEeetyd'osnteit)
a l   ouetgtlmnBI(de_o_xs';

i(l= fle {
 fe = as)
   aet"hud' w seti msae!)
   lr(solnt e e hs esg?";
}
Trailing comma
            works on my machine!

vrfo={
 a o
   br "a"
   a: br,
   bz "a"
   a: bz,
};
Return undefined
             señor developers wear mustaches




                       {
vrfo=fnto( {
 a o    ucin)
   rtr
    eun
   {
      x:"ok lk C nw"
         los ie # o!
   };
}
Associative arrays
             they don't exist

vrx=[;
a    ]
x'o' ="a"
[fo]   br;
try .. catch .. finally
                 who cares about the reason?

vrfo=fnto( {
 a o     ucin)
   ty{
    r
      dCaytf;
       orzSuf
   }cth(){
      ac e
       rtr fle
       eun as;
   }
   rtr tu;
    eun re
};
for .. in
                 use a framework

vrdt ={
 a aa
   fo "h,
   o: o"
   br "y
   a: m"
}

fr(a di dt){
 o vr  n aa
   cnoelgdt[];
   osl.o(aad)
}
for .. in
           & never touch Object.prototype

 Ojc.rttp.eAohrotig=fnto( {
  betpooyeytnteTSrn  ucin)
   rtr "o"
   eun gd;
}
Hoisting
                declare upfront all variables

vrfo="lbl;
 a o goa"

vrbr=fnto( {
 a a   ucin)
   aetfo;
   lr(o)
   vrfo="oa"
   a o   lcl;
   aetfo;
   lr(o)
};
Eval
               ... and the job is done

fnto poMnJoPre(et {
 ucin orassnasrtx)
   rtr ea(( +tx +"";
   eun vl""  et   ))
}

vrtx ='{"el":"ol"}'
a et     hlo  wrd  ;
vrjo =poMnJoPre(et;
a sn  orassnasrtx)
Eval is evil!
                Never ever!

vrtx ='fnto( {aet"akd";}('
a et   ucin)   lr(hce!) ) ;
Globals
             the mother of all antipatterns

fnto fo){
 ucin o(
   rtr "a"
   eun br;
}

cnoelgti[fo]);
osl.o(hs'o'()
Every time you clutter the global namespace,
somewhere in the world a helpless kitten dies!
Pretty Code
Coding conventions
 1.   intentation (4 spaces!)
 2.   curly braces everywhere
 3.   semicolons everywhere
 4.   constructor functions: UpperCamelCase
 5.   all other: lowerCamelCase
Globals
          reduce, minimize, delete or kill them

(ucin){"t? }(;
fnto(   wf" ))
The switch-case
         syndrome
               a functional language wants functions!

sic (oehn){
wth smtig

    cs 1
    ae :
      dFrt)
       ois(;
      bek
       ra;

    cs 2
    ae :
      dScn(;
       oeod)
      bek
       ra;

    cs 3
    ae :
      dTid)
       ohr(;
      bek
       ra;
}
Lookup tables
            avoid the switch-case syndrome

vrmtos={
 a ehd
   1 dFrt
    : ois,
   2 dScn,
    : oeod
   3 dTid
    : ohr
};
i (ehd[oehn] {
 f mtossmtig)
   mtossmtig(;
    ehd[oehn])
}
Inheritance
       favour composition over inheritance (FCoI)



“ Because inheritance exposes a subclass
to details of its parent's implementation,
  it's often said that 'inheritance breaks
              encapsulation'. ”
                                                    (Gang of Four 1995:19)
Revealing Module
            Pattern
vrmRvaigoue=fnto ( {
a yeelnMdl   ucin )

    vr_ae="oans;
    a nm  Jhne"

    fnto getns){
     ucin reig(
       cnoelg"el "+_ae;
       osl.o(Hlo    nm)
    }

    fnto staenm){
     ucin eNm(ae
       _ae=nm;
       nm  ae
    }

   rtr {
    eun
      stae stae
      eNm: eNm,
      getns getns
      reig: reig
   };
})
(;

» Documentation
Modul loaders
                 use AMD (require.js)

dfn(ts' [jur',fnto( {
eie'et, 'qey] ucin)

     rtr {
      eun
        syoehn :fnto( {aet"el!) }
        aSmtig   ucin)  lr(hlo";
     }
};
)

rqie[ts',fnto(){
eur('et] ucint
   tsyoehn(;
   .aSmtig)
};
)
Events
              Publish/Subscribe Pattern

vr$vns=${)
a eet   (};

$vnsbn(smtigapn' fnto( {
eet.id'oehnHpes, ucin)
   aet"oehn hpee!)
   lr(Smtig apnd";
};
)

$vnstigr'oehnHpes)
eet.rge(smtigapn';
TDD with Jasmine
Why Jasmine?
              similar to JSpec or RSpec,
 BDD-style    created by authors of jsUnit and Screw.Unit

              from any browser, DOM,
independent   framework or host language

              into continuous build systems
integrates
Jasmine Bootstrap
<DCYEhm>
!OTP tl
<tl
hm>
<ed
ha>
  <il>amn Se Rne<tte
   tteJsie pc unr/il>

  <ikrl"tlset he=lbjsie131jsiecs /
   ln e=syehe" rf"i/amn-../amn.s" >
  <citsc"i/amn-../amn.s>/cit
   srp r=lbjsie131jsiej"<srp>
  <citsc"i/amn-../amn-tlj"<srp>
   srp r=lbjsie131jsiehm.s>/cit

  <- icuesuc flshr..->
   !- nld ore ie ee. -
  <citsc"r/lyrj"<srp>
   srp r=scPae.s>/cit
  <citsc"r/ogj"<srp>
   srp r=scSn.s>/cit

  <- icuese flshr..->
   !- nld pc ie ee. -
  <citsc"pcSeHle.s>/cit
   srp r=se/pceprj"<srp>
  <citsc"pcPaeSe.s>/cit
   srp r=se/lyrpcj"<srp>

  <cit
   srp>

    (ucin( {
     fnto )

      vrhmRpre =nwjsieHmRpre(;
       a tleotr  e amn.tleotr)
      vrjsien =jsiegtn(;
       a amnEv  amn.eEv)

      jsien.dRpre(tleotr;
       amnEvadeotrhmRpre)
      jsien.pcitr=fnto (pc {
       amnEvseFle    ucin se)
         rtr hmRpre.pcitrse)
          eun tleotrseFle(pc;
      };

      vrcretidwnod=wno.nod
       a urnWnoOla  idwola;

      wno.nod=fnto ( {
       idwola ucin )
Output
Jsie131rvso 15561
 amn .. eiin 34593                     fnse i 008
                                        iihd n .1s

•••••

Psig5ses
 asn  pc                                 N tycth
                                          o r/ac

Pae
 lyr
  sol b al t pa aSn
   hud e be o ly  og

 we sn hsbe pue
  hn og a  en asd
   sol idct ta tesn i cretypue
    hud niae ht h  og s urnl  asd
   sol b psil t rsm
    hud e osbe o eue
 tlstecretsn i teue hsmd i afvrt
  el  h  urn og f h  sr a ae t  aoie

 #eue
  rsm
   sol trwa ecpini sn i araypaig
    hud ho n xeto f og s led lyn
Hello World
vrhlool =fnto( {
 a elWrd   ucin)
   rtr "el Wrd"
   eun Hlo ol!;
};

dsrb(hlool' fnto( {
ecie'elWrd, ucin)
  i(sy hlo,fnto( {
  t'as el' ucin)

          epc(elWrd).oqa(HloWrd";
          xethlool()tEul"el ol!)
     };
     )
};
)

jsiegtn(.xct(;
amn.eEv)eeue)

                             hint: press F12 and paste this code!
Matchers
epc()tEuly;
xetx.oqa()
epc()tB()
xetx.oey;
epc()tMthpten;
xetx.oac(atr)
epc()tBDfnd)
xetx.oeeie(;
epc()tBUdfnd)
xetx.oeneie(;
epc()tBNl(;
xetx.oeul)
epc()tBTuh(;
xetx.oerty)
epc()tBFly)
xetx.oeas(;
epc()tCnany;
xetx.ooti()
epc()tBLsTa()
xetx.oeeshny;
epc()tBGetrhny;
xetx.oeraeTa()
epc(ucin)f(;)tTrwe;
xetfnto({n)}.oho()
Own matchers
bfrEc(ucin( {
eoeahfnto )
   ti.dMthr(
   hsadaces{
      iAa:fnto ( {
       sCt ucin )
        rtr ti.culiFuf( & ti.culiLz(;
         eun hsata.slfy) & hsata.say)
      }
   };
   )
};
)

dsrb(Gril' fnto ( {
ecie'afed, ucin )
   i(i act,fnto ( {
   t's   a' ucin )
      epc(e Gril()iAa(;
      xetnw afed).sCt)
   };
   )
};
)

» Documentation
Test-Driven Development
                                     1.   Write your tests
                                     2.   Watch them fail
                                     3.   Make them pass
                                     4.   Refactor
                                     5.   Repeat


 see   Growing Object-Oriented Software, Guidedorby Tests , page 6
 see   Working Effectively with Legacy Code , page 62 many other
1. Write your test
dsrb(svFra" fnto ( {
ecie"aeomt, ucin )

     vroiia ='0 -{}-{};
     a rgnl   {}  1 2'

     i(sol rpaepaeodr" fnto ( {
     t"hud elc lchles, ucin )
        vrepce =' -B-C;
        a xetd   A   '
        vrfrae =svFra(rgnl '' '' '';
        a omtd   aeomtoiia, A, B, C)
        epc(omtd.oqa(xetd;
        xetfrae)tEulepce)
     };
     )

     i(sol ecd ijce cnet,fnto ( {
     t"hud noe netd otn" ucin )
        vrepce =' -&tbg;ETl;bg;-C;
        a xetd   A  l;&tTS&t/&t   '
        vrfrae =svFra(rgnl '' 'bTS<b' '';
        a omtd   aeomtoiia, A, <>ET/>, C)
        epc(omtd.oqa(xetd;
        xetfrae)tEulepce)
     };
     )
};
)
2. Watch them fail
vrsvFra =fnto( {
 a aeomt   ucin)
   rtr "o!;
   eun bo"
};
jsiegtn(.xct(;
 amn.eEv)eeue)

Demo
3. Make them pass
vrsvFra =fnto(x){
a aeomt   ucintt

   $agmns.ahfnto (,ie){
   (ruet)ec(ucin i tm
      i ( >0 {
       f i   )
         ie =((<i/'.etie)hm()
          tm    $'dv>)tx(tm.tl);
         tt=ttrpae""+( -1 +"" ie)
          x    x.elc({   i )  }, tm;
      }
   };
   )
   rtr tt
   eun x;
};
jsiegtn(.xct(;
 amn.eEv)eeue)

Demo
4. Refactor
fnto hmEcd(nu){
 ucin tlnoeipt
   rtr ((<i/'.etipt.tl);
   eun $'dv>)tx(nu)hm()
}

vrsvFra =fnto(x){
a aeomt   ucintt

   $ec(ruet,fnto (,ie){
   .ahagmns ucin i tm
      i ( >0 {
       f i   )
         ie =hmEcd(tm;
          tm    tlnoeie)
         tt=ttrpae""+( -1 +"" ie)
          x    x.elc({   i ) }, tm;
      }
   };
   )
   rtr tt
   eun x;
};
jsiegtn(.xct(;
 amn.eEv)eeue)

Demo
5. Repeat
fnto hmEcd(nu){
 ucin tlnoeipt
   rtr ((<i/'.etipt.tl);
   eun $'dv>)tx(nu)hm()
}

vrsvFra =fnto( {
a aeomt   ucin)

   vrag =Arypooyesiecl(ruet)
   a rs   ra.rttp.lc.alagmns;
   vrtt=ag.hf(;
   a x   rssit)

   $ec(rs fnto (,ie){
   .ahag, ucin i tm
      ie =hmEcd(tm;
      tm   tlnoeie)
      tt=ttrpae""+i+"" ie)
      x   x.elc({    }, tm;
   };
   )
   rtr tt
   eun x;
};
jsiegtn(.xct(;
 amn.eEv)eeue)

Demo
Testing HTML
        Jasmine is DOM agnostic
comes without tools to set up HTML fixtures


                                                             Definition:
                              A test fixture is a fixed state of a set of
                           objects used as a baseline for running tests.
First Solution
            in memory fixture with jQuery

dsrb(tiiljur pui' fnto ( {
ecie'rva Qey lgn, ucin )

  vrfxue
  a itr;
  bfrEc(ucin( {
  eoeahfnto )
     fxue=$'dvsm HM cd hr<dv';
     itr  (<i>oe TL oe ee/i>)
  };
  )

  i(sol d smtig,fnto ( {
  t'hud o oehn' ucin )
     fxuemPui(;
     itr.ylgn)
     epc(itr)tHvCas"eCas)
     xetfxue.oaels(nwls";
  };
  )
};
)
jsiegtn(.xct(;
amn.eEv)eeue)

            ... only works for trivial plugins!
Clumsy Solution
           directly append to/remove from DOM

dsrb(m jur pui' fnto ( {
ecie'y Qey lgn, ucin )

  bfrEc(ucin( {
  eoeahfnto )
     $'fxue)rmv(;
     (#itr'.eoe)
     $'oy)apn(<i i=fxue>TL/i>)
     (bd'.ped'dv d"itr"HM<dv';
  };
  )

  i(sol d smtig,fnto ( {
  t'hud o oehn' ucin )
     $'fxue)mPui(;
     (#itr'.ylgn)
     epc((#itr')tHvCas"eCas)
     xet$'fxue).oaels(nwls";
  };
  )
};
)
jsiegtn(.xct(;
amn.eEv)eeue)
jasmine-jquery
         custom matchers , HTML/style/JSON fixtures, event spies

dsrb(m jur pui' fnto ( {
ecie'y Qey lgn, ucin )

  bfrEc(ucin){
   eoeahfnto(
     jsiegtitrs)fxuePt=j/_amn-eojur'
      amn.eFxue(.itrsah's5jsiedm_qey;
     jsiegtitrs)la(jur.ylgnse.tl)
      amn.eFxue(.od'qeymPui.pchm';
  };
   )

  i(sol d smtig,fnto( {
   t'hud o oehn' ucin)

       vr$i =$'hlool'.ylgn)
        a dv (#elWrd)mPui(;
       epc(dv.oaels(nwls";
        xet$i)tHvCas"eCas)
  };
   )
};
)
jsiegtn(.xct(;
amn.eEv)eeue)

Demo
TDD → BDD
Spies
                           test behaviour

dsrb(Gril' fnto ( {
ecie'afed, ucin )
  dsrb(we tl t b nc' fnto( {
   ecie'hn od o e ie, ucin)

       vrgril;
        a afed
       bfrEc(ucin){
        eoeahfnto(
          gril =nwGril(;
           afed  e afed)
          syngril,'oordenEtiz'.nClTruh)
           pO(afed gTFigAdaPza)adalhog(;
       };
        )

       i(sol ase wt o' fnto( {
        t'hud nwr ih k, ucin)
          vrase =gril.eie)
           a nwr  afedbNc(;
          epc(nwr.oqa(o";
           xetase)tEul"k)
       };
        )

       i(sol selpza,fnto ( {
        t'hud ta iz' ucin )
          gril.eie)
           afedbNc(;
          epc(afedgTFigAdaPza.oaeenald)
           xetgril.oordenEtiz)tHvBeCle(;
       };
        )
   };
    )
};
)
jsiegtn(.xct(;
amn.eEv)eeue)


                                 A spy can stub any function and tracks calls to it and all arguments.



Demo
Danke!

More Related Content

PDF
Asynchronous java script
PDF
Javascript: The Important Bits
PDF
JavaFX, because you're worth it
PDF
Introduction to JavaFX 2
PDF
The State of PHPUnit
PDF
The State of PHPUnit
PPS
Bdd: Tdd and beyond the infinite
PDF
The state of PHPUnit
Asynchronous java script
Javascript: The Important Bits
JavaFX, because you're worth it
Introduction to JavaFX 2
The State of PHPUnit
The State of PHPUnit
Bdd: Tdd and beyond the infinite
The state of PHPUnit

What's hot (20)

PDF
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
PDF
Proxy OOP Pattern in PHP
PDF
Javascript fundamentals for php developers
PPTX
Executable documentation
PDF
Unit testing with PHPUnit
PDF
Lisp
PDF
Something about Golang
PDF
Testing for Unicorns
PPTX
Потоки в перле изнутри
PDF
Hidden Gems of Ruby 1.9
PPTX
What is recursion?
PPTX
Start Writing Groovy
PDF
start_printf: dev/ic/com.c comstart()
PPTX
A Prettier Printer
PPTX
Awesomely descriptive JavaScript with monads
PPTX
AngularJS Testing
KEY
Sbaw091006
PPTX
Os Practical Assignment 1
PDF
The Ring programming language version 1.3 book - Part 17 of 88
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
Proxy OOP Pattern in PHP
Javascript fundamentals for php developers
Executable documentation
Unit testing with PHPUnit
Lisp
Something about Golang
Testing for Unicorns
Потоки в перле изнутри
Hidden Gems of Ruby 1.9
What is recursion?
Start Writing Groovy
start_printf: dev/ic/com.c comstart()
A Prettier Printer
Awesomely descriptive JavaScript with monads
AngularJS Testing
Sbaw091006
Os Practical Assignment 1
The Ring programming language version 1.3 book - Part 17 of 88
Ad

Viewers also liked (6)

PPTX
Javascript best practices
PDF
Java Script Best Practices
PDF
Ten useful JavaScript tips & best practices
PDF
Functional Programming with JavaScript
PDF
Predictive Modelling
PDF
Javascript Best Practices
Javascript best practices
Java Script Best Practices
Ten useful JavaScript tips & best practices
Functional Programming with JavaScript
Predictive Modelling
Javascript Best Practices
Ad

Similar to 2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices (20)

ODP
Clojure made simple - Lightning talk
PDF
JavaScript pitfalls
PDF
Ff to-fp
ODP
Clojure made really really simple
PPTX
Virtual Separation of Concerns (2011 Update)
PDF
DEVCON1 - BooJs
PDF
Tour of language landscape (katsconf)
PDF
Scala Functional Patterns
PDF
452042223-Modern-Fortran-in-practice-pdf.pdf
PDF
Testing outside of the Ruby World
PDF
Martin Chapman: Research Overview, 2017
DOCX
In the Notes on Programming Language Syntax page, an example par.docx
PDF
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
PDF
Data struture and aligorism
PDF
PDF
Emerging Languages: A Tour of the Horizon
PDF
Dimitry Solovyov - The imminent threat of functional programming
PDF
FITC '14 Toronto - Technology, a means to an end
PDF
Technology: A Means to an End with Thibault Imbert
Clojure made simple - Lightning talk
JavaScript pitfalls
Ff to-fp
Clojure made really really simple
Virtual Separation of Concerns (2011 Update)
DEVCON1 - BooJs
Tour of language landscape (katsconf)
Scala Functional Patterns
452042223-Modern-Fortran-in-practice-pdf.pdf
Testing outside of the Ruby World
Martin Chapman: Research Overview, 2017
In the Notes on Programming Language Syntax page, an example par.docx
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
Data struture and aligorism
Emerging Languages: A Tour of the Horizon
Dimitry Solovyov - The imminent threat of functional programming
FITC '14 Toronto - Technology, a means to an end
Technology: A Means to an End with Thibault Imbert

More from Johannes Hoppe (20)

PDF
2017 - NoSQL Vorlesung Mosbach
PPTX
NoSQL - Hands on
PDF
Einführung in Angular 2
PDF
MDC kompakt 2014: Hybride Apps mit Cordova, AngularJS und Ionic
PPTX
2015 02-09 - NoSQL Vorlesung Mosbach
PDF
2012-06-25 - MapReduce auf Azure
PDF
2013-06-25 - HTML5 & JavaScript Security
PDF
2013-06-24 - Software Craftsmanship with JavaScript
PDF
2013-06-15 - Software Craftsmanship mit JavaScript
PDF
2013 05-03 - HTML5 & JavaScript Security
PDF
2013-03-23 - NoSQL Spartakiade
PDF
2013 02-26 - Software Tests with Mongo db
PDF
2012-10-16 - WebTechCon 2012: HTML5 & WebGL
PDF
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
PDF
2012-09-18 - HTML5 & WebGL
PDF
2012-09-17 - WDC12: Node.js & MongoDB
PDF
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
PDF
2012-05-14 NoSQL in .NET - mit Redis und MongoDB
PDF
2012-05-10 - UG Karlsruhe: NoSQL in .NET - mit Redis und MongoDB
PDF
2012-04-12 - AOP .NET UserGroup Niederrhein
2017 - NoSQL Vorlesung Mosbach
NoSQL - Hands on
Einführung in Angular 2
MDC kompakt 2014: Hybride Apps mit Cordova, AngularJS und Ionic
2015 02-09 - NoSQL Vorlesung Mosbach
2012-06-25 - MapReduce auf Azure
2013-06-25 - HTML5 & JavaScript Security
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
2013 05-03 - HTML5 & JavaScript Security
2013-03-23 - NoSQL Spartakiade
2013 02-26 - Software Tests with Mongo db
2012-10-16 - WebTechCon 2012: HTML5 & WebGL
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-09-18 - HTML5 & WebGL
2012-09-17 - WDC12: Node.js & MongoDB
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
2012-05-14 NoSQL in .NET - mit Redis und MongoDB
2012-05-10 - UG Karlsruhe: NoSQL in .NET - mit Redis und MongoDB
2012-04-12 - AOP .NET UserGroup Niederrhein

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
cuic standard and advanced reporting.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
The AUB Centre for AI in Media Proposal.docx
cuic standard and advanced reporting.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Machine learning based COVID-19 study performance prediction
Building Integrated photovoltaic BIPV_UPV.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation theory and applications.pdf
Modernizing your data center with Dell and AMD
Diabetes mellitus diagnosis method based random forest with bat algorithm
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Monthly Chronicles - July 2025

2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices

  • 1. JS Best Practices Created by Johannes Hoppe
  • 2. My Goal Higher code qualitiy. Pragmatic solutions. No fancy stuff.
  • 3. Know Your MS Tools
  • 4. Visual Studio 2010/2012 JScript Editor Extensions Resharper 7.1 JSHint Chutzpah Firebug / F12
  • 6. Implied globals Forgetting var vrfo=fnto( { a o ucin) br=1 a ; };
  • 7. Boolean type conversion To Truthy or to Falsy. That is the only question! vre =dcmn.eEeetyd'osnteit) a l ouetgtlmnBI(de_o_xs'; i(l= fle { fe = as) aet"hud' w seti msae!) lr(solnt e e hs esg?"; }
  • 8. Trailing comma works on my machine! vrfo={ a o br "a" a: br, bz "a" a: bz, };
  • 9. Return undefined señor developers wear mustaches { vrfo=fnto( { a o ucin) rtr eun { x:"ok lk C nw" los ie # o! }; }
  • 10. Associative arrays they don't exist vrx=[; a ] x'o' ="a" [fo] br;
  • 11. try .. catch .. finally who cares about the reason? vrfo=fnto( { a o ucin) ty{ r dCaytf; orzSuf }cth(){ ac e rtr fle eun as; } rtr tu; eun re };
  • 12. for .. in use a framework vrdt ={ a aa fo "h, o: o" br "y a: m" } fr(a di dt){ o vr n aa cnoelgdt[]; osl.o(aad) }
  • 13. for .. in & never touch Object.prototype Ojc.rttp.eAohrotig=fnto( { betpooyeytnteTSrn ucin) rtr "o" eun gd; }
  • 14. Hoisting declare upfront all variables vrfo="lbl; a o goa" vrbr=fnto( { a a ucin) aetfo; lr(o) vrfo="oa" a o lcl; aetfo; lr(o) };
  • 15. Eval ... and the job is done fnto poMnJoPre(et { ucin orassnasrtx) rtr ea(( +tx +""; eun vl"" et )) } vrtx ='{"el":"ol"}' a et hlo wrd ; vrjo =poMnJoPre(et; a sn orassnasrtx)
  • 16. Eval is evil! Never ever! vrtx ='fnto( {aet"akd";}(' a et ucin) lr(hce!) ) ;
  • 17. Globals the mother of all antipatterns fnto fo){ ucin o( rtr "a" eun br; } cnoelgti[fo]); osl.o(hs'o'()
  • 18. Every time you clutter the global namespace, somewhere in the world a helpless kitten dies!
  • 20. Coding conventions 1. intentation (4 spaces!) 2. curly braces everywhere 3. semicolons everywhere 4. constructor functions: UpperCamelCase 5. all other: lowerCamelCase
  • 21. Globals reduce, minimize, delete or kill them (ucin){"t? }(; fnto( wf" ))
  • 22. The switch-case syndrome a functional language wants functions! sic (oehn){ wth smtig cs 1 ae : dFrt) ois(; bek ra; cs 2 ae : dScn(; oeod) bek ra; cs 3 ae : dTid) ohr(; bek ra; }
  • 23. Lookup tables avoid the switch-case syndrome vrmtos={ a ehd 1 dFrt : ois, 2 dScn, : oeod 3 dTid : ohr }; i (ehd[oehn] { f mtossmtig) mtossmtig(; ehd[oehn]) }
  • 24. Inheritance favour composition over inheritance (FCoI) “ Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'. ” (Gang of Four 1995:19)
  • 25. Revealing Module Pattern vrmRvaigoue=fnto ( { a yeelnMdl ucin ) vr_ae="oans; a nm Jhne" fnto getns){ ucin reig( cnoelg"el "+_ae; osl.o(Hlo nm) } fnto staenm){ ucin eNm(ae _ae=nm; nm ae } rtr { eun stae stae eNm: eNm, getns getns reig: reig }; }) (; » Documentation
  • 26. Modul loaders use AMD (require.js) dfn(ts' [jur',fnto( { eie'et, 'qey] ucin) rtr { eun syoehn :fnto( {aet"el!) } aSmtig ucin) lr(hlo"; } }; ) rqie[ts',fnto(){ eur('et] ucint tsyoehn(; .aSmtig) }; )
  • 27. Events Publish/Subscribe Pattern vr$vns=${) a eet (}; $vnsbn(smtigapn' fnto( { eet.id'oehnHpes, ucin) aet"oehn hpee!) lr(Smtig apnd"; }; ) $vnstigr'oehnHpes) eet.rge(smtigapn';
  • 29. Why Jasmine? similar to JSpec or RSpec, BDD-style created by authors of jsUnit and Screw.Unit from any browser, DOM, independent framework or host language into continuous build systems integrates
  • 30. Jasmine Bootstrap <DCYEhm> !OTP tl <tl hm> <ed ha> <il>amn Se Rne<tte tteJsie pc unr/il> <ikrl"tlset he=lbjsie131jsiecs / ln e=syehe" rf"i/amn-../amn.s" > <citsc"i/amn-../amn.s>/cit srp r=lbjsie131jsiej"<srp> <citsc"i/amn-../amn-tlj"<srp> srp r=lbjsie131jsiehm.s>/cit <- icuesuc flshr..-> !- nld ore ie ee. - <citsc"r/lyrj"<srp> srp r=scPae.s>/cit <citsc"r/ogj"<srp> srp r=scSn.s>/cit <- icuese flshr..-> !- nld pc ie ee. - <citsc"pcSeHle.s>/cit srp r=se/pceprj"<srp> <citsc"pcPaeSe.s>/cit srp r=se/lyrpcj"<srp> <cit srp> (ucin( { fnto ) vrhmRpre =nwjsieHmRpre(; a tleotr e amn.tleotr) vrjsien =jsiegtn(; a amnEv amn.eEv) jsien.dRpre(tleotr; amnEvadeotrhmRpre) jsien.pcitr=fnto (pc { amnEvseFle ucin se) rtr hmRpre.pcitrse) eun tleotrseFle(pc; }; vrcretidwnod=wno.nod a urnWnoOla idwola; wno.nod=fnto ( { idwola ucin )
  • 31. Output Jsie131rvso 15561 amn .. eiin 34593 fnse i 008 iihd n .1s ••••• Psig5ses asn pc N tycth o r/ac Pae lyr sol b al t pa aSn hud e be o ly og we sn hsbe pue hn og a en asd sol idct ta tesn i cretypue hud niae ht h og s urnl asd sol b psil t rsm hud e osbe o eue tlstecretsn i teue hsmd i afvrt el h urn og f h sr a ae t aoie #eue rsm sol trwa ecpini sn i araypaig hud ho n xeto f og s led lyn
  • 32. Hello World vrhlool =fnto( { a elWrd ucin) rtr "el Wrd" eun Hlo ol!; }; dsrb(hlool' fnto( { ecie'elWrd, ucin) i(sy hlo,fnto( { t'as el' ucin) epc(elWrd).oqa(HloWrd"; xethlool()tEul"el ol!) }; ) }; ) jsiegtn(.xct(; amn.eEv)eeue) hint: press F12 and paste this code!
  • 34. Own matchers bfrEc(ucin( { eoeahfnto ) ti.dMthr( hsadaces{ iAa:fnto ( { sCt ucin ) rtr ti.culiFuf( & ti.culiLz(; eun hsata.slfy) & hsata.say) } }; ) }; ) dsrb(Gril' fnto ( { ecie'afed, ucin ) i(i act,fnto ( { t's a' ucin ) epc(e Gril()iAa(; xetnw afed).sCt) }; ) }; ) » Documentation
  • 35. Test-Driven Development 1. Write your tests 2. Watch them fail 3. Make them pass 4. Refactor 5. Repeat see Growing Object-Oriented Software, Guidedorby Tests , page 6 see Working Effectively with Legacy Code , page 62 many other
  • 36. 1. Write your test dsrb(svFra" fnto ( { ecie"aeomt, ucin ) vroiia ='0 -{}-{}; a rgnl {} 1 2' i(sol rpaepaeodr" fnto ( { t"hud elc lchles, ucin ) vrepce =' -B-C; a xetd A ' vrfrae =svFra(rgnl '' '' ''; a omtd aeomtoiia, A, B, C) epc(omtd.oqa(xetd; xetfrae)tEulepce) }; ) i(sol ecd ijce cnet,fnto ( { t"hud noe netd otn" ucin ) vrepce =' -&tbg;ETl;bg;-C; a xetd A l;&tTS&t/&t ' vrfrae =svFra(rgnl '' 'bTS<b' ''; a omtd aeomtoiia, A, <>ET/>, C) epc(omtd.oqa(xetd; xetfrae)tEulepce) }; ) }; )
  • 37. 2. Watch them fail vrsvFra =fnto( { a aeomt ucin) rtr "o!; eun bo" }; jsiegtn(.xct(; amn.eEv)eeue) Demo
  • 38. 3. Make them pass vrsvFra =fnto(x){ a aeomt ucintt $agmns.ahfnto (,ie){ (ruet)ec(ucin i tm i ( >0 { f i ) ie =((<i/'.etie)hm() tm $'dv>)tx(tm.tl); tt=ttrpae""+( -1 +"" ie) x x.elc({ i ) }, tm; } }; ) rtr tt eun x; }; jsiegtn(.xct(; amn.eEv)eeue) Demo
  • 39. 4. Refactor fnto hmEcd(nu){ ucin tlnoeipt rtr ((<i/'.etipt.tl); eun $'dv>)tx(nu)hm() } vrsvFra =fnto(x){ a aeomt ucintt $ec(ruet,fnto (,ie){ .ahagmns ucin i tm i ( >0 { f i ) ie =hmEcd(tm; tm tlnoeie) tt=ttrpae""+( -1 +"" ie) x x.elc({ i ) }, tm; } }; ) rtr tt eun x; }; jsiegtn(.xct(; amn.eEv)eeue) Demo
  • 40. 5. Repeat fnto hmEcd(nu){ ucin tlnoeipt rtr ((<i/'.etipt.tl); eun $'dv>)tx(nu)hm() } vrsvFra =fnto( { a aeomt ucin) vrag =Arypooyesiecl(ruet) a rs ra.rttp.lc.alagmns; vrtt=ag.hf(; a x rssit) $ec(rs fnto (,ie){ .ahag, ucin i tm ie =hmEcd(tm; tm tlnoeie) tt=ttrpae""+i+"" ie) x x.elc({ }, tm; }; ) rtr tt eun x; }; jsiegtn(.xct(; amn.eEv)eeue) Demo
  • 41. Testing HTML Jasmine is DOM agnostic comes without tools to set up HTML fixtures Definition: A test fixture is a fixed state of a set of objects used as a baseline for running tests.
  • 42. First Solution in memory fixture with jQuery dsrb(tiiljur pui' fnto ( { ecie'rva Qey lgn, ucin ) vrfxue a itr; bfrEc(ucin( { eoeahfnto ) fxue=$'dvsm HM cd hr<dv'; itr (<i>oe TL oe ee/i>) }; ) i(sol d smtig,fnto ( { t'hud o oehn' ucin ) fxuemPui(; itr.ylgn) epc(itr)tHvCas"eCas) xetfxue.oaels(nwls"; }; ) }; ) jsiegtn(.xct(; amn.eEv)eeue) ... only works for trivial plugins!
  • 43. Clumsy Solution directly append to/remove from DOM dsrb(m jur pui' fnto ( { ecie'y Qey lgn, ucin ) bfrEc(ucin( { eoeahfnto ) $'fxue)rmv(; (#itr'.eoe) $'oy)apn(<i i=fxue>TL/i>) (bd'.ped'dv d"itr"HM<dv'; }; ) i(sol d smtig,fnto ( { t'hud o oehn' ucin ) $'fxue)mPui(; (#itr'.ylgn) epc((#itr')tHvCas"eCas) xet$'fxue).oaels(nwls"; }; ) }; ) jsiegtn(.xct(; amn.eEv)eeue)
  • 44. jasmine-jquery custom matchers , HTML/style/JSON fixtures, event spies dsrb(m jur pui' fnto ( { ecie'y Qey lgn, ucin ) bfrEc(ucin){ eoeahfnto( jsiegtitrs)fxuePt=j/_amn-eojur' amn.eFxue(.itrsah's5jsiedm_qey; jsiegtitrs)la(jur.ylgnse.tl) amn.eFxue(.od'qeymPui.pchm'; }; ) i(sol d smtig,fnto( { t'hud o oehn' ucin) vr$i =$'hlool'.ylgn) a dv (#elWrd)mPui(; epc(dv.oaels(nwls"; xet$i)tHvCas"eCas) }; ) }; ) jsiegtn(.xct(; amn.eEv)eeue) Demo
  • 46. Spies test behaviour dsrb(Gril' fnto ( { ecie'afed, ucin ) dsrb(we tl t b nc' fnto( { ecie'hn od o e ie, ucin) vrgril; a afed bfrEc(ucin){ eoeahfnto( gril =nwGril(; afed e afed) syngril,'oordenEtiz'.nClTruh) pO(afed gTFigAdaPza)adalhog(; }; ) i(sol ase wt o' fnto( { t'hud nwr ih k, ucin) vrase =gril.eie) a nwr afedbNc(; epc(nwr.oqa(o"; xetase)tEul"k) }; ) i(sol selpza,fnto ( { t'hud ta iz' ucin ) gril.eie) afedbNc(; epc(afedgTFigAdaPza.oaeenald) xetgril.oordenEtiz)tHvBeCle(; }; ) }; ) }; ) jsiegtn(.xct(; amn.eEv)eeue) A spy can stub any function and tracks calls to it and all arguments. Demo