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

What's hot (20)

PDF
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
Ari Lerner
 
PDF
Proxy OOP Pattern in PHP
Marco Pivetta
 
PDF
Javascript fundamentals for php developers
Chris Ramakers
 
PPTX
Executable documentation
Russell Gold
 
PDF
Unit testing with PHPUnit
ferca_sl
 
PDF
Lisp
Sam Lee
 
PDF
Something about Golang
Anton Arhipov
 
PDF
Testing for Unicorns
Alex Soto
 
PPTX
Потоки в перле изнутри
Ilya Zelenchuk
 
PDF
Hidden Gems of Ruby 1.9
Aaron Patterson
 
PPTX
What is recursion?
AnuragSrivastava272
 
PPTX
Start Writing Groovy
Evgeny Goldin
 
PDF
start_printf: dev/ic/com.c comstart()
Kiwamu Okabe
 
PPTX
A Prettier Printer
jlongster2
 
PPTX
Awesomely descriptive JavaScript with monads
Michal Nowak
 
PPTX
AngularJS Testing
Eyal Vardi
 
KEY
Sbaw091006
Atsushi Tadokoro
 
PPTX
Os Practical Assignment 1
Emmanuel Garcia
 
PDF
The Ring programming language version 1.3 book - Part 17 of 88
Mahmoud Samir Fayed
 
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
Ari Lerner
 
Proxy OOP Pattern in PHP
Marco Pivetta
 
Javascript fundamentals for php developers
Chris Ramakers
 
Executable documentation
Russell Gold
 
Unit testing with PHPUnit
ferca_sl
 
Lisp
Sam Lee
 
Something about Golang
Anton Arhipov
 
Testing for Unicorns
Alex Soto
 
Потоки в перле изнутри
Ilya Zelenchuk
 
Hidden Gems of Ruby 1.9
Aaron Patterson
 
What is recursion?
AnuragSrivastava272
 
Start Writing Groovy
Evgeny Goldin
 
start_printf: dev/ic/com.c comstart()
Kiwamu Okabe
 
A Prettier Printer
jlongster2
 
Awesomely descriptive JavaScript with monads
Michal Nowak
 
AngularJS Testing
Eyal Vardi
 
Sbaw091006
Atsushi Tadokoro
 
Os Practical Assignment 1
Emmanuel Garcia
 
The Ring programming language version 1.3 book - Part 17 of 88
Mahmoud Samir Fayed
 

Viewers also liked (6)

PPTX
Javascript best practices
Manav Gupta
 
PDF
Java Script Best Practices
Enrique Juan de Dios
 
PDF
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
PDF
Functional Programming with JavaScript
WebF
 
PDF
Predictive Modelling
Rajib Kumar De
 
PDF
Javascript Best Practices
Christian Heilmann
 
Javascript best practices
Manav Gupta
 
Java Script Best Practices
Enrique Juan de Dios
 
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Functional Programming with JavaScript
WebF
 
Predictive Modelling
Rajib Kumar De
 
Javascript Best Practices
Christian Heilmann
 
Ad

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

ODP
Clojure made simple - Lightning talk
John Stevenson
 
PDF
JavaScript pitfalls
Claudio Cicali
 
PDF
Ff to-fp
Andy Petrella
 
ODP
Clojure made really really simple
John Stevenson
 
PPTX
Virtual Separation of Concerns (2011 Update)
chk49
 
PDF
DEVCON1 - BooJs
Iván Montes
 
PDF
Tour of language landscape (katsconf)
Yan Cui
 
PDF
Scala Functional Patterns
league
 
PDF
452042223-Modern-Fortran-in-practice-pdf.pdf
kalelboss
 
PDF
Testing outside of the Ruby World
Joseph Wilk
 
PDF
Martin Chapman: Research Overview, 2017
Martin Chapman
 
DOCX
In the Notes on Programming Language Syntax page, an example par.docx
mecklenburgstrelitzh
 
PDF
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
cizekchingbj
 
PDF
Data struture and aligorism
mbadhi barnabas
 
PDF
Dsa book
invertis university
 
PDF
Emerging Languages: A Tour of the Horizon
Alex Payne
 
PDF
Dimitry Solovyov - The imminent threat of functional programming
Dmitry Buzdin
 
PDF
FITC '14 Toronto - Technology, a means to an end
Thibault Imbert
 
PDF
Technology: A Means to an End with Thibault Imbert
FITC
 
Clojure made simple - Lightning talk
John Stevenson
 
JavaScript pitfalls
Claudio Cicali
 
Ff to-fp
Andy Petrella
 
Clojure made really really simple
John Stevenson
 
Virtual Separation of Concerns (2011 Update)
chk49
 
DEVCON1 - BooJs
Iván Montes
 
Tour of language landscape (katsconf)
Yan Cui
 
Scala Functional Patterns
league
 
452042223-Modern-Fortran-in-practice-pdf.pdf
kalelboss
 
Testing outside of the Ruby World
Joseph Wilk
 
Martin Chapman: Research Overview, 2017
Martin Chapman
 
In the Notes on Programming Language Syntax page, an example par.docx
mecklenburgstrelitzh
 
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
cizekchingbj
 
Data struture and aligorism
mbadhi barnabas
 
Emerging Languages: A Tour of the Horizon
Alex Payne
 
Dimitry Solovyov - The imminent threat of functional programming
Dmitry Buzdin
 
FITC '14 Toronto - Technology, a means to an end
Thibault Imbert
 
Technology: A Means to an End with Thibault Imbert
FITC
 
Ad

More from Johannes Hoppe (20)

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

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
July Patch Tuesday
Ivanti
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
July Patch Tuesday
Ivanti
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 

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