-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1506 lines (1364 loc) · 44.9 KB
/
Copy pathindex.html
File metadata and controls
1506 lines (1364 loc) · 44.9 KB
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>reveal.js – The HTML Presentation Framework</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<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/black.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.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">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>ECMAScript Workshop</h1>
</section>
<section>
<h2>Transpilation</h2>
<p>Browser support for ECMAScript 6 features is not extensive yet and varies alot.</p>
<p>This is why we need to convert it to the previous version of JavaScript, called ECMAScript 5,
which runs fine in any modern browser.</p>
<p>This conversion is often referred to as <b>transpilation</b>, and <a href="https://babeljs.io/repl/">Babel</a> is a popular solution to do that</p>
</section>
<section>
<h2>So, what excatly can i use?</h2>
<p>Some of the features can be used almost for "free", such as modules, arrow functions, and classes withouth to much overhead (syntatical sugar).</p>
<p>Additions to Array, String and Math objects and prototypes (such as Array.from()) require so-called polyfills (provide missing code).</p>
<p>For a full overview of features that are supported by both transpilers and browers, see <a href="https://kangax.github.io/compat-table/es6/">ECMAScript 6 compability table</a></p>
</section>
<section>
<h2>Today</h2>
<ul>
<li>Modules</li>
<li>Variables & scope</li>
<li>Template strings</li>
<li>Destructuring</li>
<li>Classes</li>
<li>Generators</li>
<li>Promises</li>
<li>Arrow functions</li>
<li>Maps/Sets</li>
<li>Iterator & iterable</li>
</ul>
</section>
<section>
<section>
<h1>Variables & scope</h1>
</section>
<section>
<h2>Spoiler alert!</h2>
<p>
Variables are so much more fun in ES6 - not! But they are a lot nicer(les:more predictible) to hang out with than the old var chap of ES5!
</p>
</section>
<section>
<h2>let & const</h2>
<p>
- ES6 brings two new ways to declare variables: let and const<br>
- These basically replace, the ES5 way of declaring variables, using var<br>
- However, var is still around<br>
</p>
</section>
<section>
<h2>let</h2>
<p>Here is an example where the let declared variable tmp, only exists within the block starting in line A: </p>
<pre>
<code class="hljs" data-trim contenteditable>
function switch(x, y) {
if (x > y) { // (A)
let tmp = x;
x = y;
y = tmp;
}
console.log(tmp===x); // ReferenceError: tmp is not defined
return [x, y];
}
</code>
</pre>
</section>
<section>
<h2>const</h2>
<p>const is a read-only, initialize at once constant type.
Here are a few examples of correct usage and wrong usage leading to SyntaxError and TypeError:</p>
<pre>
<code class="hljs" data-trim contenteditable>
const foo;
// SyntaxError: missing = in const declaration
const bar = 123;
bar = 456;
// TypeError: `bar` is read-only
</code>
</pre>
</section>
</section>
<section>
<section>
<h1>Promises</h1>
</section>
<section>
<h2>Promises - que?</h2>
<p align="left" style="font-size: large">
- Promises are a pattern, helping out with one particular kind of asynchronous programming:<br>
"a function (or method) that returns its result asynchronously."<br>
- To implement such a function, you return a Promise, an object that is a placeholder for the result.<br>
- The caller of the function registers callbacks with the Promise to be notified once the result has been computed.<br>
- The function sends the result via the Promise.<br>
<br>
The de-facto standard for JavaScript Promises is called Promises/A+ [1]. The ECMAScript 6 Promise API follows that standard.
</p>
</section>
<section>
<h2>Promises - when to use</h2>
<p>
A gentle example, to give you a feeling of what working with Promises will be like.
With Node.js-style callbacks, reading a file asynchronously looks like this:
</p>
<pre>
<code class="hljs" data-trim contenteditable>
fs.readFile('config.json',
function (error, text) {
if (error) {
console.error('Error while reading config file');
} else {
try {
let obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
} catch (e) {
console.error('Invalid JSON in file');
}
}
});
</code>
</pre>
</section>
<section>
<h2>Promises applied</h2>
<p>With Promises, the same functionality is implemented like this:</p>
<pre>
<code class="hljs" data-trim contenteditable>
readFilePromisified('config.json')
.then(function (text) { // (A)
let obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
})
.catch(function (reason) { // (B)
// File read error or JSON SyntaxError
console.error('An error occurred', reason);
});
</code>
</pre>
<p align="left" style="font-size: large">
There are still callbacks, but they are provided via methods that are invoked on the result (then() and catch()).
The error callback in line B is convenient in two ways:
First, it’s a single style of handling errors (versus if (error) and try-catch in the previous example).
Second, you can handle the errors of both readFilePromisified() and the callback in line A from a single location.
</p>
</section>
</section>
<section>
<section>
<h1>Modules</h1>
</section>
<section>
<h2>Benefits</h2>
<p>
No more global namespace pollution.
</p>
</section>
<section>
<h2>Defaults</h2>
<p>There is exactly one module per file and one file per module.</p>
<p>By default anything you declare in a file is not available outside that file (awesome).</p>
</section>
<section>
<h2>Named exports</h2>
<p>A module can export multiple things by prefixing its declarations with the keyword export:</p>
<pre><code class="hljs" data-trim contenteditable>
export var myVar1 = ...;
export let myVar2 = ...;
export const MY_CONST = ...;
export function myFunc() {}
export class MyClass {}
</code></pre>
<p>These exports are distinguished by their names and are called named exports.</p>
<pre><code class="hljs" data-trim contenteditable>
import { myFunc, myVar1 } from 'lib';
myFunc();
</code></pre>
</section>
<section>
<h2>Named exports</h2>
<p>You can also list everything you want to export at the end of the module (which is once again similar in style to the revealing module pattern):</p>
<pre><code class="hljs" data-trim contenteditable>
const MY_CONST = ...;
function myFunc() {}
export { MY_CONST, myFunc };
</code></pre>
</section>
<section>
<h2>import the whole module</h2>
<p>You can also import the complete module using a wildcard:</p>
<pre><code class="hljs" data-trim contenteditable>
import * as lib from 'lib';
lib.myFunc();
</code></pre>
</section>
<section>
<h2>Single default export</h2>
<p>If you want to export a single value from the module then you can use default export. </p>
<p>For example, a class:</p>
<pre><code class="hljs" data-trim contenteditable>
export default class {}
</code></pre>
<p>And import like this (omit the curly braces):</p>
<pre><code class="hljs" data-trim contenteditable>
import MyClass from 'MyClass';
var instance = new MyClass();
</code></pre>
</section>
<section>
<h2>Mixture</h2>
<p>Module can have both named exports and a default export.</p>
<p>In such cases, to import a module's default export, you have to omit the curly braces in the import statement:</p>
<pre><code class="hljs" data-trim contenteditable>
import myDefault, { foo, bar } from 'lib';
</code></pre>
</section>
<section>
<h2>Best practise?</h2>
<p> Only use <b>export default</b>, and to do that at the end of your module files. Like this:</p>
<pre><code class="hljs" data-trim contenteditable>
var api = {
foo: 'bar',
baz: 'ponyfoo'
}
export default api
</code></pre>
<p>Easy then to import the whole thing like this:</p>
<pre><code class="hljs" data-trim contenteditable>
import api from 'api';
api.foo; // bar
</code></pre>
</section>
<section>
<h2>Code task 1 - export two named functions</h2>
<p>In `src/00-modules/named.js´ create and export two named functions:</p>
<ul>
<li>
sum(x,y) - A function that add two numbers
</li>
<li>
multiply(x,y) - A function that multiply two numbers
</li>
</ul>
</section>
<section>
<h2>Code task 2 - export two functions by default</h2>
<p>In `src/00-modules/default.js` import the two functions created in the previous task, then export them again, but as a single default export. </p>
</section>
<section>
<h2>Export Syntax</h2>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export</a>
</section>
<section>
<h2>Import Syntax</h2>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import</a>
</section>
</section>
<section>
<section>
<h1>Classes</h1>
</section>
<section>
<h2>Benefits</h2>
<p>
Simpler and clearer syntax to create objects and to deal with inheritance
</p>
</section>
<section>
<h2>Syntatical sugar</h2>
<p>Classes aren't really 'classes', instead they are functions which are in turn objects</p>
<p>It’s important to understand that while JavaScript is an object-oriented language, it is prototype-based and does not implement a traditional class system.</p>
</section>
<section>
<h2>JavaScript Objects</h2>
<p>
Almost everything in JavaScript are objects (including functions and arrays). Except for primitives:
</p>
<ul>
<li>
numbers
</li>
<li>
boolean
</li>
<li>
strings
</li>
<li>
undefined
</li>
<li>
null
</li>
</ul>
</section>
<section>
<h2>JavaScript Objects</h2>
<p>
An object is a collection of properties, and a property is an association between a name (or key) and a value.
A property's value can be a function, in which case the property is known as a method.
</section>
<section>
<h2>Creating A JavaScript Object</h2>
<pre><code class="hljs" data-trim contenteditable>
// The easiest way to create an object is like this:
let myObject = { 'key1': "Awesome", 'key2': "Object" }
// Or:
var myObject = Object.create(new Object());
myObject.key1 = "Awesome";
myObject.key2 = "Object";
// Or:
function MyObject(value1, value2) {
this.key1 = value1;
this.key2 = value2;
}
var myObject = new MyObject("Awesome", "Object");
</code></pre>
<p>Which of these alternatives are suited to create multiple instances of same type?</p>
</section>
<section>
<h2>Using A JavaScript Object</h2>
<pre><code class="hljs" data-trim contenteditable>
// Get a property
var value = myObject.key1;
var value = myObject["key1"];
// Set a property
myObject.property = "Value";
myObject["property with space in it"] = "Value";
// Call a method
myObject.toString();
// To find out if a property exists on an object
'key1' in myObject; // true
</code></pre>
</section>
<section>
<h2>Classes in ECMAScript 5</h2>
<pre><code class="hljs" data-trim contenteditable>
function MyClass (id) {
var privateField = "My secret";
// Instance property
this.id = id;
}
// Instance method
MyClass.prototype.myMethod = function () {};
var instance1 = new MyClass(1);
var instance2 = new MyClass(2);
instance1.myMethod();
instance1.id; // 1
instance2.myMethod();
instance2.id; // 2
instance1 instanceof MyClass; // true
</code></pre>
<p>Prototype methods are shared across all instances of the class. One method, many instances!</p>
</section>
<section>
<h2>Why is MyClass a function, shouldn’t it be a class?</h2>
<p>
MyClass is a constructor function, and combined with the new keyword, work together to create new objects in much in the same way classes do in other OO languages.
</p>
<p>When you create an object using the new keyword, it creates a new object, passes it in as this to the constructor function.</p>
</section>
<section>
<h2>Inherited properties and own properties</h2>
<p>The own properties are properties that were defined on the instance,
while the inherited properties were inherited from the Function’s Prototype object.</p>
<pre><code class="hljs" data-trim contenteditable>
instance1.hasOwnProperty("id"); // true
instance1.hasOwnProperty("myMethod"); // false
</code></pre>
</section>
<section>
<h2>Functions have a prototype</h2>
<p>When you define a function within JavaScript, it comes with a few pre-defined properties and one of these is the illusive prototype.</p>
<p>
(1) Initially an empty object. (2) You can add methods and properties on a function’s prototype property
to make those methods and properties <b>available</b> to instances of that function. All class instances, past and future, will be affected.
</p>
</section>
<section>
<h2>Prototypal inheritance</h2>
<!--<p>In classical languages, like Java, instances are created from classes.
JavaScript differs in that it has prototypal inheritance, in which there are no classes.
Instead, objects inherit from other objects.
</p>-->
<p>Objects inherit from other objects.</p>
</section>
<section>
<h2>How does prototype inheritance work?</h2>
<p>
Every object in JavaScript has a special related object called the prototype.
</p>
<pre><code class="hljs" data-trim contenteditable>
vehicle.__proto__ = machine
// machine is the prototype of vehicle
car.__proto__ = vehicle
// vehicle is the prototype of car
</code></pre>
<p>This is a prototype chain: car -> vehicle -> machine</p>
<p>
When looking up a property, Javascript will try to find the property in the object itself. If it does not find it then it tries in it's prototype, and so on.
</p>
</section>
<section>
<h2>Functions vs objects prototype</h2>
<p>A function’s prototype is used as the object to be assigned as the prototype for new objects’ created using this function as a constructor function.</p>
<pre><code class="hljs" data-trim contenteditable>
instance.__proto__ = Function.prototype
</code></pre>
<p>An object’s prototype is the object from which it is inheriting properties. </p>
</section>
<!--
<section>
<h2>Inherited properties vs. native properties</h2>
<pre><code class="hljs" data-trim contenteditable>
instance1.__proto__; // { myMethod: [Function] }
instance1.hasOwnProperty("id"); // true
instance1.hasOwnProperty("myMethod"); // false
</code></pre>
</section>
<section>
<h2>Described by Douglas Crockford</h2>
<blockquote>
you make prototype objects, and then … make new instances. Objects are mutable in JavaScript, so we can augment the new instances, giving them new fields and methods. These can then act as prototypes for even newer objects. We don't need classes to make lots of similar objects… Objects inherit from objects. What could be more object oriented than that?
</blockquote>
</section>-->
<section>
<h2>Subclasses in ECMAScript 5</h2>
<pre><code class="hljs" data-trim contenteditable>
function MySubClass(id) {
MyClass.call(this, id);
}
// Inherit from the parent class
MySubClass.prototype = Object.create(MyClass.prototype);
MySubClass.prototype.constructor = MySubClass;
// Child class method
MySubClass.prototype.myMethod = function() {
MyClass.prototype.method.call(this);
}
</code></pre>
<p>Easy to read?</p>
</section>
<section>
<h2>Classes in ECMAScript 6</h2>
<pre><code class="hljs" data-trim contenteditable>
class MyClass {
constructor (id) {
this.id = id
}
myMethod () {}
static myStaticMethod() {}
}
let instance = new MyClass(1);
instance instanceof MyClass; // true
typeof MyClass // 'function' (old-school constructor function)
MyClass.myStaticMethod();
darth.hasOwnProperty("myMethod")
MyClass.prototype.myMethod(); // prototype-based
</code></pre>
<p>The class keyword is syntactical sugar, JavaScript remaining prototype-based!</p>
<p>This is the prototype chain: MyClass -> Object</p>
</section>
<section>
<h2>Subclasses in ECMAScript 6</h2>
<pre><code class="hljs" data-trim contenteditable>
class MySubClass extends MyClass {
constructor (id) {
super(id)
}
}
</code></pre>
<p>This is the prototype chain: MySubClass -> MyClass -> Object</p>
</section>
<section>
<h2>Code task 3 - Create a class</h2>
<p>Create a class equal to the ECMAScript 5 code:</p>
<pre><code class="hljs" data-trim contenteditable>
function Point(x,y) {
this.x = x;
this.y = y;
}
// Static method
Point.distance = function (a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return Math.sqrt(dx*dx + dy*dy);
};
Point.prototype.toString = function () {
return this.x + ' ' + this.y;
};
module.exports = Point;
</code></pre>
</section>
<section>
<h2>Code task 4 - Class inheritance</h2>
<p>Extend the Point class from previous task so that it behaves equal to the ECMAScript 5 code below:</p>
<pre><code class="hljs" data-trim contenteditable>
// Child class constructor
var ColorPoint = function (x, y, color) {
Point.call(this, x, y);
this.color = color || 'red';
};
// Inherit from the parent class
ColorPoint.prototype = Object.create(Point.prototype);
ColorPoint.prototype.constructor = ColorPoint;
// Child class method
ColorPoint.prototype.getColor = function () {
return this.color;
};
module.exports = ColorPoint;
</code></pre>
</section>
<section>
<h2>References</h2>
<ul>
<li><a href="http://www.objectplayground.com">http://www.objectplayground.com</a></li>
<li><a href="http://blog.pluralsight.com/understanding-javascript-objects-2">http://blog.pluralsight.com/understanding-javascript-objects-2</a></li>
<li><a href="http://blog.pluralsight.com/understanding-javascript-prototypes">http://blog.pluralsight.com/understanding-javascript-prototypes</a> </li>
<li><a href="http://aaditmshah.github.io/why-prototypal-inheritance-matters">http://aaditmshah.github.io/why-prototypal-inheritance-matters</a></li>
<li><a href="https://blog.pivotal.io/labs/labs/javascript-constructors-prototypes-and-the-new-keyword">https://blog.pivotal.io/labs/labs/javascript-constructors-prototypes-and-the-new-keyword</a></li>
<li><a href="https://www.nczonline.net/blog/2012/10/16/does-javascript-need-classes">https://www.nczonline.net/blog/2012/10/16/does-javascript-need-classes</a></li>
<li><a href="http://exploringjs.com/es6/ch_classes.html">http://exploringjs.com/es6/ch_classes.html</a></li>
<li><a href="https://www.reinteractive.net/posts/235-es6-classes-and-javascript-prototypes">https://www.reinteractive.net/posts/235-es6-classes-and-javascript-prototypes</a></li>
</ul>
</section>
</section>
<section>
<section>
<h1>Iterator & iterable</h1>
</section>
<section>
<h2>for-of-loop</h2>
<p>ES6 has a new loop — for-of. It works with iterables. Let’s look at his signature:</p>
<pre><code class="hljs" data-trim contenteditable>
for (let item of ITERABLE) {
CODE BLOCK
}
</code></pre>
<p>
It’s similar to for-in loop, which can be used to iterate through object properties.
</p>
</section>
<section>
<h2>Iterable</h2>
<p>
Iterable is an object which has [Symbol.iterator]() method inside.
</p>
<p>
The [Symbol.iterator] method must return an iterator object,
which is actually responsible for the iteration logic.
</p>
</section>
<section>
<h2>Iterator</h2>
<p>
An iterator is an object with a next method that returns { done, value } tuples.
</p>
</section>
<section>
<h2>Arrays are iterable by default</h2>
<p>We finally can use for-of for looping over the elements:</p>
<pre><code class="hljs" data-trim contenteditable>
const arr = [1, 2, 3, 4, 5];
for (let item of arr) {
console.log(item); // 1
// 2
// 3
// 4
// 5
}
</code></pre>
</section>
<section>
<h2>Symbol</h2>
<p>
Symbol is in turn an unique and immutable data type which can be used
as an identifier for object properties — no equivalent in ES5.
</p>
</section>
<section>
<h2>Symbol</h2>
<pre><code class="hljs" data-trim contenteditable>
// Symbol
let s1 = Symbol('abc');
let s2 = Symbol('abc');
console.log(s1 !== s2); // true
console.log(typeof s1); // 'symbol'
let obj = {};
obj[s1] = 'abc';
console.log(obj); // Object { Symbol(abc): 'abc' }
</code></pre>
<p>You can use symbols to create unique identifiers for object properties.</p>
<p>Symbols are not visible in `for...in` iterations and object.keys()</p>
</section>
<section>
<h2>Symbol.iterator</h2>
<p>The Symbol.iterator well-known symbol specifies the default iterator for an object.</p>
</section>
<section>
<h2>Encapsulating collections</h2>
<pre><code class="hljs" data-trim contenteditable>
class Classroom {
constructor() {
this.students = ["Tim", "Joy", "Sue"];
}
}
</code></pre>
<p>Option 1: Return a reference to the array, in which case the caller might change the array by adding or removing items.</p>
<p>Option 2: Another option is to make a copy of the array. Then, the original student array remains safe. However, copy operations can be expensive.</p>
<p>Option 3: Make the classroom iterable by adding a [Symbol.iterator]() method.</p>
</section>
<section>
<pre><code class="hljs" data-trim contenteditable>
function PointCloud(list) {
this.collection = list;
}
PointCloud.prototype[Symbol.iterator] = function() {
var index = 0;
var array = this.collection;
return {
next: () => {
var result = { value: undefined, done: true };
if (index < array.length) {
result.value = array[index++];
result.done = false;
}
return result;
}
};
};
module.exports = PointCloud;
</code></pre>
</section>
<section>
<h2>References</h2>
<ul>
<li>
https://medium.com/ecmascript-2015/es6-iterators-4afec026f70a#.6wfbn4xnc
</li>
<li>
http://jsrocks.org/2015/09/javascript-iterables-and-iterators/
</li>
<li>
http://odetocode.com/blogs/scott/archive/2015/02/09/creating-iterables-in-ecmascript-6.aspx
</li>
</ul>
</section>
</section>
<section>
<section>
<h1>Arrow functions</h1>
<p>() => {}</p>
</section>
<section>
<h2>Benefits</h2>
<ul>
<li>
function(){...} can now be written as () => {...}
<ul>
<li>Shorter syntax than using traditional anonymous functions</li>
</ul>
</li>
<li>Lexically binds the <i>this</i> value
<ul>
<li>Which is where arrow functions shine</li>
</ul>
</li>
</ul>
</section>
<section>
<p>
A quick overview of the syntax:
</p>
<pre>
<code class="hjls" data-trim contenteditable>
// Basic syntax:
(param1, param2, paramN) => { statements }
(param1, param2, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one argument:
(singleParam) => { statements }
singleParam => { statements }
// A function with no arguments requires parentheses:
() => { statements }
</code>
</pre>
</section>
<section>
<p>
Another example:
</p>
<pre>
<code class="hjls" data-trim contenteditable>
function(x) { return x+1;}
x => x+1;
</code>
</pre>
</section>
<section>
<p>
Here a2 is using traditional anonymous functions while a3 is using the arrow function syntax.
</p>
<pre>
<code class="hjls" data-trim contenteditable>
var a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
var a2 = a.map(function(s){ return s.length });
var a3 = a.map( s => s.length );
//a2 = [8, 6, 7, 10]
//a3 = [8, 6, 7, 10]
</code>
</pre>
</section>
<section>
<h2>Lexically binding this</h2>
<p><p>
<ul>
<li>
Javascript uses lexical scope
<ul>
<li>Like Python, Java ..</li>
</ul>
</li>
<li>Block scope: let (pre ECMAScript 2015)</li>
</ul>
<pre>
<code class="hjls" data-trim contenteditable>
function foo(a) {
var b = a * 2;
function bar(c) {
console.log( a, b, c );
}
bar(b * 3);
}
foo( 2 ); // 2 4 12
</code>
</pre>
</section>
<section>
<ul>
<li>Every new function defines a new this. </li>
<li>
Object methods gets the context of the object.
<pre>
<code class="hjls" data-trim contenteditable>
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.changeName = function (name) {
this.lastName = name;
};
}
</code>
</pre>
</li>
</ul>
</section>
<section>
<ul>
<li>
When calling a function (not an object method) the this of the object is not reachable.
</li>
<pre>
<code class="hjls" data-trim contenteditable>
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
</code>
</pre>
</ul>
</section>
<section>
<p>
That can be solved like this:
</p>
<pre>
<code class="hjls" data-trim contenteditable>
function Person() {
var self = this;
// Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
var p = new Person()
</code>
</pre>
</section>
<section>
<p>
With arrow functions and lexical binding of <i>this</i>, the problem can be solved like this:
</p>
<pre>
<code class="hjls" data-trim contenteditable>
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
</code>
</pre>
</section>
<section>
<h2>References</h2>
<ul>
<li><a href="http://spin.atomicobject.com/2014/10/20/javascript-scope-closures/">Javascript scope</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a></li>
</ul>
</section>
</section>
<section>
<section>
<h1>Destructuring</h1>
<p>
let {a,b} = obj;
</p>
</section>
<section>
<h2>Array destructing</h2>
<pre>
<code class="hjls" data-trim contenteditable>
let foo = ["one", "two", "three"];
// without destructuring
let one = foo[0];
let two = foo[1];
let three = foo[2];
// with destructuring
let [one, two, three] = foo;
</code>
</pre>
</section>
<section>
<h2>Object destructuring</h2>
<pre>
<code class="hjls" data-trim contenteditable>
let o = {p: 42, q: true};
let {p, q} = o;
</code>
</pre>
<p>It is also possible to give the new variable a new name by using:</p>
<pre>
<code class="hjls" data-trim contenteditable>
let {p:age, q}
</code>
</pre>
</section>
<section>
<h2>Object destructuring</h2>
<pre>
<code class="hjls" data-trim contenteditable>
var metadata = {
title: "Scratchpad",
translations: [
{
locale: "de",
localization_tags: [ ],
last_edit: "2014-04-14T08:43:37",
url: "/de/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung"
}
],
url: "/en-US/docs/Tools/Scratchpad"
};
let { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
</code>
</pre>