-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1659 lines (1403 loc) · 64.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>API Days: JavaScript API Workshop</title>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/moon.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Workshop-specific styles -->
<link rel="stylesheet" href="css/custom.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<div id="watermark"></div>
<div class="slides">
<section>
<img src="img/apidays-logo.png" alt="API Days Logo">
<h1>The Nature of JS</h1>
<div>Don Smith (<a href="http://twitter.com/locksmithdon">@locksmithdon</a>)</div>
<div>Rich Churcher (<a href="http://twitter.com/richchurcher">@richchurcher</a>)</div>
</section>
<!-- SECTION 1 -->
<section data-background="img/backgrounds/landscape.jpg">
<h1>JavaScript: the Landscape</h1>
</section>
<section>
<h1>Why JavaScript?</h1>
<aside class="notes" data-markdown>
* JS API consumption predates JS API provision by about 10 years. Asynchronous content loads date from late 90's, term AJAX coined in 2005.
* Server-side JavaScript using Node since 2009
</aside>
</section>
<section data-background="img/backgrounds/monkey_small.jpg">
<h1 class="offset-bottom">Immediacy</h1>
<aside class="notes" data-markdown>
* Supremely easy to get started, essentially zero cost entry point...
* Potentially same developers on front and back end
* Quick design-code-test-debug cycles
</aside>
</section>
<section data-background="img/backgrounds/rhino.jpg">
<h1 class="offset-top">Reliability</h1>
<aside class="notes" data-markdown>
* Infrastructure investments (Google: V8, Microsoft: Chakra)
* Large, mainstream frameworks (Google: Angular, Facebook: React)
* Thriving community (Node.js/IO.js/4.0, and NPM modules)
* As of Oct 2015, over 195K NPM packages
</aside>
</section>
<section data-background="img/backgrounds/baby_koala.jpg">
<h1 class="offset-top">Portability</h1>
<aside class="notes" data-markdown>
* Not only capable of building frontend and backend web, but mobile and desktop
* Blurring lines between browser and native (React Native, Phonegap)
* No longer the wild west: *ES6*
</aside>
</section>
<section data-background="img/backgrounds/ants.jpg">
<h1 class="offset-bottom">Maintainability</h1>
<aside class="notes" data-markdown>
* Simple, well-established mechanisms for sharing and troubleshooting code (REPLs everywhere: jsfiddle.net, jsbin.com, plnkr.io, codepen.io)
* _Lingua franca_ effect: finding JS devs not difficult (quality variable)
* Reasonable debugging tools using the browser and nodemon
* Voracious (and opinionated) community
</aside>
</section>
<section data-background="">
<h1>Why not JavaScript?</h1>
</section>
<section data-background="img/backgrounds/kea_rope.jpg">
<h1 class="offset-bottom">Tooling</h1>
<aside class="notes" data-markdown>
* Even today, with WebStorm, and Visual Studio incorporating JS debugging, still not as good as statically typed languages
* Can be hard to debug, particularly larger code bases
</aside>
</section>
<section data-background="img/backgrounds/flock.jpg">
<h1>Framework churn</h1>
<aside class="notes" data-markdown>
* Makes assessing the correct tool for a particular task more challenging
* May mean poorer documentation, out of date tutorials, lost time
</aside>
</section>
<section data-background="img/wombat.gif">
<h1 class="offset-top">Speed</h1>
<aside class="notes" data-markdown>
* Traditional response to speed concerns around JS is, "processing speed always increases"
* Compared with Go and other compiled backend languages
</aside>
</section>
<section data-background="img/backgrounds/zebras.jpg">
<h1>Regional preference</h1>
<aside class="notes" data-markdown>
* Full-stack JavaScript perhaps less common in New Zealand
- May mean delays in finding developers for support/maintenance, although this is changing
</aside>
</section>
<section data-background="">
<h1>Why Web APIs?</h1>
</section>
<section data-background="img/backgrounds/urchins.jpg">
<h1 class="offset-top">Decoupled</h1>
<aside class="notes" data-markdown>
* UX can be developed independently
* Arbitrary partitioning: microservices or monolithic
* Arbitrary language/stack, everything groks JSON
* Common formats (JSON: .doc for the web?)
* Can be versioned independently
</aside>
</section>
<section data-background="img/backgrounds/giraffe.jpg">
<h1>Expose public data sets</h1>
<aside class="notes" data-markdown>
* Independent of consuming applications
* Consumers at organisational level, paying clients, or open
</aside>
</section>
<section data-background="img/backgrounds/polar.jpg">
<h1>Clear expectations</h1>
<aside class="notes" data-markdown>
* Simple and straight-forward requests response model
* Discovery through HATEOAS Level 3 of the Richardson Maturity Model
- HATEOAS: Hypertext As The Engine Of Application State
* Good debugging tools like Postman
</aside>
</section>
<section data-background="">
<h1>Why not Web APIs?</h1>
<aside class="notes" data-markdown>
* Every request across HTTP has latency
</aside>
</section>
<section>
<h2>Further reading</h2>
<ul>
<li> <a href="http://www.infoworld.com/article/2907190/javascript/javascript-will-lead-a-massive-shift-in-enterprise-development.html">JavaScript will lead a massive shift in enterprise development</a></li>
</ul>
</section>
<!-- SECTION 2 -->
<section data-background="img/backgrounds/night_lake.jpg">
<h1>JavaScript: Surviving in the wild</h1>
</section>
<section data-background="img/backgrounds/chameleon.jpg">
<h1>When is JavaScript... not JavaScript?</h1>
<h2 class="fragment">EcmaScript</h2>
<h2 class="fragment">ES6</h2>
<h2 class="fragment">ES2015</h2>
<aside class="notes" data-markdown>
* JavaScript is the common/generic name of the language.
* EcmaScript refers to the language’s specification.
* ES6 refers to the 6th edition of that spec.
* EcmaScript 2015 is the title of the 6th edition of the spec.
* Yes, we know this is ridiculous, but you will most certainly run across all of these on the web.
* For the purpose of this workshop, we will use _JavaScript_ as much as possible, and _ES6_ when we are referring to a language feature that was added in the latest version of the spec only because it has fewer syllables when pronounced."
* All examples in this workshop assume _strict mode_. Incorporating [Babel](https://babeljs.io) into your workflow will take care of this for you. All _ES6_ modules are in strict mode by default.
</aside>
</section>
<section>
<section>
<h2>Function level scope</h2>
<ul>
<li>Unlike languages with <em>block level scope</em>, in JavaScript blocks do not create their own restricted scope</li>
</ul>
<pre><code class="js">function foo () {
for (var i = 0; i < 10; i++) { }
console.log(i); // 10
}</code></pre>
<ul>
<li>Here, <code>i</code> is available anywhere within <code>foo</code></li>
</ul>
<aside class="notes" data-markdown>
* In the past, was often recommended that `var` statements occur at the beginning of functions to avoid unwelcome surprises caused by this behaviour
* With _ES6_, `var` can largely be replaced by `let`
* https://jsbin.com/memopi/edit?js,console
</aside>
</section>
<section>
<h2><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let"><code>let</code></a> </h2>
<ul>
<li>Restricts scope to its block, statement or expression:</li>
</ul>
<pre><code class="js">function bar () {
for (let i = 0; i < 10; i++) { }
console.log(i); // undefined
}</code></pre>
<aside class="notes" data-markdown>
* https://jsbin.com/warevab/edit?js,console
</aside>
</section>
<section>
<h2><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><code>const</code></a> </h2>
<ul>
<li> Creates a reference to a value that cannot be altered:</li>
</ul>
<pre><code class="js">// TypeError: assignment to constant
function wombat () {
const n = 5;
n++;
}</code></pre>
<aside class="notes" data-markdown>
* https://jsbin.com/jizivi/1/edit?js,console
</aside>
</section>
</section>
<section>
<section>
<h2>Closures</h2>
<ul>
<li> Functions can be declared inside other functions</li>
<li> local variables in the outer function are still available <em>even if the outer function has already returned</em></li>
</ul>
</section>
<section>
<pre><code class="js">function foo() {
let n = 1;
return bar;
function bar() {
// bar "closes over" n
console.log(n++);
}
}
let baz = foo();
baz(); // 1
baz(); // 2
let wombat = foo();
wombat(); // 1
baz(); // 3</code></pre>
<aside class="notes" data-markdown>
* https://jsbin.com/cibibe/1/edit?js,console
</aside>
</section>
<section>
<ul>
<li> Here, <code>n</code> remains "alive" and can be modified after <code>foo</code> exits. </li>
<li> Each call to <code>foo</code> creates a new <em>closure</em>, with its own local copy of <code>n</code>. </li>
</ul>
</section>
</section>
<section>
<section>
<h2><code>this</code></h2>
<ul>
<li>In <em>ES6</em> the value of <code>this</code> is fairly predictable</li>
<li> Watch out for legacy JS, where it can unexpectedly default to the window object and lead to some unintuitive behaviour</li>
<li>Best practice is to <em>be explicit</em></li>
</ul>
<aside class="notes" data-markdown>
* Best practice is to _be explicit_: never assume that the next developer to read your code understands the nuances of `this`
* Think _functionally_: avoid altering global or object level state
</aside>
</section>
<section>
<ul>
<li>Value of <code>this</code> depends on the execution context:</li>
</ul>
<pre><code class="js">// Value of 'this' set to Window object
console.log(this);
function foo () {
console.log(this); // undefined
}
let bar = {
wombat: function () {
// Value of 'this' is the object the
// method is called on: 'bar' in this case
console.log(this);
}
};</code></pre>
</section>
<section>
<ul>
<li><code>this</code> can be tricky when used in event handlers. Generally its value is the DOM element which fired the event:</li>
</ul>
<pre><code class="js">let foo = document.getElementById('foo');
foo.onclick = makeGreen;
function makeGreen() {
// 'this' is the <p> DOM element
this.style.backgroundColor = 'green';
}</code></pre>
</section>
<section>
<ul>
<li>But when a function isn't called as a method of an object...</li>
</ul>
<pre><code class="js">let foo = document.getElementById('foo');
foo.onclick = toggleGreen;
function toggleGreen() {
if (this.style.backgroundColor === 'green') {
makeTransparent();
} else {
makeGreen();
}
}
function makeGreen() {
this.style.backgroundColor = 'green'; // undefined
}
function makeTransparent() {
this.style.backgroundColor = 'transparent'; // undefined
}</code></pre>
</section>
<section>
<ul>
<li>Use of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call"><code>call</code></a> invokes a function with the desired value of <code>this</code>:</li>
</ul>
<pre><code class="js">if (this.style.backgroundColor === 'green') {
makeTransparent.call(this);
}</code></pre>
<ul>
<li>Compare <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"><code>bind</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply"><code>apply</code></a></li>
</ul>
<aside class="notes" data-markdown>
* https://jsbin.com/xirapa/1/edit?js,console,output
* Cross-browser issues (particularly with earlier versions of Internet Explorer) can yield surprising results, with <code>this</code> being set to the global window object.</li>
</ul>
</aside>
</section>
</section>
<section>
<section>
<h2>The object prototype</h2>
<ul>
<li>In JavaScript every object has its own <em>prototype</em></li>
<li>Each prototype has its own prototype, and so on down the chain until <code>null</code> is reached</li>
<li>Properties are first looked for in the object itself (see: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"><code>hasOwnProperty</code></a>) then in its prototype, then in the prototype's prototype, and so on</li>
</ul>
</section>
<section>
<ul>
<li>It's useful to remember the difference between giving one distinct object a property ...</li>
</ul>
<pre><code class="js">let foo = {
aardvarks: function() {
console.log("I see many aardvarks.");
}
};
foo.aardvarks(); // I see many aardvarks</code></pre>
</section>
<section>
<ul>
<li>... and giving all objects created with a particular constructor function access to the property:</li>
</ul>
<pre><code class="js">function AardvarkCounter(n) {
this.count = n;
}
AardvarkCounter.prototype.aardvarks = function() {
console.log(`I see ${this.count} aardvarks.`);
};
let firstCounter = new AardvarkCounter(11);
let secondCounter = new AardvarkCounter(1337);
firstCounter.aardvarks(); // "I see 11 aardvarks."
secondCounter.aardvarks(); // "I see 1337 aardvarks."</code></pre>
<aside class="notes" data-markdown>
* https://jsbin.com/kohese/1/edit?js,console
</aside>
</section>
<section>
<ul>
<li>Functions declared on the prototype are shared between all objects with that prototype</li>
<li>Many libraries include the ability to copy properties from one object to another</li>
<li>For example, using <a href="http://underscorejs.org">Underscore's</a> <a href="http://underscorejs.org/#extend"><code>extend</code></a>:</li>
</ul>
<pre><code class="js">let foo = {
n: 5
};
let bar = {
wombat: function() {
console.log("Wombats: accept no substitute.");
}
};
let combined = _.extend(foo, bar);
combined.wombat();
console.log(combined.n); // 5</code></pre>
</section>
</section>
<section>
<section>
<h2>Modules and Imports</h2>
<ul>
<li>To make a property, function, or object available outside its own file (<em>module</em>), prefix it with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export"><code>export</code></a> keyword:</li>
</ul>
<pre><code class="js">// wombats.js
export const metabolism = 4;
export function showWombats() {
// ...
};</code></pre>
<aside class="notes" data-markdown>
* https://gist.github.com/locksmithdon/96fb0ae2904f86c86e66
</aside>
</section>
<section>
<ul>
<li>To make use of this in another module, we use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import"><code>import</code></a>. The following will all make <code>showWombats</code> available:</li>
</ul>
<pre><code class="js">// Import the entire module
import wombats from './wombats';
// Just one function
import {showWombats} from './wombats';
// Same as above, but give it a shorter alias
import {showWombats as sw} from './wombats';</code></pre>
<ul>
<li> In the first statement, <code>showWombats</code> would be referred to as <code>wombats.showWombats</code></li>
</ul>
</section>
</section>
<section>
<section>
<h2>Underscore and Lo-Dash</h2>
<ul>
<li>Utility libraries act as extensions to the JavaScript standard library, providing consistent and well-tested ways to interact with data structures.</li>
<li>The two most popular are <a href="http://underscorejs.org">Underscore</a> and its API-compatible alternative, <a href="http://lodash.com">Lo-Dash</a></li>
</ul>
<aside class="notes" data-markdown>
* If you've ever wished that JavaScript had <em>X</em> feature from another language, chances are it (or something like it) is provided by a utility library
* One of the key roles of a utility library is making it simpler, more expressive, and less error-prone to work with data structures (an array, object, or string).
* The question of which one to use has gotten quite political, and beyond our scope here. Either one will run the examples.
</aside>
</section>
<section>
<ul><li>Given an array:</li></ul>
<pre><code class="js">let aardvarks = [
"Snuffler", "Stinker", "Slappy", "Sadface"
];</code></pre>
<ul><li>You could do this:</li></ul>
<pre><code class="js">for (let i = 0; i < aardvarks.length; i++) {
console.log(aardvarks[i]);
}</code></pre>
<ul><li>Or this:</li></ul>
<pre><code class="js">_.each(aardvarks, console.log);</code></pre>
</section>
<!--
I'm leaving these sections in for now, but I'm hiding
them because I think it might be a bit too much. Plus
a lot of lodash/underscore isn't needed with ES6.
<section>
<ul>
<li>Checking if an object has a particular propery is another common use case:</li>
</ul>
<pre><code class="js">let wombat = {
registeredToVote: false,
highlyOpinionated: true
};
if (_.contains(_.keys(wombat), 'registeredToVote')) {
console.log("This marsupial is registered to vote.");
}</code></pre>
</section>
<section>
<ul>
<li>Some standard library functions are duplicated:</li>
</ul>
<pre><code class="js">// Standard library
let sum1 = [1, 2, 3, 4, 5].reduce( function (prev, curr) {
return prev + curr;
});
// Underscore / Lo-Dash
let sum2 = _.reduce([1, 2, 3, 4, 5], function (total, n) {
return total + n;
});
// Alternative syntax
let sum3 = _([1, 2, 3, 4, 5]).reduce( function (total, n) {
return total + n;
});
console.log(sum1, sum2, sum3); // 15 15 15</code></pre>
<aside class="notes" data-markdown>
* Why not use the standard library version?
* The same approach to work with anything that can be treated as a container (objects, strings, and arrays), so we don't need to explicitly convert to array and back again. This can give our code consistency and readibility.
* In some circumstances, the library will default to the native version if it's known to be faster in a given environment.
</aside>
</section>
-->
</section>
<section>
<h2>Further Reading</h2>
<ul>
<li>
<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let">let</a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a> (MDN)
</li>
<li><a href="http://stackoverflow.com/a/111111/122643">Closures - canonical Stack Overflow answer</a></li>
<li><a href="http://bjorn.tipling.com/all-this">all this</a></li>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call</a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply</a>,
<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind">bind</a> (MDN)
</li>
<li><a href="http://www.sitepoint.com/javascript-this-event-handlers/">JavaScript 'this' and event handlers</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a></li>
<li><a href="http://colintoh.com/blog/lodash-10-javascript-utility-functions-stop-rewriting">Lodash: 10 JavaScript Utility Functions That You Should Probably Stop Rewriting</a></li>
<li><a href="http://blog.xebia.com/2015/08/11/you-might-not-need-lodash-in-your-es2015-project">You might not need lodash in your ES2015 Project</a>
<li><a href="https://babeljs.io/docs/learn-es2015/">Learn ES2015</a></li>
<li><a href="http://exploringjs.com/es6/">Exploring ES6</a> (free online book)</li>
</ul>
</section>
<!-- SECTION 3 -->
<section data-background="img/backgrounds/log.jpg">
<h1 class="offset-bottom">The Ecosystem</h1>
</section>
<section>
<p>Today, the JavaScript ecosystem is in a constant state of ... innovation ... as millions of developers contribute to client-side and server-side libraries and tools.</p>
<p>We couldn't possibly present an exhaustive overview of the ecosystem, but we think the following tools are mandatory for most JavaScript developers to at least be familiar with.</p>
</section>
<section>
<section>
<h2>npm</h2>
<ul>
<li>Since its release in 2009, the <a href="https://www.npmjs.com">Node package manager</a> has become one of the most prolific package managers in the world </li>
<li>Share packaged modules of JavaScript code</li>
<li>Stipulate versions (or version ranges) for package dependencies</li>
<li>npm Registry contains over 195,000 modules: the largest of all package repositories</li>
<li>Can install packages <em>locally</em> or <em>globally</em></li>
</ul>
</section>
<section>
<pre><code class="json">{
"name": "Aardvarks Ahoy",
"version": "0.0.0",
"description": "Orycterapus after",
"main": "server.js",
"repository": "https://iamnotarealrepository",
"author": "Rich Churcher <foo@wombat.com>",
"dependencies": {
"express": "~3.2.4",
},
"devDependencies": {
"babel": "^5.8.23",
"babelify": "^6.3.0",
"browserify": "^11.1.0",
"gulp": "^3.9.0",
"gulp-babel": "^5.2.1",
"gulp-concat": "^2.6.0",
}
}</code></pre>
</section>
<section>
<ul>
<li>Each package keeps a copy of its own dependencies in a nested folder structure (under <code>node_modules</code>)</li>
<li>This causes a lot of duplication on the server's file system, but since we're not running JavaScript in the browser it's rarely a problem</li>
</ul>
</section>
</section>
<section>
<section>
<h2>Bower</h2>
<ul>
<li>Bower is ideally suited to managing packages for the client, because unlike npm it doesn't nest dependencies: there's only one copy of each</li>
<li>Much lighter weight, faster page loads</li>
<li>Interacts with Git, can install directly from a repository</li>
<li>Very common to use a combination of Bower and npm: they're not mutually exclusive</li>
<li>Controlled by <code>bower.json</code>:</li>
</ul>
</section>
<section>
<pre><code class="json">{
"name": "Aardvarks Ahoy",
"description": "Orycterapus after",
"version": "0.0.0",
"homepage": "https://thisisnotthehomepage.io",
"authors": [
"Rich Churcher <foo@wombat.com>"
],
"main": "js/app.js",
"moduleType": [ "amd", "es6", "node" ],
"keywords": [ "aardvark" ],
"license": "MIT",
"ignore": [ "**/.*", "node_modules", "bower_components" ],
"dependencies": {
"jquery": "~2.1.4",
"lodash": "~3.10.1"
}
}</code></pre>
</section>
<section>
<ul>
<li>The above or something very like it would be generated with the following terminal commands:</li>
</ul>
<pre><code class="bash">npm i bower --save-dev
bower init
bower install jquery lodash --save</code></pre>
<ul>
<li><code>bower init</code> fills most of the details out for you, including grabbing the GitHub repo as homepage, and adding any previously installed components</li>
<li>Subsequently, components can be included directly from <code>bower_components/packagename/packagename.js</code> or similar</li>
</ul>
</section>
</section>
<section>
<section>
<h2>Gulp</h2>
<ul>
<li>Unlike <a href="#npm">npm</a> and <a href="#bower">Bower</a>, Gulp is a <em>build system</em> and not a package manager</li>
<li>Also referred to as a <em>task runner</em></li>
</ul>
<aside class="notes" data-markdown>
* Typically used for:
* Concatenation and minification of source files, other deployment-related tasks
* Compiling your CSS/Sass
* Running a transpiler, allowing you to use _ES6_ features
* Running test suites
* Compressing images
* Watching files for changes
</aside>
</section>
<section>
<ul>
<li>Gulp can be used with both client and server-side projects</li>
<li>Uses node streams</li>
<li> Reads source files, pipes the text through plugins, and writes output</li>
<li>Wide variety of plugins: uses <a href="#npm">npm</a> packages</li>
<li>Compares to <a href="http://gruntjs.com">Grunt</a>, another widely-used task runner</li>
<li>Controlled with <code>gulpfile.js</code>.</li>
</ul>
</section>
<section>
<pre><code class="js">gulp.task('js', function () {
return gulp.src('js/**/*.js')
.pipe(sourcemaps.init())
.pipe(concat('app.js'))
.pipe(uglify(true))
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
});
gulp.task('test', function (done) {
new Server({
configFile: 'test/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('watch', ['js'], function () {
gulp.watch('js/**/*.js', ['js', 'test']);
});</code></pre>
<aside class="notes" data-markdown>
* The `js` task does the following:
* Suck every JavaScript file in `js` and its subdirectories into a stream
* Starts a [sourcemap](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/): a way to retain the ability to debug minified code
* Pass the stream through `concat`, which (surprise!) concatenates all the files into one, naming it `app.js`
* Pass the stream through `stripDebug`, which removes all those pesky `console.log`s
* Pass the stream through `uglify`, which minifies it
* Finishes the sourcemap
* Writes the stream to the destination directory.
* The `test` task runs the unit test suite
* The `watch` task above will keep an eye on files with the `.js` suffix and run first the `js` task, then the tests, for each code change
</aside>
</section>
</section>
<section>
<section>
<h2>Browserify</h2>
<ul>
<li>Bundles the dependencies for your project, letting you program with modules while browser support for <em>ES6</em> and <code>import</code>/<code>export</code> is still patchy</li>
<li>Can also handle minification and other pre-deployment tasks</li>
<li>Can be used from the command line or within the context of other tools such as <a href="#gulp">Gulp</a>:</li>
</ul>
</section>
<section>
<pre><code class="js">var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var bundler = browserify({
entries: './src/main.js',
extensions: ['.js'],
debug: true
});
gulp.task('default', function () {
return bundler
.transform(babelify)
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('js'));
});</code></pre>
<aside class="notes" data-markdown>
* To walk through the above `gulpfile.js`:
* Create a `bundler` using Browserify which begins at `main.js` and scoops up everything that app.js requires to work (dependencies)
* Pass it through a transform using `babelify`, which is specifically designed to create _ES5_ output from _ES6_ JavaScript
* Bundle it all up
* Pipe the result into a file named `app.js`
* Write `app.js` into the `js` destination directory
</aside>
</section>
</section>
<section data-background="img/backgrounds/kea_car.jpg">
<h1 class="offset-bottom">Testing</h1>
</section>
<section>
<section>
<h2>Jasmine</h2>
<ul>
<li>A long-standing <a href="https://en.wikipedia.org/wiki/Behavior-driven_development">behaviour-driven</a> test framework</li>
<li>Probably as close to a 'standard' as JavaScript has, although alternatives are growing in popularity</li>
<li>Tests are just JavaScript files, which can contain any code you like</li>
</ul>
</section>
<section>
<pre><code class="js">describe('Wombat Counter', function() {
describe('GET /', function() {
it('responds with HTTP status 200', function() {
request.get(base_url, function(error, response, body) {
expect(response.statusCode.toBe(200));
});
});
});
});</code></pre>
</section>
<section>
<ul>
<li>Jasmine comes with its own assertion tools:</li>
</ul>
<pre><code class="js">expect(countTheAardvarks()).toEqual(9);
expect("I'm a wombat").toContain('wombat');
expect(countTheAardvarks()).not.toEqual(8);</code></pre>
</section>
<section>
<ul>
<li>It also has <em>spies</em>: a way to keep tabs on parts of your program where it's not simple to track what's happening, like methods/functions</li>
</ul>
<pre><code class="js">var a = new ArmouryOfAardvarks();
spyOn(a, 'countTheAardvarks');
a.showPopulation();
// Did showPopulation call countTheAardvarks?
expect(a.countTheAardvarks).toHaveBeenCalled();</code></pre>
</section>
</section>
<section>
<section>
<h2>Mocha</h2>
<ul>
<li>Similar on the surface to Jasmine</li>
<li>Uses third party libraries for assertions, runners and spies</li>
<li>The framework decision is less important than ensuring good test coverage</li>
</ul>
<aside class="notes" data-markdown>
* On the surface, Mocha looks very similar to Jasmine but there are some important differences:
* Mocha doesn't have an assertion tool or spies, preferring third party libraries for this purpose
* (see <a href="#chai">Chai</a> and <a href="#sinon">Sinon</a>, below)
* Mocha can be considered more flexible, but requires a bit more setup/configuration before use than Jasmine
* For many uses there will be little difference between Jasmine, Mocha, and `[insert library here]`.
* The take-home message is, it's probably more important that your app has good test coverage than spending time worrying about which framework to use!
</aside>
</section>
<section>
<h2>Chai</h2>
<ul>
<li><a href="http://chaijs.com">Chai</a> is perhaps the most popular assertion library for Mocha.</li>
<li><em>assert</em>:</li>
</ul>
<pre><code class="js">assert.typeOf(foo, 'string', 'Yup, that is a string.');
assert.lengthOf(aardvarkArmoury, 9, 'There are 9 aardvarks.');</code></pre>
<ul><li><em>BDD</em>:</li></ul>
<pre><code class="js">expect(foo).to.equal('bar');
expect(bar).to.have.property('population').with.length(9);</code></pre>
<ul><li><em>should</em> (extends each object with a new property):</li></ul>
<pre><code class="js">bar.should.have.property('population').with.length(9);</code></pre>
</section>
</section>
<section>
<h2>Further Reading</h2>
<ul>
<li><a href="https://markgoodyear.com/2014/01/getting-started-with-gulp/">Getting Started with Gulp</a></li>
<li><a href="https://medium.com/@preslavrachev/gulp-vs-grunt-why-one-why-the-other-f5d3b398edc4">Gulp vs Grunt. Why one? Why the Other?</a></li>
<li><a href="http://thejsguy.com/2015/01/12/jasmine-vs-mocha-chai-and-sinon.html">Jasmine vs. Mocha, Chai, and Sinon</a></li>
<li><a href="http://www.macwright.org/2014/03/11/tape-is-cool.html">TAP & Tape, the awesome way to test JavaScript</a></li>
</ul>
</section>
<!-- SECTION 4 -->
<section data-background="img/backgrounds/sheep.jpg">
<h1 class="offset-bottom">Asynchronous JavaScript</h1>
</section>
<section>
<section>
<h2>Callbacks</h2>
<ul>
<li>Also called the <em>Continuation Passing Style (CPS)</em></li>
<li>Can be used with synchronous or asynchronous functions</li>
<li>Called when an event occurs, or when the function completes</li>
</ul>
</section>
<section>
<ul>
<li>Passing a callback into a synchronous function</li>
</ul>
<pre><code class="js">function displayResults(results) {
for (let i = 0; i < results.length; i++) {
console.log(results[i]);
}
}
function incrementAll(numbers, callback) {
for (let i = 0; i < numbers.length; i++) {
numbers[i] += 1;
}
callback(numbers);
}
incrementAll([1, 2, 3, 4, 5], displayResults);</code></pre>
<aside class="notes" data-markdown>
* Here, the function `displayResults` is passed as a _callback_ to `incrementAll`.
* It outputs values to the console, but we could just as easily pass in a function which further modifies the array
* Many JavaScript standard library functions use callbacks, often optionally. For example:
</aside>
</section>
<section>
<pre><code class="js">function even(n) {
return n % 2;
}
console.log([1, 2, 3, 4, 5].filter(even)); // [1, 3, 5]</code></pre>
<ul>
<li><code>even</code> serves as a callback to <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter"><code>Array.filter</code></a></li>
<li>Callbacks can be inline, which should only be used if it improves readability (i.e. not for lengthy callbacks)</li>
</ul>
<pre><code class="js">console.log([1, 2, 3, 4, 5].filter(function () {
return n % 2;
});</code></pre>
<ul>
<li>Anonymous functions/callbacks make debugging more difficult</li>
</ul>
</section>
</section>
<section>
<section>
<h2>Promises</h2>
</section>
<section>
<ul>
<li>A <em>promise</em> is an operation we expect to complete in the future</li>
</ul>
<pre><code class="js">function showWombats() {
let wombats = getWombatsFromServer();
displayWombats(wombats);
}</code></pre>
<ul>