Survive JavaScript - Strategies and Tricks


Published on

Getting started with JavaScript can be somewhat challenging. Especially given how fast the scenery changes. In this presentation I provide a general view of the state of the art. Besides this I go through various JavaScript related tricks that I've found useful in practice. is a companion site of the presentation and goes on further detail in various topics.

The original presentation was given at AgileJkl, a local agile conference held in Central Finland.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Survive JavaScript - Strategies and Tricks

  1. 1. Survive JavaScriptStrategiesand TricksJuho VepsäläinenAgileJkl 2013
  2. 2. Whats in Store?Web Development StrategiesJavaScript TricksConclusion·How Did We Get HereWhere Are We NowWhere Are We Headed---·Node.jsDevelopment ToolsStructuring CodeFinding LibrariesTesting-----·
  3. 3. Web Development Strategies
  4. 4. Strategy for GoldfishesSource: (CC BY-NC-ND)
  5. 5. Strategy for the Rest of Us
  6. 6. How Did We Get Here
  7. 7. Ten Days to JavaScript1995 - Brendan Eichs ten days → MochaKnown as LiveScript till the marketing folks changed thenameEven though has Java in name, completely differentInfluence of Java 1.0 visible mainly in Math and TimemodulesPrototypal inheritance a lá SelfDynamic, flexible, lambdasScheme in disguise - See The Little JavaScripter byCrockford·······
  8. 8. A Bit of JavaScriptvarhelloAgileJkl=hello.bind(undefined,AgileJkl!);helloAgileJkl();functionhello(target){console.log(Hello+target);}//orcouldjustconsole.log(HelloAgileJkl!);//toavoidover-engineering!JAVASCRIPT
  9. 9. Web - From Documents to ApplicationsWeb as a Document PlatformImproved InteractivityWeb as an Application Platform·1995 - Brendan Eichs ten days1999 - ES3 (modern baseline), Mozilla established--·2005 - AJAX, dynamic loading (search for instance)2008 - RIP ES4, parts of HTML5 emerge, Chrome (V8)2009 - ES5, Chrome OS, Node.js---·2012 - HTML5 well supported (interesting JS APIs)-Source: Brendan Eich at Strange Loop 12
  10. 10. JavaScript Has TractionSource: Redmonk
  11. 11. CrockfordSource: superfluity (CC BY-NC-SA)
  12. 12. The Good Parts vs. The RestSource: Oльга + Haфaн (CC BY)
  13. 13. RecapJavaScript, an unlikely winnerLanguage of the webMore powerful than it seemsWeb isnt just about documents, now applications too····
  14. 14. Where Are We Now
  15. 15. Elements of Web Applications
  16. 16. Logic
  17. 17. JavaScript
  18. 18. CoffeeScriptCoffeeScript is a little language that compiles into JavaScript. Underneath that awkwardJava-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt toexpose the good parts of JavaScript in a simple way.The golden rule of CoffeeScript is: "Its just JavaScript". The code compiles one-to-one into theequivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript libraryseamlessly from CoffeeScript (and vice-versa). The compiled output is readable and pretty-printed,passes through JavaScript Lint without warnings, will work in every JavaScript runtime, and tendsto run as fast or faster than the equivalent handwritten JavaScript.Latest Version: 1.6.2sudo npm install -g coffee-scriptOverviewCoffeeScript on the left, compiled JavaScript output on the right.# Assignment:number = 42opposite = truevar cubes, list, math, num, number, opposite, race, square,__slice = [].slice;TABLE OF CONTENTS TRY COFFEESCRIPT ANNOTATED SOURCE
  19. 19. Dart(/)Dart brings structure to web appengineering with a new language,libraries, and tools. Read about ournew M4 release!( ( TweetTweetSearch Docs Tools Resources Development
  20. 20. TypeScriptGet TypeScript NowTypeScript is a language for application-scale JavaScript development.TypeScript is a typed superset of JavaScript that compiles to plainJavaScript.Any browser. Any host. Any OS. Open Source.Starts from JavaScript, Ends withJavaScriptTypeScript starts from the syntax and semantics that millions of JavaScript developers knowtoday.learn play get it run it join in
  21. 21. And many othersaltJS
  22. 22. Markup
  23. 23. HTML
  24. 24. Jadedoctype 5html(lang="en")headtitle= pageTitlescript(type=text/javascript)if (foo) {bar()}bodyh1 Jade - node template engine#containerif youAreUsingJade<!DOCTYPE html><html lang="en"><head><title>Jade</title><script type="text/javascript">if (foo) {bar()}</script></head><body><h1>Jade - node template engine</h1>View DocumentationNode Template Engine
  25. 25. Mustache}Logic-less templates.Available in Ruby, JavaScript, Python, Erlang, PHP, Perl, Objective-C, Java, .NET, Android, C++, Go, Lua, ooc, ActionScript, ColdFusion, Scala,Clojure, Fantom, CoffeeScript, D, and for node.js.Works great with TextMate, Vim, Emacs, and Coda.The Manual: mustache(5) and mustache(1)Demo
  26. 26. HandlebarsHandlebars provides the power necessary to let you build semantic templateseffectively with no frustration.Mustache templates are compatible with Handlebars, so you can take a Mustachetemplate, import it into Handlebars, and start taking advantage of the extra Handlebarsfeatures.Download: 1.0.0-rc.3Download: 1.0.0-rc.3Download: runtime-1.0.0-rc.3Getting Started
  27. 27. TransparencyExamplesAssigning valuesAssigning valuesIterating over a listIterating over a listNested listsNested listsNested objectsNested objectsTransparency is a minimal template engine for jQuery. It maps JSONTransparency is a minimal template engine for jQuery. It maps JSONobjects to DOM elements with zero configuration.objects to DOM elements with zero configuration. Just call .render()Just call .render()CoffeeScript JavaScripthello=hello:"Hello!"hi: "<i>Hithere!</i>"span: "Goodbye!"$(.container).renderhelloJade HTML.container#hello.hispan
  28. 28. Styling
  29. 29. CSS
  30. 30. LESSWrite some LESS:@base: #f938ab;.box-shadow(@style, @c) when (iscolor(@c)) {box-shadow: @style @c;-webkit-box-shadow: @style @c;-moz-box-shadow: @style @c;}.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {.box-shadow(@style, rgba(0, 0, 0, @alpha));}.box {color: saturate(@base, 5%);border-color: lighten(@base, 30%);div { .box-shadow(0 0 5px, 30%) }}Compile to CSS:npm install -g lesslessc styles.less styles.cssversion 1.3.3changelogThe dynamic stylesheet language.LESS extends CSS with dynamic behavior such asvariables, mixins, operations and functions.LESS runs on both the server-side (with Node.jsand Rhino) or client-side (modern browsers only).overview   usage   language   function reference   source   about   try it now! FollowFollow
  31. 31. SASS$ gem install sass$ mv style.css style.scss$ sass --watch style.scss:style.cssAbout Tutorial Documentation Blog Try OnlineLatest Release: Media Mark (3.2.7)Whats New?DownloadEditor SupportDevelopmentSass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins,selector inheritance, and more. It’s translated to well-formatted, standard CSS using the commandline tool or a web-framework plugin.Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and isa superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSSfiles use the extension .scss.The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’sterseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets
  32. 32. Twitter BootstrapBootstrap (./index.html)BootstrapSleek, intuitive, and powerful front-endframework for faster and easier webdevelopment.Download Bootstrap (assets/
  33. 33. Zurb FoundationFeatures (grid.php) Add-ons (templates.php) Case Studies (case-jacquelinewest.php) Docs (docs) Training (training.php)Foundation ( most advanced responsivefront-end framework in the world.Download Foundation 4 (download.php)10.9k stargazers(
  34. 34. Data
  35. 35. DataUsually handled with a backend or external services(Disqus for comments for example)RESTful interfaces (client-side MVC)Local caching (localStorage ie.)Offline usage (replication, PouchDB)····
  36. 36. Big DataSource: infocux Technologies (CC BY-NC)
  37. 37. RecapLogics are violetMarkups are blueStyling is sweetAnd so is data
  38. 38. Where Are We Headed
  39. 39. EnlightenmentSource: michael.heiss (CC BY-NC-SA)
  40. 40. Source: Augie Schwer (CC BY-SA)
  41. 41. Source: letmehearyousaydeskomdeskom (CC BY-SA)
  42. 42. Shima thin often tapered piece of material (as wood, metal, orstone) used to fill in space between things (as for support,leveling, or adjustment of fit)Source: Merriam-Webster, esagor (CC BY-NC)
  43. 43. caniuse.comIndex TablesCan I use...Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers.Latest update: Three new features added: Shadow DOM, WebP images & Intrinsic width & height (April 3, 2013)Search:border‑radius, WebGL, woff, etcCSS@font­face Web fontscalc() as CSS unit value2.1 selectorsCountersFeature QueriesFilter EffectsGenerated contentGradientsGrid LayoutHyphenationinline­blockMasksmin/max­width/heightoutlineposition:fixedRegionsHTML5Audio elementCanvas (basic support)Color input typecontenteditable attribute (basic support)Datalist elementdataset & data­* attributesDate/time input typesDetails & Summary elementsDownload attributeDrag and DropForm validationHTML5 form featuresinput placeholder attributeNew semantic elementsNumber input typeOffline web applicationsSVGInline SVG in HTML5SVG (basic support)SVG effects for HTMLSVG filtersSVG fontsSVG fragment identifiersSVG in CSS backgroundsSVG in HTML img elementSVG SMIL animationAll SVG featuresOtherasync attribute for external scriptsTOPSuggestions  Feed  TwitterImport stats FAQ Resources Embed564
  44. 44. Source: T.R.G. (CC BY-NC-SA)
  45. 45. Rise of the Mobile
  46. 46. AndroidSource: San Diego Shooter (CC BY-NC-ND)
  47. 47. Firefox OS, Jolla etc.
  48. 48. Source: Brian LeRoux (CC BY-NC-SA)
  49. 49. Native vs. HTML5Native apps still have their advantagesJS is a good alternative for prototypingAvailable technology keeps maturingAnd well likely see better platform support····
  50. 50. Web Architectures
  51. 51. Blog (Static Site)
  52. 52. JSter (Portal)
  53. 53. Future JSter?
  54. 54. Other ConsiderationsWhat belongs to server, what to client and why (businessgoals)Client-side MVC is not a silver bulletBasecamps experiences (hint: pushState, aggressivecaching)Synchronization, offline usage, skills, time, budget...Fashion. Techs come and goUp and coming? Mixed approaches. Examples: Meteor,Derby, mojito, rendr······
  55. 55. RecapWeb dev is as hard as you make itEspecially on the bleeding edgeFortunately a bit of tape fixes anythingMobile on the rise, native HTML5 apps not mainstream yetWeb architectures - from monoliths to distributed·····
  56. 56. JavaScript Tricks
  57. 57. Node.js
  58. 58. TrendsSource: Google Trends
  59. 59. Packages per YearPython: 29,720 packages / 22 years = 1351 packages / yearRuby: 54,385 packages / 18 years = 3022 packages / yearNode.js: 26,966 packages / 4 years = 6742 packages / year···Source: Gregg Gaines
  60. 60. Server Using Callbacksvarhttp=require(http);http.createServer(function(req,res){res.writeHead(200,{Content-Type:text/plain});res.end(HelloAgileJkl!n);}).listen(8000);JAVASCRIPTShort and sweetExpress is very popular for more complex cases··
  61. 61. Server Using EventStreamsvarhttp=require(http);vars=newhttp.Server();s.on(request,function(req,res){res.writeHead(200,{Content-Type:text/plain});res.end(HelloAgileJkl!n);});s.listen(8000);JAVASCRIPTViable alternative to callbacks at timesMore info at Node.js: Patterns and Opinions by @izs (theNode guy)··
  62. 62. RecapExcellent for prototypingStrong ecosystem thanks to NPMDevelops at a blistering pace···
  63. 63. Development Tools
  64. 64. Vim, Emacs, Sublime Text, WebStorm...
  65. 65. Chrome InspectorSee also Firebug·Source: Chrome DevTools
  66. 66. LiveReloadLiveReload 2 proudly presents…The Web Developer Wonderland(a happy land where browsers dont need a Refresh button)CSS edits and image changes apply live.CoffeeScript, SASS, LESS and others just work.Citizenship is granted through the Mac App Store.Windows permanent residency issues are being worked out,temporary stay already allowed.
  67. 67. JSLintclearRead the instructions.Set the options.Enjoy The Good Parts.Donate.The JavaScript Code Quality ToolEdition 2013-04-09Source// Paste quality code hereSee also JSHint·
  68. 68. jsFiddleRun Save TidyUp JSHint Login/Sign upNo‑Library (pure JS)onLoadTip JSFiddleFrameworks & ExtensionsFiddle OptionsExternal ResourcesLanguagesAjax RequestsExamplesLegal, Credits and LinksGittipKeyboard shortcuts?111HTMLJavaScriptCSSResultOthers: jsbin,, ...·
  69. 69. Cloud9 IDECloud9 IDE - Online IDEGive us a shout out: Share on twitter Share on Google Share on facebook Share on emailSign upSign outUsername or e‑mail Password Sign InKeep me signed inForgot password? Resend activation emailOr sign in instantly with:NEWS: The Changelog of March: Stability, Performance, FeaturesHey there! Over the past month we have worked very hard on improving the stability and performance of our service. In addition, we also worked onsome interface changes the full article | see all articlesPricingFeaturesBlogCompanyCompany•Board Members•Jobs•Press•ContactNode.jsNode.js••NodeManual.orgSupportSupport•Status•DocumentationYour code anywhere, anytime...
  70. 70. RecapTraditional editors and IDEs are fineAdditional tooling available, use itFuture in the web?···
  71. 71. Structuring Code
  72. 72. The Anti-Pattern<scriptsrc=jquery-current.jstype=text/javascript></script><scriptsrc=sorttable.js type=text/javascript></script><scriptsrc=scripts.js type=text/javascript></script><scriptsrc=miniCalendar.js type=text/javascript></script>HTMLEach include has to be defined by handBrittle and prone to error, especially with large codebasesDoes not encourage to modularityHard to reuse····
  73. 73. Concatenate Scripts<scriptsrc=application.jstype=text/javascript></script> HTMLOld skool but worksLess overhead at HTMLStill, running into dependency order problem atconcatenationPossible to complement by loading scripts (ie. jQuery)from a CDNNevertheless a step forward·····
  74. 74. RequireJS and AMD + Bower<scriptdata-main="scripts/main"src="scripts/require.js"></script> HTMLdefine([jquery,./math],function($,math){return{//exportsvector:function(){...}};});JAVASCRIPTModular, asynchronous approachIncludes defineoverhead (possible to mimic Node.jsconvention, though)Optimizer resolves dependencies and creates build(loadable with Almond)Configuration complex at times····
  75. 75. Browserify + NPM<scriptsrc=application.jstype=text/javascript></script> HTMLvar$=require(jquery);varmath=require(./math);exports.vector=function(){...};JAVASCRIPTAllows to use Node.js module convention (CJS)Better yet allows to hook into NPM ecosystem!Still fairly bleeding edge···
  76. 76. RecapNo official module system yet (ES6?)Many alternatives (AMD, CJS etc.)browserify looks promising (NPM!)···
  77. 77. Finding Libraries
  78. 78. NPMSearch PackagesNODE.JS HOMEDOWNLOADABOUTNPM REGISTRYDOCSBLOGCOMMUNITYLOGOSJOBSNode Packaged ModulesTotal Packages: 28 067907 584 downloads in the last day9 157 954 downloads in the last week33 188 669 downloads in the last monthPatches welcome!Any package can be installed by using npminstall.Add your programs to this index by using npmpublish.Recently Updated0m jspmMost Depended Upon2740 underscoreCreate Account | Login
  79. 79. BowerBower componentsDiscover Bower ( out some of my otherprojectsFocus(,JsRun(, sublime-editorconfig(, GitHub-Notifier(, Pure(,quora-unblocker( (https://git…stringify-object (https:/…Featured componentsFullsc…APIwrap…String…anflight-storage (https://gi…spice.css (https://github…Latest componentsStore…JSONdataBasic…dry cssmin.js (…angularjs-ordinal-filter …Hot componentsSuper…mini…select…Angul…Ordinal(
  80. 80. JSwikiJSwiki2 TweetTweet 59EditEditHi there! Welcome to jswiki.This wiki indexes libraries and resources available for JavaScript. In addition it provides some starting pointsfor newbies in form of Beginners Resources. In case you want to contribute, do take a look at Meta first forsome extra pointers. Happy hacking!IMPORTANT! is a spiritual successor of jswiki. There is more content but thesite is less of a wiki. jswiki will remain here as more of a communal alternative. Inaddition you might want to check out the following:JSwikiEssentialsMultimediaGraphicsDataUIUtilitiesDevelopmentApplicationsjsgamewiki MicrojsEveryJS JSDBJSPkg
  81. 81. JSterFollowFollow @jsterlibs@jsterlibsBlogCatalogAdd LibrarySign InFind a Javascript libraryJSter is a catalog of 1095 JavaScript libraries and tools for web development.Problems?Problems?
  82. 82. RecapNo need to just Google itPackage managers (esp. NPM) make your life easierAvoid NIH and use existing solutions···
  83. 83. Testing
  84. 84. Unit Testingassert(title(HELLOWORLD!)===HelloWorld!);assert(title(Helloworld!)===HelloWorld!);assert(title(hi)===Hi);assert(title()===undefined);functiontitle(s){returns&&s.split().map(capitalize).join();}functionassert(s){if(!s)thrownewError(Assertionfailed!);}JAVASCRIPTPopular alternatives: Jasmine (BDD), Mocha, QUnit·
  85. 85. Fuzz Testing//functiontotest,noteannotationvartitle=annotate(title,Returnsgivenstringinatitleformat.).on(is.string,function(s){returns&&s.split().map(capitalize).join();}).satisfies(is.string);//testinganinvariantfuzz(title,function(op,str){varparts=op(str).split();;});JAVASCRIPTUp and coming (hopefully)·Source: bebraw/annofuzz
  86. 86. Testlingtestling-cirun your browser tests on every pushwrite some testsUse the test runner you like best!The only thing your test runner needs to do is to produce TAP outputon console.log or process.stdout. Heres an example project usingmocha.You can also use tape to output TAP output in browsers and in node.Here is what a simple tape test looks like:var test = require(tape);var myCode = require(../my_code.js);test(make sure my code works, function (t) {t.plan(2);t.equal(myCode.beep(5), 555);
  87. 87. Travistravis-ci.orgBlogDocumentationEnglishFrançaisEspañolPortuguêsTravis CIA hosted continuous integration service for the open source community.Welcome to Travis CI #Travis CI is a hosted continuous integration service for the open source community. It is integrated with GitHub and offers first class support for:CC++ClojureErlangGoGroovyHaskellJavaJavaScript (with Node.js)Perl
  88. 88. Browserlinginteractive cross-browser testinghttp://3.0 3.5 3.6 4.0 5.0 6.07.0 8.0 9.0 10.0 11.0 12.013.0 14.0 15.0 16.0 17.0 18.019.0 nightlycreate account sign in
  89. 89. BrowserstackLive, Web-Based Browser TestingInstant access to all desktop and mobile browsers.Say goodbye to your setup of virtual machines and devices.Free TrialSign up for freeFull NameEmailPasswordNo credit cardNo credit cardrequired. We promise.required. We promise.Support Pricing Free TrialResources Sign inLive
  90. 90. Chaos MonkeySource: Jeff Atwood - Working with the Chaos Monkey
  91. 91. AB TestingSource: TheBusyBrain (CC BY)
  92. 92. RecapTest your JSBrowser differences bring their own challengeFuture in continuous integration (Travis and co.)Fail constantly to avoid failure····
  93. 93. Conclusion
  94. 94. ConclusionJS - the most valuable language you dont know yetA target for tool and language developmentNot without its quirks but still manageableThe most important language of this decade?····
  95. 95. Survive JS - The GuideSurvive JSHave you ever felt lost in the JavaScript jungle? If so, you are in the right place. The purpose of this guideis to provide you with sharp implements that help you survive and perhaps thrive even. Even seasonedJavaScript explorers might find a trick or two to apply in practice.As it is very possible I have not reached omnipotence yet, I encourage you to submit issues. This way wecan make the guide to serve you better.I am well aware there are other excellent resources out there. Of these I would like to mention EloquentJavaScript and JavaScript Garden in particular. I have listed various beginners resources over at JSwiki,the predecessor of JSter.Table of ContentsA Misunderstood Language? - What is the essence of JavaScript? Why is it relevant?Current State - What is the current state of JavaScript and the ecosystem?Language Features - What the language looks like? How to use it effectively?EditEditTweetTweet 00Table of ContentsSurvive JS
  96. 96. Thank You!twitter @bebrawwww www.nixtu.infogithub