-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
662 lines (637 loc) · 144 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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CPL Assignment 1: JavaScript</title>
<link href="http://fonts.googleapis.com/css?family=Crimson+Text:400,400italic,700,700italic|Quattrocento+Sans:400" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
</head>
<body id="top">
<div id="info">
<div class="leftCol">
<div id="header">
<h1>CPL<br>Assignment 1</h1>
<h2>JavaScript</h2>
</div>
<div id="credits">© 2012 Glenn Croes, Philippe De Croock, Thomas Winant</div>
<h3 id="preface">Preface</h3><p>The following discussion takes place between a programmer that isn’t familiar with JavaScript, and our group, three ‘competent’ JavaScript programmers.</p><p>Throughout the discussion many code examples will be presented to you. Feel free to edit the code. You can even run the code<span class="footnote">Note that statements, e.g. declarations and assignments, will result in <code>undefined</code> return values. Don’t be alarmed when results differ from the predicted outcome, this has to do with the parser, the code printer or sometimes even scoping issues.</span> by pressing the ‘Evaluate’ button above the code editor. Besides the conventional shortcuts like <kbd>ctrl</kbd> + <kbd>z</kbd> for undo, <kbd>ctrl</kbd> + <kbd>e</kbd> evaluates the code example and <kbd>ctrl</kbd> + <kbd>r</kbd> resets the code example to its initial contents.</p><p>Although JavaScript is a small language, you can do a lot of things with it, certainly when combining the small number of powerful features, without even touching on the vast ecosystem. Browser-specific parts (HTML5, the DOM, events, etc.), popular frameworks (jQuery, Prototype.js, etc.), community practices (testing, code minimisation, etc.), and many other interesting topics aren’t covered.</p>
</div>
<div id="toc" class="rightCol">
<ol start="0">
<li class="unnumbered"><a href="#preface">Preface</a></li>
<li><a href="#introduction-history">Introduction & history</a>
<ol>
<li><a href="#naming-history">Naming & history</a></li>
<li><a href="#influences">Influences</a></li>
<li><a href="#scripting-language">Scripting language</a></li>
</ol>
</li>
<li><a href="#syntax">Syntax</a>
<ol>
<li><a href="#variables-and-functions">Variables and functions</a></li>
<li><a href="#anonymous-functions">Anonymous functions</a></li>
<li><a href="#semicolons">Semicolons</a></li>
<li><a href="#strings-regular-expressions">Strings & regular expressions</a></li>
</ol>
</li>
<li><a href="#object-oriented-programming">Object-oriented programming</a>
<ol>
<li><a href="#objects">Objects</a></li>
<li><a href="#prototype-based-programming">Prototype-based programming</a></li>
<li><a href="#invoking-functions">Invoking functions</a>
<ol>
<li><a href="#function-invocation">Function invocation</a></li>
<li><a href="#method-invocation">Method invocation</a></li>
<li><a href="#constructor-invocation">Constructor invocation</a></li>
<li><a href="#indirect-invocation">Indirect invocation</a></li>
</ol>
</li>
<li><a href="#encapsulation">Encapsulation</a>
<ol>
<li><a href="#function-global-scope">Function & global scope</a></li>
<li><a href="#variable-hoisting">Variable hoisting</a></li>
<li><a href="#lexical-dynamic-scope">Lexical & dynamic scope</a></li>
<li><a href="#closures">Closures</a></li>
</ol>
</li>
<li><a href="#polymorphism">Polymorphism</a></li>
<li><a href="#function-arguments">Function arguments</a></li>
<li><a href="#modularity">Modularity</a></li>
</ol>
</li>
<li><a href="#dynamic-typing">Dynamic typing</a>
<ol>
<li><a href="#weak-typing">Weak typing</a></li>
<li><a href="#equality">Equality</a></li>
<li><a href="#-undefined-null-">undefined & null</a></li>
<li><a href="#truthiness-and-falsiness">Truthiness and falsiness</a></li>
</ol>
</li>
<li><a href="#functional-programming">Functional programming</a>
<ol>
<li><a href="#immutability">Immutability</a></li>
<li><a href="#higher-order-functions-recursion-lists">Higher-order functions, recursion & lists</a></li>
<li><a href="#libraries">Libraries</a></li>
</ol>
</li>
<li><a href="#monkey-patching">Monkey-patching</a></li>
<li><a href="#implementation">Implementation</a>
<ol>
<li><a href="#just-in-time-compilation">Just-in-time compilation</a></li>
<li><a href="#components-of-a-javascript-engine">Components of a JavaScript engine</a></li>
<li><a href="#garbage-collection">Garbage collection</a></li>
<li><a href="#representations">Representations</a>
<ol>
<li><a href="#numbers">Numbers</a></li>
<li><a href="#objects">Objects</a></li>
<li><a href="#arrays">Arrays</a></li>
</ol>
</li>
<li><a href="#benchmarks">Benchmarks</a></li>
<li><a href="#concurrency-parallelism">Concurrency & parallelism</a>
<ol>
<li><a href="#node-js">Node.js</a></li>
<li><a href="#callback-hell">Callback hell</a></li>
</ol>
</li>
</ol>
</li>
<li><a href="#compiling-to-javascript">Compiling to JavaScript</a></li>
<li class="unnumbered"><a href="#closing-thoughts">Closing thoughts</a></li>
<li class="unnumbered"><a href="#bibliography">Bibliography</a></li>
</ol>
</div>
</div>
<span class="spacer"></span>
<div class="chapter" id="chapter-1"><h3 id="introduction-history">I. Introduction & history</h3><div class="question">Which programming language are we talking about today?</div><div class="answer"><p>JavaScript, the language of the Internet.</p></div><div class="question">Why do you call it the ‘language of the Internet’?</div><div class="answer"><p>JavaScript is the primary programming language than can be used in a web browser. Whenever a site wants some client-side interactivity, JavaScript is <em>the</em> tool in the box for this task.</p></div><div class="question">What do you mean by ‘client-side’?</div><div class="answer"><p>Visiting a website involves two parties (or more): the visitor, i.e. the client, and the visited website, i.e. the server.</p><p>First of all, the client requests a web page from the server. The server then generates or retrieves the page to be sent to the client. The generation of this page will be performed by a program, which, of course, is written in a certain programming language. Programming languages used to write the program on the server, commonly called the <em>web server</em>, are called server-side languages.</p><p>The second part of the interaction takes place in the browser of the client. After receiving and rendering the web page, the web page would remain completely static, were it not for client-side languages. Programs written in a client-side language are sent along with the page to the client and are executed in the browser when the page is loaded. They provide a means to change the web page on the fly or to interact with the user without requiring a new page to be loaded.</p></div><div class="question">Is JavaScript the only language that can do that?</div><div class="answer"><p>There are several client-side languages that can do quite the same. Examples are Flash, Java,<span class="footnote">Through the use of Java Applets.</span> Silverlight, … but JavaScript is the most widely used. Virtually every web browser supports the execution of JavaScript.<span class="footnote">Text-based browsers like <a href="http://lynx.browser.org/" target="_blank">Lynx</a> and <a href="http://elinks.or.cz/" target="_blank">elinks</a> don’t support JavaScript.</span> JavaScript is used by roughly 75% of all Internet websites, see <a href="#bib-40" class="ref"><span class="bib">40</span> MAMA: Key findings</a>.</p><p>HTML, XHTML, CSS, … are also client-side languages, but are only used for mark-up.</p></div><div class="question">Why is JavaScript the most popular?</div><div class="answer"><p>Unlike other client-side languages like Flash or Java, JavaScript doesn’t require a plugin to function.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="naming-history">I.1. Naming & history</h4><div class="question">Glancing at the name, one can’t help but think JavaScript is related to Java. Is JavaScript perhaps the scripting variant of Java?</div><div class="answer"><p>To answer this question, we shall first tell you a bit about JavaScript’s history.</p><p>During the first browser wars<span class="footnote">The term <a href="http://en.wikipedia.org/wiki/Browser_wars" target="_blank">browser wars</a> is used to refer to the competition for dominance in usage share in the web browser market share.</span> in 1995, it had become clear that static HTML pages weren’t sufficient for the development of web applications. The Web needed a portable programming language.</p><p>At the time, Java was the new kid on the block and was rapidly gaining in popularity because of Sun’s successful marketing campaign. Netscape saw Java as the language of the Web, but Java was deemed too complex for beginning programmers. Java was the Web’s C++. Netscape needed a lightweight interpreted scripting language. If Visual Basic is C++’s easy alternative, Netscape wanted to develop a language that would be Java’s Visual Basic.</p><p>In April 1995, Netscape hired Brendan Eich to develop the programming language that would run in Netscape’s browser. The catch was that he had only <strong>10 days</strong> to deliver a working prototype. Eich was instructed to make it similar to Java, but was prohibited from using the object-oriented syntax reserved for Java.<span class="footnote">With <em>object-oriented syntax</em> we mean the keywords like <code>class</code>, <code>extends</code>, … More about this in <a href="#syntax" class="ref">Syntax</a>.</span> He combined the syntax from C and Java with a small number of relatively simple, but powerful, language features. The resulting language seems simple and easy at first sight, but the powerful features, certainly when combined, allow experienced programmers to build complex programs. Because of the short development time, corners were cut, and consequences thereof are still present in the language.</p><p>Source: <a href="#bib-22" class="ref"><span class="bib">22</span> JavaScript: Designing a Language in 10 Days</a></p><p>During development the language was named Mocha,<span class="footnote">This is a reference to Java, which is also a coffee made from beans produced in the Indonesian island of Java.</span> but it was officially renamed to LiveScript in 1995. Later that year LiveScript was renamed to JavaScript. For people unfamiliar with JavaScript’s origin and relation to Java, this caused lots of confusion, because besides syntax, JavaScript is quite different from Java. The reference to Java in JavaScript’s name was a slick marketing choice of Netscape to give JavaScript the attention it needed.</p><p>In 1996 JavaScript was renamed again to ECMAScript,<span class="footnote">ECMAScript comes from Ecma (European Computer Manufacturers Association) International, the standards organisation that standardised JavaScript in the ECMA-262 standard.</span> but JavaScript <em>stuck</em> and is still the most popular name for the language.</p></div><div class="question">Can you tell me more about the differences between JavaScript and Java?</div><div class="answer"><p>JavaScript has <a href="#dynamic-typing">dynamic</a> and <a href="#weak-typing">weak typing</a>, whereas Java is statically and strongly typed. Java programs are compiled to byte-code, while JavaScript is loaded from human-readable source code. JavaScript is <a href="#prototype-based-programming">prototype-based</a> whereas Java is class-based. JavaScript also has support for many higher-level programming features, e.g. <a href="#closures" class="ref">Closures</a>, that are not present in Java. So besides the similar name and syntax,<span class="footnote">JavaScript’s small standard library also follows Java’s naming conventions, e.g. the <code>Math</code> and the <code>Date</code> objects.</span> Java and JavaScript share very few features. These differences will be discussed in more detail later on.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="influences">I.2. Influences</h4><div class="question">So if Java is not the main inspiration for JavaScript, is there some other language that was JavaScript’s main inspiration? Or was JavaScript unique when it was created?</div><div class="answer"><p>If one ignores the syntax and the object-oriented nature, JavaScript is awfully similar to functional languages in the Lisp tradition, particularly Scheme. As a matter of fact, Brendan Eich, the creator of JavaScript, says that he was lured by Netscape promising him to make a Scheme for the browser, see <a href="#bib-11" class="ref"><span class="bib">11</span> Popularity</a>. A short time before, Brendan Eich had developed an interest in the famous <a href="#bib-1" class="ref"><span class="bib">1</span> Structure and Interpretation of Computer Programs</a> book, which presents the tremendous capabilities of a simple functional language, Scheme.</p><p>The main influence of Scheme was the presence of first-class functions in JavaScript, also see <a href="#functional-programming" class="ref">Functional programming</a>. Another similarity with Scheme is the small size of the language, a handful of built-in types, <a href="#closures">closures</a>, …</p><p>During the ’90s, when JavaScript was being developed, object-oriented programming was all the rage, so at the time, it was evident that JavaScript had to jump on the OO bandwagon. The object-oriented parts of JavaScript, most notably the presence of prototypes, are borrowed from Self, the programming language that pioneered <a href="#prototype-based-programming">prototype-based programming</a>. Self is a dialect of Smalltalk, according to some people, the true dynamic object-oriented programming language.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="scripting-language">I.3. Scripting language</h4><div class="question">JavaScript is a scripting language, what does it mean for a language to be a scripting language?</div><div class="answer"><p>A scripting programming language is actually a lightweight language that is mostly used for writing little programs to execute repetitive tasks. It’s a high-level language that is most often implemented by an interpreter.</p><p>As JavaScript is a high-level scripting language, it is garbage collected, thus not requiring the programmer to manually manage the memory like in C or C++. More about this topic in <a href="#garbage-collection" class="ref">Garbage collection</a>.</p><div class="question">How is JavaScript executed?</div><div class="answer"><p>JavaScript is executed by an interpreter.<span class="footnote"><a href="#implementation">Modern JavaScript engines</a> employ techniques like <a href="#just-in-time-compilation">JIT compilation</a> to compile JavaScript to native code at run-time.</span> The interpreter executes a JavaScript program line by line, from top to bottom.</p><div class="question" id="line-by-line">But when a program is executed linearly, you can’t refer to functions and variables that are defined later on in the program? Is this also true for JavaScript?</div><div class="answer"><p>Good question! The interpreter actually works in multiple stages: first all variables in the current scope are initialised to <code>undefined</code> and all functions are initialised with pointers to their locations in memory. After some other initialisations, the actual execution starts at the first line of code. This multi-phased approach makes it possible to have forward references in JavaScript. However, this seemingly logical step has some unwanted consequences, see <a href="#variable-hoisting" class="ref">Variable hoisting</a>. For more details on the execution, we refer you to <a href="#bib-23" class="ref"><span class="bib">23</span> What is the Execution Context & Stack in JavaScript?</a>.</p></div></div></div></div>
<div class="chapter" id="chapter-2"><h3 id="syntax">II. Syntax</h3><div class="question">Could you describe JavaScript’s syntax?</div><div class="answer"><p>As JavaScript syntax is mostly borrowed from C and Java, syntax you are familiar with, we shall only highlight where JavaScript deviates from Java’s or C’s syntax. Moreover, this document contains a myriad of code examples you can look at to get an idea of what JavaScript code looks like.</p><p>Besides the common keywords like <code>for</code>, <code>if</code>, <code>while</code>, <code>try</code>, <code>new</code>, … there are a number of <em>future reserved keywords</em> in JavaScript: <code>class</code>, <code>const</code>, <code>enum</code>, <code>export</code>, <code>extends</code>, <code>import</code>, <code>super</code>. These keywords aren’t used in JavaScript and probably never will. Identifiers cannot have the same name as a keyword. These keywords are a remnant of Java’s influence.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="variables-and-functions">II.1. Variables and functions</h4><p>As JavaScript is <a href="#dynamic-typing">dynamically typed</a>, the programmer doesn’t have to declare the types of variables or functions. To declare a new variable, prepend the <code>var</code> keyword to the identifier. A function definition is started with the <code>function</code> keyword.</p><pre>function f(x, y) {
var sum = x + y;
return sum;
}
f(3, 4); // 7
sum; // 'ReferenceError: sum is not defined' as sum was a local variable</pre><p>Watch what happens when we forget the <code>var</code> keyword:</p><pre>function f(x, y) {
sum = x + y;
return sum;
}
f(3, 4); // 7
sum; // 7 (!)</pre><p>Omitting the <code>var</code> keyword will declare the variable as a global! This is a typical pitfall of JavaScript. See <a href="#function-global-scope" class="ref">Function & global scope</a> and <a href="#modularity" class="ref">Modularity</a> for more about the global object and why this is a problem.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="anonymous-functions">II.2. Anonymous functions</h4><p>As told in <a href="#influences" class="ref">Influences</a>, thanks to Scheme, JavaScript has <a href="#functional-programming">first-class functions</a>. Whereas anonymous functions in Scheme are introduced by lambda-expressions, in JavaScript you can just omit the name of the function to create an anonymous function.</p><pre class="Scheme">(let ([f (lambda (x y) (+ x y))])
f); #<procedure:f></pre><pre>function f(x, y) { return x + y; }
f; // [Function]</pre><p>It’s also possible to assign a function to a variable.</p><pre>var f = function(x, y) { return x + y; };</pre><div class="question">Is this equivalent to the function declaration syntax seen in <a href="#variables-and-functions" class="ref">Variables and functions</a>?</div><div class="answer"><p>In most cases it is, but not always, see the following examples:</p><pre>function f() {
var z = x() + 1;
var x = function() { return 10; };
return z;
}
f(); // TypeError: x is not a function</pre><pre>function f() {
var z = x() + 1;
function x() { return 10; };
return z;
}
f(); // 11</pre><p>In the first example, <code>x</code> is called before it is defined. In the second example <code>x</code> is also defined after it is called, but using the other syntax for function definitions, resulting in a correct result.</p><p>The reason for this difference was mentioned in <a href="#line-by-line" class="ref">line by line execution</a> and will also be covered in <a href="#variable-hoisting" class="ref">Variable hoisting</a>.</p><blockquote>[..] all variables in the current scope are initialised to <code>undefined</code> and <strong>all functions are initialised with pointers to their locations</strong> in memory [..]</blockquote></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="semicolons">II.3. Semicolons</h4><p>A controversial feature in JavaScript is <em>semicolon insertion</em>. In C and Java, each statement or expression should be terminated with a semicolon, <code>;</code>. In JavaScript, terminating semicolons are optional, and will be inserted by the interpreter if absent. They aren’t just inserted willy-nilly after each line, there are rules for this, which we shall not cover. However, there are some edge cases where semicolon insertion will mess up your program.</p><pre>function f(a, b) {
return
a + b;
}
f(1, 2); // undefined
// Treated as:
// return;
// a + b;
// But:
var a = 1,
b = a
(1 + 1).toString() // TypeError: a is not a function
// Treated as:
// b = a(1 + 1).toString();</pre><p>Source: <a href="#bib-35" class="ref"><span class="bib">35</span> JavaScript Syntax</a></p><div class="question">What do you recommend: always writing semicolons or not?</div><div class="answer"><p>As you saw in the code sample above, a semicolon would have prevented the problem in the second example, but not in the first. Like indentation width,<span class="footnote">And the famous <a href="http://www.jwz.org/doc/tabs-vs-spaces.html" target="_blank">tabs versus spaces war</a>.</span> semicolons are often considered a question of convention or style.<span class="footnote">Trivial matters often lead to heated discussions, see for example <a href="https://github.com/twitter/bootstrap/issues/3057" target="_blank">this discussion about a single semicolon</a>.</span></p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="strings-regular-expressions">II.4. Strings & regular expressions</h4><p>Like most scripting languages, but unlike C and Java, strings can be delimited with single (<code>''</code>) or double quotes (<code>""</code>). This comes in handy when constructing HTML, in which attributes appear between double quotes, from strings.</p><p>Regular expressions have a literal syntax in JavaScript, which is also typical of a scripting language.</p><pre>'Wubwobwab'.replace(/([aou])b/g, '$1p$1');
// Wupuwopowapa</pre></div></div>
<div class="chapter" id="chapter-3"><h3 id="object-oriented-programming">III. Object-oriented programming</h3><div class="question">You said that JavaScript is an object-oriented language, could you expand on that?</div><div class="answer"><p>Indeed, JavaScript is object-oriented. Typically, in object-oriented languages, everything is an object (e.g. Python, Scala, Ruby, Eiffel, …) In JavaScript this is not the case, there are both objects and primitives. The primitives in JS are <code>Number</code>s, <code>String</code>s, <code>Boolean</code>s, and the special types <code>null</code> and <code>undefined</code>. The objects include <code>Array</code>, <code>Function</code>, <code>Date</code>, <code>RegExp</code>, <code>Error</code>, … This design decision, by many people considered a mistake, was carried over from Java.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="objects">III.1. Objects</h4><p>Objects in JavaScript are in fact containers of properties, where each property has a name and a value. To create a method, assign a function to a property’s value. This demonstrates the importance of the presence of first-class functions. Objects in JavaScript can be compared with untyped hash maps from strings to values from any kind, similar to Python’s dicts, Ruby’s hashes, … The name of a property can be any string, but the quotes can be dropped if the name of the property is a valid JavaScript identifier. The quotes are required when the property name is a reserved keyword, an empty string, or other strings not constituting valid JavaScript identifiers.</p><pre data-name="person">var emptyObject = {};
var person = {
name: "Erin",
age: 28,
"place-of-birth": "Gibraltar", // hyphens are not allowed in JavaScript identifiers
walk: function () { return "Do bi do ... walking, walking, walking"; }
};</pre><p>Property lookup is done via the <code>.</code> notation. When the property name is not a valid JavaScript identifier, one has to use the bracket notation. Looking up a property of which the value is a function, just returns that function. To actually invoke it, terminate the expression with <code>()</code>.</p><pre data-name="person-usage" data-depends="person">person.name; // "Erin"
person["place-of-birth"]; // "Gibraltar"
person.walk; // [Function]
person.walk(); // "Do bi do ... walking, walking, walking"</pre><p>This notation of objects is compact, easy to read and parse, and has become a popular general data-interchange format, called <a href="http://www.json.org/" target="_blank">JSON</a> (JavaScript Object Notation).</p><p>JavaScript has no separate hash map type. Since objects function as hash maps, they are often (ab)used as hash maps. Conflating objects with hash maps can have some unwanted consequences, see the examples in <a href="#monkey-patching" class="ref">Monkey-patching</a>.<span class="footnote">The next JavaScript standard will contain a separate <code>Map</code> type.</span></p><p>As the keys of an object are required to be strings, any key that isn’t a string will first be converted to a string, which can cause some surprising results. See the following example.</p><pre>var z = {};
z[0] = 3;
z[0]; // 3
z['0']; // 3
z[[0]]; // 3, as [0].toString() == '0'</pre></div><div class="question">Object-oriented programming includes more than “everything is an object”. What about polymorphism, inheritance, etc.?</div><div class="answer"><p>Of course, OOP is broader than “everything is an object”. Most definitions of object-oriented programming include features such as modularity, encapsulation, polymorphism, inheritance, …</p><p>JavaScript has support for most of them, but differs from other classical OO languages in the implementation of these features. Take for instance inheritance. Classical OO languages mostly feature a class-based inheritance mechanism, whereas JavaScript has prototype-based inheritance. JavaScript often has a different way of doing things compared to other languages, this will be a recurring theme.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="prototype-based-programming">III.2. Prototype-based programming</h4><div class="question">What entails prototype-based inheritance?</div><div class="answer"><p>A better term would be prototype-based programming, as inheritance is just one ingredient of this style of object-oriented programming. Prototype-based programming can easily be explained by comparing it with class-based programming.</p><p>In class-based programming, one defines <em>classes</em>. Each class consists of fields and methods. To use a class, one <em>instantiates</em> a new object of the class, which will have the fields and methods defined in the class. The values of the fields can differ from object to object. Let’s make an analogy: the class is the blueprint of the car, and the objects are cars built from the blueprint. Now let’s throw inheritance in the mix. One can define a class that inherits from another class. This new class will contain all the fields and methods of the parent class, but can add fields and methods, and can also override fields and methods.</p><p>In prototype-based programming, one defines <em>objects</em>. Each object will consist of fields and methods, or in JavaScript’s case, <em>properties</em>. The whole concept of classes is removed from the equation. Instead of defining a blueprint to build new cars with, one just builds a car. But does this mean that we have to build every car from scratch, i.e. (re)define the fields and methods for every objects we want to use? No, to make a new object with the same fields and methods as another object, we <em>clone</em> the old object to get a new one. In other terms: we define a new object with the old object as <em>prototype</em>. Inheritance is also done via cloning, but after the cloning, the new object is extended with new fields and/or methods, and existing fields and/or methods can also be overriden. This new object can, in turn, be used as a prototype for other objects.</p><div class="question">Could you show how it’s done in JavaScript?</div><div class="answer"><p>In JavaScript, objects can be created via object literals. In this case, <code>Object</code>, the top of the inheritance hierarchy, will be their prototype.</p><pre>var o = {foo: "bar"};
// Object.getPrototypeOf(x) returns the prototype of x
Object.getPrototypeOf(o); // {}, which is an empty Object</pre><p>Another way to create objects in JavaScript, is via the <code>new</code> keyword, which you probably know from C++, Java, etc. The <code>new</code> keyword should be followed by a function call. The function after the <code>new</code> keyword is called the constructor. Objects created this way will have their constructor’s prototype as their prototype.</p><pre>// Car is a constructor
function Car(make) {
this.make = make;
};
Object.getPrototypeOf(Car); // [Function: Empty] is the prototype of a function
// Define a new method for Car
Car.prototype.drive = function() {
println("Vroom");
};
var myCar = new Car("BMW");
Object.getPrototypeOf(myCar); // { drive: [Function] }, the prototype of Car</pre><p>Notice that the name of the constructor function is capitalised. This is a convention carried over from Java.</p><div class="question">If the naming is only a convention, how then differs a constructor from a regular function?</div><div class="answer"><p>It doesn’t actually, it’s the use of <code>new</code> keyword that makes a regular function act like a constructor. By prepending this keyword to the function invocation, a couple of things happen, see <a href="#constructor-invocation" class="ref">Constructor invocation</a>.</p></div><div class="question">If methods are just properties that are functions, why don’t you just define them in the constructor instead of defining them on the prototype? The latter seems more verbose.</div><div class="answer"><p>If we were to define the methods in the constructor, copies of these methods would be created for every object created via the constructor. The methods defined on the prototype don’t have to be copied, but are inherited.</p></div><p>Here’s another example of inheritance in JavaScript.</p><pre>// Create a new object that inherits from obj
function inherit(obj) {
function f() {}; // Dummy constructor
// The new object's prototype is obj
f.prototype = obj;
// Make the new object
return new f();
}
// Create a new object from scratch
var a = {x: "a's x"};
// Create a new object by cloning an existing object
var b = inherit(a);
// Change the value of b's x property
b.x = "b's x";
// This change only affects b
a.x; // "a's x"
b.x; // "b's x"</pre></div><div class="question">What are the pros and cons of prototype-based programming?</div><div class="answer"><p>Prototype-based programming gives the programmer more flexibility and freedom to define and redefine the fields and methods of objects dynamically. Instead of focusing on building a brittle taxonomy of classes as in class-based programming, the focus lies on making a set of objects with the desired behaviour, reusing their behaviour via cloning, and modifying their behaviour when it’s required. When building a taxonomy, it is often the case that some class at the bottom of the hierarchy inherits some unwanted fields or methods, as it is not always possible to classify everything in a consistent taxonomy. Prototype-based programming gives you the freedom to clone and override the fields and methods of other objects at will.</p><p>For example, you have a bunch of <code>Cat</code> objects, but you want one of the cats, named Dexter, to make a different meow-sound. You can simply change the <code>meow</code> method of Dexter, a single <code>Cat</code> object, without affecting the others, or having to define a new subclass of <code>Cat</code> just for Dexter.</p><p>Having so much control over which fields and methods to <em>inherit</em> allows the programmer to do things not possible in class-based languages without language support, for instance, traits can easily be emulated using prototype-based programming. Even classes can be and often are emulated.</p><p>Let’s show you how to emulate classes using prototypes:</p><pre data-name="car">function Car(make) {
this.make = make;
};
Car.prototype.drive = function() {
println("Vroom");
};
// Constructor for the subclass SportsCar
function SportsCar(make) {
this.make = make;
};
// The prototype of SportsCar is a regular Car
SportsCar.prototype = new Car;
// We change the constructor, because we inherited Car's constructor
SportsCar.prototype.constructor = SportsCar;
SportsCar.prototype.driveFast = function() {
this.drive(); this.drive();
};
// Instantiate a new SportsCar
var mySportsCar = new SportsCar("BMW");
mySportsCar.driveFast();
// Vroom
// Vroom</pre><p>The steps to create a subclass are often put together in a single function, allowing easy class-based inheritance.</p><p>Traits are also easy to emulate, although we don’t have access to the super objects anymore. Abstract members can also be emulated, but will not be checked at compile-time for presence.</p><p>The methods are simply copied over from the trait object to the other object.</p><pre data-name="trait" data-depends="car">// The Trait we define
var HasTires = {
tiresOk: true,
puncture: function() {
this.tiresOk = false;
}
};
// Add the properties of the trait to the prototype of obj
var mixin = function(obj, trait) {
for (var prop in trait) {
obj.prototype[prop] = trait[prop];
}
};
// We'll continue with the SportsCar defined above
mixin(SportsCar, HasTires);
// The already defined mySportsCar now has the functionality defined in
// the HasTires trait
mySportsCar.puncture();
mySportsCar.tiresOk; // false</pre><p>Of course, freedom comes with a price. One of the disadvantages are the slower field and method accesses/dispatches and to a lesser extent the memory overhead. When cloning an object, the fields and methods aren’t cloned. It would be wasteful to clone this reusable data. Instead, the cloned object keeps track of its prototype. Whenever an inherited field or method of the new object, i.e. a field or method defined in the prototype (or a prototype of the prototype), is accessed, the new object delegates the call to the prototype. This delegation will go on until a definition is found in one of the ancestor prototypes. The longer this <em>chain</em> of prototypes, the costlier a field access or method call.</p><p>Another disadvantage is that it becomes harder to figure out which fields and methods an object has, and where they were defined. When using classes, knowing the class of an object is enough to know which fields and methods an object has (this, of course, includes looking at superclasses). A class functions as the type of the object, but in JavaScript properties can be added and removed from objects at run-time.</p></div></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="invoking-functions">III.3. Invoking functions</h4><p>In JavaScript, a function can be invoked in four different ways:</p><ul><li>As a function</li><li>As a method</li><li>As a constructor</li><li>Indirectly through <code>call</code> or <code>apply</code></li></ul><p>Functions can behave differently depending on the kind of invocation. For instance, the value of <code>this</code> will be different. In JavaScript, as in most object-oriented languages, <code>this</code> is a special keyword inside the context of a function that refers the object of which the function is a method, i.e. the owner of the method.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="function-invocation">III.3.1. Function invocation</h5><p>Function invocation is the regular kind of invocation, like you would call functions (or procedures) in C, Haskell, or Lisp, i.e. in a non-OO language.</p><p>For example:</p><pre>function add(x, y) {
return x + y;
}</pre><p>Functions that don’t contain an explicit <code>return</code>-statement, will return <code>undefined</code>, JavaScript’s <code>void</code>.</p><p>In the case of a regular function invocation, the value of <code>this</code> will be the global object. See <a href="#function-global-scope" class="ref">Function & global scope</a> and <a href="#modularity" class="ref">Modularity</a> for more about the global object.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="method-invocation">III.3.2. Method invocation</h5><p>A function is considered a method when it’s the property of an object. The big difference between function and method invocation, is that in the case of method invocation, <code>this</code> will refer to the object on which the method is called, instead of the global object.<span class="footnote">When evaluating the code example below, the results will differ from the predicted outcome, because the code example isn’t executed in the global scope.</span></p><pre>function f() {
return this.x;
}
// Function invocation
var x = 1;
f(); // 1
// Method invocation
var o = {x: 2, f: f};
o.f(); // 2</pre><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="constructor-invocation">III.3.3. Constructor invocation</h5><p>When a function or method invocation is preceded by the <code>new</code> keyword, it is a constructor invocation.</p><p>A few things are different for constructor invocations:</p><ul><li>A new object is created and will be accessible via <code>this</code>.</li><li>The prototype of the constructor function is stored as the prototype of the new object.</li><li>The newly created object is automatically returned at the end of the function call, no explicit <code>return</code> is required.</li><li>When the constructor has no parameters, the parentheses after the function name are optional. E.g. <code>new Object()</code> vs <code>new Object</code>.</li></ul><div class="question">So you’re saying, every function can be invoked as a constructor? What is the point of that?</div><div class="answer"><p>The ability to invoke every function as a constructor isn’t very useful. The <code>new</code> keyword is rather dangerous, certainly when it’s forgotten. Not prepending a constructor call with <code>new</code> will cause the properties defined in the function to be added to the global object instead of a newly created object. A reason for the inclusion of the <code>new</code> keyword is the familiarity from other object-oriented languages. And, of course, there still has to be a way to create a new object.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="indirect-invocation">III.3.4. Indirect invocation</h5><p>The fourth and final kind of invocation, is indirect invocation. As <code>Function</code>s are also <code>Object</code>s in JavaScript, they can have methods. Two of the available methods of <code>Function</code>s are <code>call</code> and <code>apply</code>.<span class="footnote">For readers familiar with Common Lisp (or a <a href="http://en.wikipedia.org/wiki/Lisp-1_vs._Lisp-2#The_function_namespace" target="_blank">Lisp-2</a> to be more precise), <code>call</code> is similar to Common Lisp’s <code>funcall</code>. For readers familiar with any Lisp dialect, JavaScript’s <code>apply</code> is similar to most Lisp’s <code>apply</code>.</span></p><p>The <code>call</code> method is invoked on a function and takes at least one argument, the object to which <code>this</code> will refer in the context of the function. Extra arguments are passed to the function.</p><p>The <code>apply</code> method is invoked on a function and takes at least one argument, the object to which <code>this</code> will refer in the context of the function. The optional second argument should be an <code>Array</code>, holding the arguments that will be passed to the function.</p><pre>
function f(x, y) {
return [this, x, y];
}
f.call({a: 'foo'}, 1, 2); // [ { a: 'foo' }, 1, 2 ]
f.apply({a: 'foo'}, [1, 2]); // [ { a: 'foo' }, 1, 2 ]</pre><div class="question">Can you give me a use case of these <code>call</code>- and <code>apply</code>-methods?</div><div class="answer"><p>A possible use case is the reuse of methods. Let’s say we have an object (or a class) A with some methods. We also have some other, totally unrelated object B. There might be a method defined on A that we wish to invoke on B too. Instead of copying the method from object A to object B, or making A B’s prototype, we can simply invoke the method on object B.</p><p>Essentially, we bypass the inheritance tree, and are able to reuse methods defined for other objects.</p><pre>// Object/Class A
var Person = function(name) { this.name = name; };
Person.prototype.introduce = function() {
return "Hello, my name is " + this.name;
};
// Object B. We don't want B to inherit from A. We could add the
// `introduce`-method as a property to B, but indirect invocation is much
// cheaper than copying the method, and then performing a method
// invocation.
var car = {name: 'Mater', town: 'Radiator Springs'};
Person.prototype.introduce.call(car);</pre></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="encapsulation">III.4. Encapsulation</h4><p>Another example of JavaScript’s <em>exotic</em> way of doing things is encapsulation. Most classical OO languages support visibility modifiers (<code>private</code>, <code>public</code>, …) to control the accessibility of fields and methods by other classes. In JavaScript, there are no such modifiers, but encapsulation is still achievable, via the use of closures.</p><p>Example:</p><pre class="Java">class A {
private int counter = 0;
public void inc() {
counter++;
}
}
..
A a = new A();
a.inc(); // OK
a.counter; // Error: not visible!
..</pre><pre>var a = (function () {
var counter = 0;
return {
inc: function() {
return ++counter;
},
};
})();
a.inc(); // 1
a.counter; // Not visible: undefined</pre><div class="question">What is a closure?</div><div class="answer"><p>Before explaining what a closure is, you have to know some things about (JavaScript’s) scoping rules.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="function-global-scope">III.4.1. Function & global scope</h5><p>JavaScript’s scoping rules differ from common languages like C and Java. In C and Java, curly braces (<code>{…}</code>) delimit different scopes. The body of a function, a while-loop, a for-loop, a class (in the case of Java), all have a separate scope (known as <em>block scope</em>). In JavaScript, there are only two kinds of scope: the global scope and function scope.</p><p>Let’s look at some examples of these differing scoping rules:</p><pre class="Java">for (int i = 0; i < 10; i++) {
// ...
}
System.out.println(i); // Error: i is undefined here,
// it is only accessible within the scope of the body
// of the for-loop.
int a = 10;
{
// A new scope
a = 3;
}
System.out.println(a); // 10</pre><pre>for (var i = 0; i < 10; i++) {
// ...
}
println(i); // 10
var a = 10;
{
// No new scope
a = 3;
}
println(a); // 3</pre><p>By default all variables will be defined in the global scope, i.e. they will be global variables. This sends cold shivers down many a programmer’s spine. The only way to delimit the scope of variable definitions is by wrapping them in a function.</p><pre>var x = 3;
(function() {
var x = 10;
println(x); // 10
})(); // This function is invoked immediately after definition
println(x); // 3</pre><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="variable-hoisting">III.4.2. Variable hoisting</h5><p>We shall now introduce another peculiarity of JavaScript’s scoping rules, <em>variable hoisting</em>.</p><pre>var f = function() {
return y;
};
// ...
var y = 3;
f(); // 3</pre><p>In the example above, we define the function <code>f</code> which returns the value of the undefined variable <code>y</code> when called. A bit later in the program, but still in the same scope (global or function), we define the variable <code>y</code>. Finally, we invoke <code>f</code>, which returns <code>3</code>. As JavaScript is executed line by line, shouldn’t the definition of <code>f</code> fail with an error message complaining about the undefined variable <code>y</code>? What actually happens, is that all variable declarations in the current scope are moved to the beginning of the scope. Only the declarations, not the initialisations.</p><p>What happens under the hood is the following:</p><pre>var f, y;
f = function() {
return y;
};
// ...
y = 3;
f(); // 3</pre><p>In this case, some people might consider variable hoisting to be advantageous, but that’s not always the case, see the following example:</p><pre>var x = 0;
function f() {
println("A: " + x);
var x = 1;
println("B: " + x);
}
f();
// A: undefined
// B: 1</pre><p>Most programmers would expect the first <code>println</code>-statement to print out <code>A: 0</code>. What actually happens is the following:</p><pre>var x = 0;
function f() {
var x; // x is now declared, but uninitialised, i.e. `undefined`
println("A: " + x);
x = 1;
println("B: " + x);
}
f();</pre><p>This phenomenon is called <em>variable hoisting</em>. The variable declarations are hoisted to the top of the scope, but the initialisations are left in place.</p><div class="question">Why does JavaScript do this?</div><div class="answer"><p>We explained this in the answer to the question about <a href="#line-by-line" class="ref">line by line execution</a>.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="lexical-dynamic-scope">III.4.3. Lexical & dynamic scope</h5><p>We assume you’re already familiar with lexical and dynamic scoping, so we’ll quickly glance over it.</p><p>In the case of lexical scoping, functions are invoked in the scope that was active during the definition of the function. In the case of dynamic scoping, functions are invoked in the scope active during the invocation of the function. Let’s show difference with an example.</p><pre>var f = (function() {
var z = 'lexical';
return function() {
return z;
};
})();
var z = 'dynamic';
f(); // 'lexical' when lexically scoped,
// 'dynamic' in the other case</pre><p>JavaScript is lexically scoped, as is Scheme, one of JavaScript’s biggest <a href="#influences">influences</a>. The return value of the call to <code>f</code> in the example above will be ‘lexical’.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="closures">III.4.4. Closures</h5><p>Let’s have another look of the example that we showed you to demonstrate encapsulation.</p><pre>var a = (function () {
var counter = 0;
return {
inc: function() {
return ++counter;
},
};
})();
a.inc(); // 1
a.counter; // Not visible: undefined</pre><p>As JavaScript is lexically scoped, functions have to capture the scope that was active during their definition. Essentially, what happens is that all variables defined in a scope outside the defined function but referenced from within the scope of the function, known as <em>free variables</em>, have to be captured. In the example above, the function defined on line 4 references a variable <code>counter</code> (line 5), that was defined in another scope (line 2). The free variables are <em>closed</em>-over, they are <em>captured</em> by the closure. One can think of a closure as a pair of a function, i.e. code, and its environment, i.e. data.</p><p>Encapsulation can be achieved by defining the variables meant to be private in a function (scope) A, and defining a new function B within A, that references these variables. The closure of function B will capture these private variables. By holding on to function B, but discarding function (scope) A, only B will be able to access these private variable,<span class="footnote">Unless function B leaks them via its properties.</span> effectively achieving encapsulation.</p><p>The following example<span class="footnote">Taken from the <a href="http://www.dartlang.org/docs/dart-up-and-running/ch02.html#for-loops" target="_blank">Dart Language Tour</a>.</span> demonstrates a common pitfall with closures (and scope) in JavaScript:</p><pre>var closures = [];
for (var i = 0; i <= 1; i++) {
var f = function() { println(i); } // f will print i when invoked
closures.push(f);
}
closures[0](); // 2, why not 0?
closures[1](); // 2, why not 1?</pre><p>What happens is that the <em>variable</em> is captured by the closure, not the <em>value</em> of the variable during the capture. Because JavaScript has no separate scope for the body of a for-loop, the variable <code>i</code> is in scope during the whole example. The for-loop stops when variable <code>i</code> is greater than <code>1</code>, i.e. <code>2</code>, this explains why both closures print the number <code>2</code>.</p><p>The solution to this problem is to wrap the definition of <code>f</code> in another function which takes the variables that will be captured as arguments, effectively creating a new scope/closure, and invoking it immediately with the variable to capture as argument. Function arguments are passed by value, not by reference.</p><pre>var closures = [];
for (var i = 0; i <= 1; i++) {
var f = (function(i) {
return function() {
println(i);
};})(i);
closures.push(f);
}
closures[0](); // 0
closures[1](); // 1</pre></div><div class="question">What are the advantages of implementing encapsulation via closures?</div><div class="answer"><p>Actually, one could call it <em>emulating</em> encapsulation via closures. Because of the absence of built-in encapsulation via visibility modifiers, JavaScript programmers are required to implement encapsulation manually via closures. So one could call it a disadvantage of JavaScript, although some people argue against encapsulation.</p><p>With closures, the programmer has more control over encapsulation, but has to do more work to achieve it.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="polymorphism">III.5. Polymorphism</h4><p>Polymorphism in JavaScript is achieved through inheritance or duck typing.</p><p>An example of polymorphism through inheritance:</p><pre>// Superclass Animal
var Animal = function(name) { this.name = name; };
// Default implementation of makeNoise
Animal.prototype.makeNoise = function() { return "Silence"; };
// Subclass Dog
var Dog = function(name) { this.name = name; };
Dog.prototype = new Animal();
// Override makeNoise
Dog.prototype.makeNoise = function() { return "Bark"; };
// Subclass Turtle
var Turtle = function(name) { this.name = name; };
// Don't override makeNoise
Turtle.prototype = new Animal();
var animals = [new Dog("Pluto"), new Turtle("Jeffrey")];
for (var i = 0; i < animals.length; i++) {
println(animals[i].makeNoise());
}
// Bark
// Silence</pre><p>Example of polymorphism through duck-typing:</p><pre>var Dog = function(name) {
this.name = name;
this.makeNoise = function() { return "Bark"; };
};
var Turtle = function(name) {
this.name = name;
this.makeNoise = function() { return "Silence";};
};
var animals = [new Dog("Pluto"), new Turtle("Jeffrey")];
for (var i = 0; i < animals.length; i++) {
println(animals[i].makeNoise());
}
// Bark
// Silence</pre><blockquote>Duck-typing is a style of dynamic typing in which an object’s methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.<br><span class="cite">—<a href="http://en.wikipedia.org/wiki/Duck_typing">Wikipedia on Duck typing</a></span></blockquote><p>In the example above, all objects have the required <code>makeNoise</code> function as a property, thus satisfy the required <em>semantics</em>.</p><div class="question">Which of the two is preferable, polymorphism through inheritance, or through duck typing?</div><div class="answer"><p>To obtain polymorphism through inheritance, you have to set up the inheritance relation, including boilerplate code (constructors, method prototypes, …). This requires more work from the programmer. The advantage of this approach is that the methods can be inherited from prototypes of objects, requiring less memory than storing a method for each object.</p><p>Duck typing is more ad-hoc: it’s sufficient to add the appropriate methods to the objects that will participate in this application of polymorphism. You don’t have to set up the inheritance relation.</p></div><div class="question">You mentioned that one can <em>override</em> a method in JavaScript, is it also possible to <em>overload</em> a method in JavaScript?</div><div class="answer"><p>To be clear, a method (or function) overloads another method if it has the same name, but differs in the number of arguments or the types of the expected arguments. The right method to call is chosen statically, at compile-time. Overloading is a feature typically present in statically typed languages. With JavaScript being a dynamically typed language, the compile-time resolution that determines which method to call is ruled out, as the types are not known in advance.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="function-arguments">III.6. Function arguments</h4><p>Overloading based on arity is possible in dynamically typed languages, but not in JavaScript. The reason being that JavaScript doesn’t check whether a function is called with the correct number of arguments. JavaScript will happily allow you to call a function expecting two arguments with 0, 1, 2, 3, … arguments. Missing arguments will be <code>undefined</code>. JavaScript also allows you to access the excess arguments via the <code>arguments</code> object. The <code>arguments</code> object is a local variable accessible within all functions. It is similar to an Array, but not quite the same. The elements of <code>arguments</code> can be accessed, and it has the <code>length</code>-property, but the other methods available for <code>Array</code>s cannot be used on the <code>arguments</code> object. One can convert the <code>arguments</code> object to an actual array, by calling <code>Array</code>’s <code>slice</code>-method on it, like so: <code>var args = Array.prototype.slice.call(arguments);</code>.<span class="footnote">The <code>slice</code>-method of <code>Array</code> copies the elements into a new array, it optionally takes start- and end-indexes. See <a href="#indirect-invocation" class="ref">Indirect invocation</a> for more about the <code>call</code>-method.</span></p><div class="question">What’s the point of this <code>arguments</code> object? And why isn’t it a proper <code>Array</code>?</div><div class="answer"><p>The <code>arguments</code> object allows the programmer to define methods expecting a variable number of arguments.</p><p>Example:</p><pre>// Sums all its arguments. The argument list is empty, because we'll
// use the arguments object.
function addAll() {
var args = Array.prototype.slice.call(arguments);
var total = 0;
// args.shift() removes the first element from the array, and
// returns that element.
while (args.length > 0) total += args.shift();
return total;
}</pre><p>Even when expecting a fixed number of arguments, the programmer can benefit from access to the <code>arguments</code> object. For instance, when implementing a decorator.</p><pre>function decorate(toDecorate, decorator) {
return function() {
// Both the decorator and the function to decorate can be
// called with the same arguments.
decorator.apply(null, arguments);
return toDecorate.apply(null, arguments);
};
};
function argsPrinter() {
var args = Array.prototype.slice.call(arguments);
println("Arguments: " + args.join(", "));
};
function add(x, y) { return x + y; };
decorate(add, argsPrinter)(1, 2);
// Arguments: 1, 2
// => 3</pre><p>The reason that the arguments object isn’t a proper <code>Array</code>, is <em>probably</em> the following:</p><blockquote>The concept of the <code>arguments</code> object has been on the language since the very beginning, it’s even described in the ECMAScript First Edition Standard. In that version of ECMAScript, the <code>Array.prototype</code> was really basic, array objects contained <em>only 4 methods</em>: <code>toString</code>, <code>join</code>, <code>reverse</code> and <code>sort</code>. I think that’s one of the major reasons about they make <code>arguments</code> to inherit from <code>Object.prototype</code>, at that time those <code>Array</code> methods didn’t look too <em>useful</em>. But the <code>Array.prototype</code> object was extended in the next versions of the standard, now on ES5, <code>Array</code> objects have methods such as <code>map</code>, <code>reduce</code>, <code>every</code>, <code>some</code>, etc, that are <em>really powerful</em>. […]<br><span class="cite">—<a href="http://stackoverflow.com/a/3242693">CMS's answer on StackOverflow</a></span></blockquote></div><p>JavaScript’s loose call convention, and the presence of the <code>arguments</code> object allows the programmer to emulate overloading by doing the resolution at run-time.</p><pre class="Java">void overloaded() { return "No args"; }
void overloaded(int x) { return "A number"; }
void overloaded(String x) { return "A string"; }
void overloaded(int x, String y) { return "A number and a string"; }</pre><pre>function overloaded(arg1, arg2) {
// One could also use an if-then-else construction
switch (arguments.length) {
case 0: return "No args"; break;
case 1: switch (typeof(arg1)) {
case 'number': return "A number"; break;
case 'string': return "A string"; break;
}
break;
case 2: if (typeof(arg1) == 'number' && typeof(arg2) == 'string')
return "A number and a string";
}
}
// Identical for the Java program
overloaded();
// No args
overloaded(1);
// A number
overloaded("foo");
// A string
overloaded(1, "foo");
// A number and a string</pre><p>In practice, these <code>return</code>-statements would be replaced with different blocks of code, specific for each case.</p><p>Of course, doing this resolution at run-time has a negative impact on the performance.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="modularity">III.7. Modularity</h4><p>An important cornerstone of object-oriented programming is code reuse. In order to reuse code, it’s helpful, or rather often of paramount importance to organise code into modular components. We’ll use the term <em>module</em> for such a modular component. Such modules should provide a clear interface of the offered functionality, as well as the required functionality.</p><p>Modules often function as a namespace, take for example a look at Java, where packages or classes act as modules.</p><p>Originally, JavaScript was intended to augment static web pages with little scripts, making the page more dynamic. JavaScript was designed with this goal in mind. Little scripts don’t need namespaces, packages, or modules. They were often thrown together in a single file. As we saw in <a href="#function-global-scope" class="ref">Function & global scope</a>, variables and functions defined outside the context of a function, become global variables. Every script executed on a web page executes in the same context, the global object. This object is directly accessible via the <code>window</code> variable, the name of this object immediately reveals JavaScript tight coupling with the browser. All globals are properties of this <code>window</code> object.<span class="footnote">When evaluating the code example below, the results will differ from the predicted outcome, because the code example isn’t executed in the global scope.</span></p><pre>var x = 3;
x; // 3
window.x; // 3</pre><p>This global object is the default namespace. Imagine loading some third-party scripts, for example scripts that add advertisements to your website. They will be executed in the same context as your own scripts. They can call into your code, or override your functions when names conflict. Not only is the global object a problem in terms of namespacing and modularisation, it’s also a security issue.</p><p>JavaScript has no concept of a module or any language features for namespacing. But, as we saw a couple of times already, JavaScript provides sufficient means to emulate them.</p><p>The construct we’ll use to emulate a module is a closure (see <a href="#closures" class="ref">Closures</a>). Recall that we emulated <a href="#encapsulation" class="ref">Encapsulation</a> via closures. A closures provides us with two useful ingredients: <em>privacy</em> and <em>state</em>. We have control over the visibility of the variables declared in the scope of the closure, as well as their state.</p><p>By wrapping the code constituting the module in a closure, we prevent it from tainting the global namespace. Forgetting the <code>var</code> keyword will still create global variables though, see <a href="#variables-and-functions" class="ref">Variables and functions</a>.</p><pre>(function() {
var x = 3;
var _privateVar = 1;
var f = function(a) { return a * a; };
// Here come other variables and function definitions
// ...
})();
f(x); // ReferenceError: f is not defined</pre><p>Currently, the functionality of our module is only accessible inside the module. The next thing to do is to export the functionality so it can be used by other modules. This is accomplished by letting the closure return an object containing the exported variables and functions. This object acts as a namespace for the exported functionality of the module. These namespace can be nested, by embedding other namespace objects inside them.</p><pre data-name="myModule">var myModule = (function() {
var module = {};
module.x = 3;
var _privateVar = 1; // Not exported
module.f = function(a) { return a * a; };
// Here come other variables and function definitions
// ...
return module;
})();
myModule.f(myModule.x); // 9</pre><p>To use functionality from other modules, we just pass the module object as an argument to the closure.</p><pre data-name="otherModule" data-depends="myModule">var otherModule = (function(m) {
var module = {};
module.f = function(a) { return m.f(a) * a; };
return module;
})(myModule);
otherModule.f(myModule.x); // 27</pre><p>This approach is also known as the <em>Module Pattern</em>.</p><p><a href="#node-js" class="ref">Node.js</a> employs a similar approach, albeit with less boilerplate code. There is a one-to-one mapping of files to modules. The code of every file is executed in a separate context, preventing the code from tainting the global namespace. To actually export variables or functions, they have to be attached to <code>exports</code>-object. The <code>exports</code>-object is a free variable within the context of each file. To use the functionality of another module, one has to <code>require</code> the file containing the module. The result of this call to the <code>require</code>-function returns the <code>exports</code>-object of the corresponding module.</p><pre class="NodeJS">// File a.js
var x = 3;
exports.f = function(a) { return x + a; };
// File b.js
var a = require('a.js');
a.f(5); // 8</pre></div></div>
<div class="chapter" id="chapter-4"><h3 id="dynamic-typing">IV. Dynamic typing</h3><div class="question">What kind of typing discipline does JavaScript have?</div><div class="answer"><p>Unlike for instance Java, a language people believe to be akin to JavaScript when comparing their names, JavaScript isn’t statically typed, but dynamically typed.</p><p>The types of <em>variables</em> aren’t known at <em>compile</em>-time, but the types of the <em>values</em> are known at <em>run</em>-time. Programmers don’t have to annotate functions and variables with types like in statically typed programs.<span class="footnote">In statically typed languages with <em>type inference</em>, e.g. ML, Haskell, … it is also not required to declare the types.</span></p><div class="question">Why did JavaScript’s creator choose to make JavaScript dynamically typed?</div><div class="answer"><p>As mentioned before, JavaScript’s creator, Brendan Eich, based JavaScript on Scheme, which is a dynamically typed language.</p><p>JavaScript was intended to be a quick and easy scripting language. Advocates of dynamic typing suggest that programmer productivity is increased, at least for small to medium size programs, when the programmer doesn’t have to figure out the types when writing the program.</p><p>Even though static typing has many advantages, like better documentation, the elimination of type errors at run-time,<span class="footnote">Most (static) type systems are actually unsound and cannot guarantee a program is well-typed in all of the cases. For instance <em>casting</em> in Java and C is a totally unsafe operation. Even Haskell, a language with an advanced type system, has an unsafe function that bypasses the type system: <code>unsafePerformIO</code>.</span> correct auto completion during development, … it would be very hard to make JavaScript statically typed.</p><p>The ability to extend (prototypes of) objects with new properties at run-time, the ability to change the prototype of an object at run-time, the way the <code>arguments</code>-object works, or even the <code>eval</code> function (see the next paragraph) will make a static type system for JavaScript very complicated, or in the case of <code>eval</code>, impossible.</p><p>There is one built-in function present in JavaScript that is impossible to annotate with a useful type signature, <code>eval</code>, which originates from Lisp. This function takes a string and evaluates it, effectively parsing and interpreting it.<span class="footnote">If someone wanted to statically compile JavaScript <strong>and</strong> include <code>eval</code>, a JavaScript interpreter would have to be included in the executable.</span> The <code>eval</code> function is also a security risk and should not be called with input from third parties. Using <code>eval</code> in a program is often frowned upon.<span class="footnote">A plausible use of <code>eval</code> is to build a REPL (Read-Eval-Print-Loop).</span></p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="weak-typing">IV.1. Weak typing</h4><p>JavaScript’s type system is also <em>weakly</em> typed. The opposite of weak typing is <em>strong</em> typing. In weakly typed programs, types can be implicitly converted to other types, whereas these conversion have to be done explicitly in a strongly typed language.</p><p>An example will make it much clearer:</p><pre>"12" * 3; // 36</pre><pre class="Java">"12" * 3; // Type Error
Integer.parseInt("12") * 3; // 36</pre><p>In the JavaScript example, <code>12</code>, a string, is implicitly converted to a number to be able to multiply it with <code>3</code>. In strongly typed languages, such as Java, the conversion of string to number has to be done explicitly.</p><div class="question">This looks like a useful feature to me, why aren’t most languages weakly typed?</div><div class="answer"><p>In the example above, it indeed seems useful. This is not always the case. It’s not always obvious <em>when</em> a conversion and <em>which</em> conversion will occur. Take the following example:</p><pre>('10' - 1) * 2; // 18 = 9 * 2
('10' + 1) * 2; // 202 = 101 * 2</pre><p><code>Object</code>s and <code>Array</code>s can also cause some odd interactions:<span class="footnote">It’s possible that the results after pressing ‘Evaluate’ don’t match the expected outcome, this is due to differences in parsing and code printing.</span></p><pre>[] + 1; // "1"
{} + 1; // 1
[] + []; // ""
[] + {}; // "[object Object]"
{} + []; // 0
{} + {}; // NaN</pre><p>Source: <a href="https://www.destroyallsoftware.com/talks/wat" target="_blank">Gary Bernhardt’s talk, “WAT”</a></p><p>This is the downside of these conversions, you have to know when they will occur and which conversion will occur for which types. Looking at the examples, you will probably agree that these rules aren’t really intuitive.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="equality">IV.2. Equality</h4><p>Like most programming languages, JavaScript has a <code>==</code> operator to check whether two values are equal, its inverse, <code>!=</code> is also present. JavaScript also has another operator that checks whether two values are equal, <code>===</code>, and of course, its inverse, <code>!==</code>. The latter operator, <code>===</code>, is also called the <em>strict</em> equality or <em>identity</em> operator. The two operators define <em>equality</em> in a different manner.</p><p>The strict equality operator, <code>===</code>, compares two values as follows:</p><ul><li>If the two values have different types, they are not equal.</li><li>If both values are <code>null</code> or both values are <code>undefined</code>, they are equal.</li><li>If both values are the boolean value <code>true</code> or both are the boolean value <code>false</code>, they are equal.</li><li>If one or both values is <code>NaN</code>, they are not equal. The <code>NaN</code> value is never equal to any other value, including itself! To check whether a value <code>x</code> is <code>NaN</code>, use <code>x !== x</code>. <code>NaN</code> is the only value of <code>x</code> for which this expression will be true.</li><li>If both values are numbers and have the same value, they are equal. If one value is <code>0</code> and the other is <code>-0</code>, they are also equal.</li><li>If both values are strings and contain exactly the same 16-bit values in the same positions, they are equal. If the strings differ in length or content, they are not equal.</li><li>If both values refer to the same object, array, or function, they are equal. If they refer to different objects they are not equal, even if both objects have identical properties.</li></ul><p>The (non-strict) equality operator, <code>==</code>, compares two values as follows:</p><ul><li>If the two values have the same type, test them for strict equality as described above. If they are strictly equal, they are equal. If they are not strictly equal, they are not equal.</li><li>If the two values do not have the same type, the <code>==</code> operator may still consider them equal. Use the following rules and type conversions to check for equality:</li><ul><li>If one value is <code>null</code> and the other is <code>undefined</code>, they are equal.</li><li>If one value is a number and the other is a string, convert the string to a number and try the comparison again, using the converted value.</li><li>If either value is <code>true</code>, convert it to <code>1</code> and try the comparison again. If either value is <code>false</code>, convert it to <code>0</code> and try the comparison again.</li><li>If one value is an object and the other is a number or string, convert the object to a primitive. An object is converted to a primitive value by either its <code>toString()</code> method or its <code>valueOf()</code> method. The built-in classes of core JavaScript attempt <code>valueOf()</code> conversion before <code>toString()</code> conversion, except for the <code>Date</code> class, which performs <code>toString()</code> conversion.</li><li>Any other combinations of values are not equal.</li></ul></ul><p>Source: <a href="#bib-14" class="ref"><span class="bib">14</span> JavaScript: The Definitive Guide</a></p><p>The following table illustrates the rules of the strict equality operator, <code>===</code>.</p><table class="comparisons" id="strict-equality-table"></table><p>And the following table illustrates the rules of the non-strict equality operator, <code>==</code>.</p><table class="comparisons" id="equality-table"></table><p>Tables adapted from <a href="https://github.com/dorey/JavaScript-Equality-Table" target="_blank">dorey’s JavaScript-Equality-Table</a>.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="-undefined-null-">IV.3. <code>undefined</code> & <code>null</code></h4><p>Most (object-oriented) languages have a special value, <code>null</code>, a.k.a. the <em>null pointer</em>, which is used to indicate the absence of a value. Whenever a variable is expected to be a pointer or an object, i.e. a reference type, it can contain the <code>null</code> value, meaning that the variable has no value. This null pointer is the cause of many errors, as the programmer should verify whether a reference isn’t a null pointer before using it.<span class="footnote">C.A.R. Hoare, the inventor of the null reference, calls it his “billion-dollar mistake”.</span><span class="footnote">A safer alternative is a nullable type, like Haskell’s <code>Maybe</code> type or Scala’s <code>Option</code> type.</span></p><p>Allowing null pointers in a language is commonly regarded as a source of problems. Of course, JavaScript can do better than this, it has two different special values that are essentially null pointers! The first one is <code>null</code>, the regular null pointer, which indicates the absence of a value. <code>null</code> is a special keyword in JavaScript. The second one is <code>undefined</code> and indicates that a value is not initialised, e.g. the value of missing parameters, undefined methods, missing properties of an <code>Object</code>, missing elements of an <code>Array</code>. In older versions of JavaScript <code>undefined</code> was a global value, which could even be changed! Changing the value of the global <code>undefined</code> value could break whole programs. Luckily, this mistake was corrected in later versions. The type of <code>null</code> is <code>object</code>, in a way, this makes sense, because <code>null</code> takes the place of an absent <code>object</code>. The type of <code>undefined</code> is <code>undefined</code>.</p><div class="question">Why make a difference between these two? When a property is <code>undefined</code>, isn’t it the same as the absence of the value of this property?</div><div class="answer"><p>It’s hard to conceive of a convincing argument for a separation between the two. Here’s the one Douglas Crockford makes in <a href="#bib-7" class="ref"><span class="bib">7</span> JavaScript: The Good Parts</a>:</p><blockquote>You might consider <code>undefined</code> to represent a system-level, unexpected, or error-like absence of value and <code>null</code> to represent program-level, normal, or expected absence of value. If you need to assign one of these values to a variable or property or pass one of these values to a function, <code>null</code> is almost always the right choice.<br><span class="cite">—<a href="#bib-7">Douglas Crockford</a></span></blockquote></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="truthiness-and-falsiness">IV.4. Truthiness and falsiness</h4><p>JavaScript has a <code>boolean</code> type of which there exist two values, <code>true</code> and <code>false</code>. These two values, or expressions that evaluate to one of them can be used as conditions of an if-statement, or any other <em>boolean context</em>.<span class="footnote">Expressions used as operands of a boolean operator are also in a boolean context, e.g. <code>1 && true == true</code>.</span> In JavaScript, values of all types, not just booleans, can be used in a boolean context. All values can be converted to a boolean, depending on the <em>truthiness</em> or <em>falsiness</em> of the value. All values are considered to be <em>truthy</em>, including <code>Object</code>s, <code>Array</code>s, <code>Number</code>s, except for the following list of values which are <em>falsy</em>:</p><ul><li><code>undefined</code></li><li><code>null</code></li><li><code>0</code></li><li><code>-0</code><span class="footnote"><code>0</code> is equal to <code>-0</code>! To distinguish between these two values, you can use the following tests: <code>1 / 0 == Infinity</code>, <code>1 / -0 == -Infinity</code>. Also see <a href="#numbers" class="ref">Numbers</a>.</span></li><li><code>NaN</code></li><li><code>""</code></li></ul><p>The concept of truthiness and falsiness comes from Lisp.</p><div class="question">Is this something one shouldn’t rely on, such as these type conversions?</div><div class="answer"><p>This actually proves to be useful in most cases. With one check, you can quickly cover the most common edge cases. If you’re working with strings or numbers, you still have to pay attention to <code>0</code> and <code>""</code>, see the following example:</p><pre>function g(x, y) {
if (x && y)
return x + y;
else
return -1;
}
g(4, 5); // 9
g(4, 0); // -1</pre><p>The programmer could have had the following intention when writing the function <code>g</code> in the example above: “when both arguments are non-<code>null</code> and also not <code>undefined</code>, return the sum of them.” This, of course, will not function correctly as <code>0</code>, a falsy number, will fail the check. You can see that it’s easy to overlook this subtlety.</p></div></div></div>
<div class="chapter" id="chapter-5"><h3 id="functional-programming">V. Functional programming</h3><div class="question">You mentioned that JavaScript has first-class functions, does this mean that JavaScript is a functional language?</div><div class="answer"><p>It’s true that all functional languages support first-class functions, but this alone doesn’t make a language functional. Functional programming consists of more than just first-class functions, sometimes it’s more about what you <em>can’t</em> do<span class="footnote">In Haskell, for example, you can’t just change the value of a variable.</span>, or in some cases, what the default is.<span class="footnote">Immutable data structures are the default in Scala, but mutable ones are also available.</span></p><p>An important tenet of functional programming is the avoidance or isolation of side-effects. All forms of state are side-effects. In JavaScript, pretty much every accessible variable can be modified, effectively making the whole environment <em>stateful</em>. It’s very common to define and change global variables, even by <a href="#variables-and-functions">accident</a>. The properties of objects are mutable by default, including the methods and the prototype. Just like Ruby, JavaScript is a very dynamic language, offering the programmer nearly maximum flexibility, at the cost of the omnipresent fragility of state.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="immutability">V.1. Immutability</h4><p>An important tool to minimise the presence of state in a program is the use of immutable data structures, instead of mutable ones, which are inherently stateful. Rather than modifying the data structure in-place, a new copy of the data structure is made with the desired modifications.<span class="footnote">Copying the whole data structure for every change is of course costly. Luckily, efficient immutable data structures exist, for example the <em>hash array mapped trie</em>, invented by the late Phill Bagwell. See <a href="#bib-17" class="ref"><span class="bib">17</span> Purely Functional Data Structures</a>, for more such data structures.</span></p><p>It might come as a surprise, but in JavaScript, properties can be made immutable. As you will see, this requires a lot more effort. This clearly indicates the language designer’s intention, to discourage users from using the feature.</p><div class="question">How do you mean, “This clearly indicates the language designer’s intention, to discourage users from using the feature”?</div><div class="answer"><p>When doing something in a particular way requires more code than in the default way, and thus more effort, programmers will not be inclined to make the extra effort, and will quickly fall back to the default way.</p></div><p>Here’s how to make a property immutable:</p><pre> var obj = {x: 1};
// Make obj's x property immutable
Object.defineProperty(obj, 'x', {
writable: false
});
obj.x = 3;
obj.x; // 1</pre><p>You can still assign a new value to the property, it just won’t have any effect. Of course, this in no way comes close to Haskell’s, Scala’s or Clojure’s immutable data structures.</p><p>In JavaScript 1.8.5, there is a new method available for <code>Object</code>s, called <code>freeze</code>, which effectively makes an object immutable.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="higher-order-functions-recursion-lists">V.2. Higher-order functions, recursion & lists</h4><p>If there even was an accepted definition of functional programming, JavaScript probably wouldn’t satisfy the requirements, but this won’t prevent programmers from writing JavaScript programs in a functional style. JavaScript is in fact a multi-paradigm language, that supports object-oriented, functional, and imperative styles. Thanks to Scheme’s influence, JavaScript is equipped with first-class functions, which allow the programmer to write some of the typical higher-order functions that are almost invariably present in a functional language.</p><p>Disclaimer: the following functions are in no way optimised or robust enough for general use, they just serve to illustrate programming in a functional style.</p><p>Let’s start off with some primitives, they should be familiar to programmers that have dabbled in Lisp or Haskell.</p><pre data-name="func-primitives">// Make a list with x as head and xs as tail
var cons = function(x, xs) {
// Make a copy of xs
var xs2 = xs.slice(0);
xs2.unshift(x);
return xs2;
};
// Return the first element of xs
var head = function(xs) {
return xs[0];
};
// Return all but the first element of xs
var tail = function(xs) {
return xs.slice(1);
};
// Return true when xs is an empty list
var isEmpty = function(xs) {
return xs.length == 0;
};</pre><p>Using these primitives, we can easily define our first <em>higher-order function</em>. A higher-order function is a function that takes a function as an argument, or returns a function. The function defined below, <code>map</code> takes two arguments: a function <code>f</code> and an array <code>xs</code>. <code>map</code> will apply <code>f</code> to every element in <code>xs</code> and return a new array containing the return values of these applications.</p><pre data-name="map" data-depends="func-primitives">var map = function(f, xs) {
if (isEmpty(xs))
return [];
else
return cons(f(head(xs)), map(f, tail(xs)));
};
map(function(x) { return x + 1; }, [1, 2, 3]); // [2, 3, 4]</pre><p>The <code>map</code> function is defined recursively. Functional programmers prefer recursion to iteration, mostly because iteration involves loop indexes, or some other form of state, but elegance also plays a role.</p><blockquote>To iterate is human, to recurse divine.<br><span class="cite">—L. Peter Deutsch</span></blockquote><div class="question">Doesn’t recursion lead to stack overflow errors when it goes on for too long?</div><div class="answer"><p>That’s true, recursion comes at a cost, namely the stack space that is consumed by the recursive function calls. When passed a very large list, the <code>map</code> function will exhaust the stack and cause a stack overflow error. The solution for this problem is <em>tail call optimisation</em>. When a language, or rather a language implementation, supports tail call optimisation, function calls in tail position<span class="footnote">A statement or expression is in tail position when it’s the last thing to be executed or evaluated before the function returns.</span> are eliminated and replaced by jumps to the function, effectively transforming tail recursive programs<span class="footnote">The example above is actually not <em>tail</em> recursive, but could be made tail recursive, e.g. by the use of an accumulator.</span> into equivalent programs that use loops. Although the Scheme<span class="footnote">Remember that Scheme was one of the main influences on JavaScript.</span> standards require implementations to support tail call optimization, JavaScript standards don’t require it.</p><p>Because of this lack of tail call optimisation, it’s recommended to write programs using loops instead of recursion in JavaScript.</p></div><p>On the last line of the example above, you can see the <code>map</code> function in use: we increment each element of an array with one. You will probably have noticed that declaring the anonymous function that adds <code>1</code> to a value takes lots of space. Declaring the simplest anonymous function, e.g. the identity function, takes at least 21 characters in JavaScript: <code>function(x){return x}</code>, compare this with, for example, Haskell: <code>\x->x</code>, only 5 characters! The unwieldiness of the <code>function</code> keyword is one of JavaScript’s warts when it comes to writing programs using higher-order functions.</p><p>Version 1.6 of JavaScript provides a built-in <code>map</code> function declared on the prototype of <code>Array</code>:</p><pre>[1, 2, 3].map(function(x) { return x + 1; }); // [2, 3, 4]</pre><p>In addition to <code>map</code>, <code>forEach</code>, <code>every</code>, <code>some</code>, and <code>filter</code> are also available. In even more recent versions of JavaScript, <code>reduce</code> and <code>reduceRight</code> are available. These will ring a bell with programmers with Haskell or Clojure experience. This demonstrates that functional programming, albeit in limited form, is slowly creeping into mainstream languages.</p><p>Let’s look at another example, the <code>partial</code> function. Invoking <code>partial</code> on a function <code>f</code> with a number of arguments will return a new function, let’s call this function <code>g</code>. When <code>g</code> is invoked, the following things will happen: the original arguments are concatenated with the new arguments, and <code>f</code> is invoked with the concatenated arguments. Three elements come together in this example: prototypes, the <code>arguments</code> object and higher-order functions.</p><pre>Function.prototype.partial = function() {
var args = Array.prototype.slice.call(arguments);
// Capture this into f, so we can refer to it in the nested function
// definition, wherein this refers to the defined function.
var f = this;
return function () {
var innerArgs = Array.prototype.slice.call(arguments);
return f.apply(this, args.concat(innerArgs));
};
};
function add(x, y) { return x + y; };
var inc = add.partial(1);
inc(2); // 3</pre><p>The example was taken from <a href="#bib-24" class="ref"><span class="bib">24</span> Functional Programming in JavaScript</a>.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="libraries">V.3. Libraries</h4><p>As demonstrated in the previous section, programming in a functional style is certainly possible in JavaScript. Numerous programmers have discovered this and have even made libraries providing functions that promote programming in a functional style. Here are some interesting ones:</p><ul><li><a href="http://underscorejs.org" target="_blank">Underscore.js</a></li><li><a href="http://osteele.com/sources/javascript/functional/" target="_blank">Functional JavaScript</a></li><li><a href="http://gkz.github.com/prelude-ls/" target="_blank">prelude.ls</a><span class="footnote">This library is actually written in LiveScript, a functional language that compiles to JavaScript, more about such languages in <a href="#compiling-to-javascript" class="ref">Compiling to JavaScript</a></span></li></ul></div></div>
<div class="chapter" id="chapter-6"><h3 id="monkey-patching">VI. Monkey-patching</h3><div class="question">When talking about JavaScript’s dynamic nature, you said JavaScript was comparable to Ruby in this aspect. Does JavaScript also support monkey patching?</div><div class="answer"><p>Yes, it’s also possible to do monkey patching in JavaScript. In Ruby, classes can be modified at run-time. As seen in <a href="#prototype-based-programming" class="ref">Prototype-based programming</a>, JavaScript allows objects, and by consequence classes too,<span class="footnote">Remember that classes in JavaScript are emulated/implemented using objects.</span> to be modified at run-time. This is just the way JavaScript works. As JavaScript is executed line by line, objects are also created line by line, property after property, constantly modifying the object.</p><p>Monkey patching is often used to modify the behaviour of third-party or even standard libraries without requiring access to their source. Fixing bugs in libraries, mocking test objects, changing the behaviour of a function to suit your program, extending objects with useful methods, … are all reasons to monkey patch.</p><p>In JavaScript, you can simply modify properties of objects. A more effective and also more radical approach is to modify the prototypes of objects.</p><p>Let’s extend JavaScript’s built-in object with some methods:</p><pre>// Return the last element
Array.prototype.last = function() {
return this[this.length - 1];
};
[1, 2, 3].last(); // 3
// Capitalise the string
String.prototype.capitalise = function() {
var newStr = '';
if (this.length == 0)
return newStr;
newStr += this[0].toUpperCase() + this.substring(1).toLowerCase();
return newStr;
};
'brendan'.capitalise(); // 'Brendan'
// Merge two hash maps together in a new one
Object.prototype.merge = function(obj) {
var newObj = {};
for (var k in this) {
newObj[k] = this[k];
}
for (var k in obj) {
newObj[k] = obj[k];
}
return newObj;
};
({a: 1}).merge({b: 2}); // { a: 1, b: 2, merge: [Function] }</pre><p>All the methods that we added with monkey patches are quite useful. They seem to work correctly except for the last one: the <code>merge</code> function appears to have sneaked in the hash map we got back after merging the two hash maps. How did this happen? By adding the <code>merge</code> method to the prototype of <code>Object</code>, the top of the inheritance hierarchy, <em>every</em> object will inherit this property and thus have a <code>merge</code> property with as value the newly defined function. This is obviously an unintended side-effect.</p><p>It turns out that we can actually hide this <code>merge</code> property, by making it <em>un</em>enumerable.</p><pre>Object.defineProperty(Object.prototype, 'merge', {
enumerable: false
});
({a: 1}).merge({b: 2}); // { a: 1, b: 2 }</pre><div class="question">The apparent problem seems to be solved by hiding the properties that were added as monkey patches. Are there any other drawbacks to monkey patching?</div><div class="answer"><p>The common pitfalls of monkey patching still apply:</p><ul><li>Patching a method in a single place will affect the whole program, which can cause some unintended behaviour. However, it is possible to revert or remove the monkey patched methods after using them.<span class="footnote">Users familiar with Lisp macros will see in the example below a perfect opportunity for a <code>with-patches</code> macro. The application and removal and the patches should be put in a try- and a finally-clause respectively.</span></li></ul><pre>Array.prototype.last = function() {
return this[this.length - 1];
};
[1, 2, 3].last(); // 3
delete Array.prototype.last; // the delete operator deletes a property
[1, 2, 3].last(); // last is not a function</pre><ul><li>When a single method is monkey patched in two different places in your program, it’s not always clear which monkey patch <em>wins</em>.</li></ul><ul><li>Monkey patching third-party libraries or the built-in objects, will inevitably create discrepancies between the documented and the actual behaviour.</li></ul><p>Source: <a href="#bib-41" class="ref"><span class="bib">41</span> Monkey patch</a></p><p>The example with the <code>merge</code> monkey patch is actually still not correct, consider the following case:</p><pre>({a: 1, merge: 3}).merge({b: 2});
// TypeError: Property 'merge' of object #<Object> is not a function</pre><p>Objects are the easiest way to emulate hash maps in JavaScript, but as soon as the prototype of <code>Object</code> is monkey patched, objects can no longer be used safely as hash maps.<span class="footnote">Actually, even without monkey patching objects can’t be used safely as hash maps, having a key called <code>toString</code> will also cause problems.</span> As you saw in the example above, keys with the same name as a monkey patched method will break the behaviour of the hash map and the monkey patched method.</p></div><div class="question">Given the pitfalls just listed, is monkey patching still encouraged in JavaScript or rather frowned upon?</div><div class="answer"><p>If done with care and for the right reasons, monkey patching is a defensible solution. Fixing a bug in a third-party library could be a valid reason, provided that the monkey patch will only be applied to faulty versions of the library.</p></div></div></div>
<div class="chapter" id="chapter-7"><h3 id="implementation">VII. Implementation</h3><div class="question">How is JavaScript implemented?</div><div class="answer"><p>JavaScript has many different implementations. Just looking at the browsers, each one has its own implementation of JavaScript. Chrome uses the V8 JavaScript engine<span class="footnote">V8 is also used by <a href="#node-js">Node.js</a>.</span>, the latest version of Firefox uses IonMonkey,<span class="footnote">It’s hard to keep track of the current JavaScript engine of Firefox, they seem to change every couple of releases. Previous engines or parts of the engine include SpiderMonkey, TraceMonkey, and JägerMonkey.</span> Safari uses Nitro,<span class="footnote">Nitro was previously called SquirrelFish, which is another name for JavaScriptCore, the WebKit JavaScript engine.</span> Opera uses Carakan (formerly Futhark), and lastly, Internet Explorer uses an engine called Chakra (versions prior to IE9 used an engine called JScript). These are just the JavaScript engines present in web browsers. Besides the web browser engines, there are also a few other engines in use such as Rhino,<span class="footnote">Rhino is written in Java and comes standard with the Java Development Kit.</span> Nashorn,<span class="footnote">Nashorn (“nose horn”, the German translation of rhinoceros) is the successor of Rhino. Nashorn is written in Java and takes advantage of the <code>invokedynamic</code> instruction that was added to version 7 of the JVM, which greatly improves the performance of dynamic function invocation. Function invocation in JavaScript is highly dynamic, as methods can be added and redefined at run-time.</span> and Narcissus.<span class="footnote">Narcissus is a JavaScript engine written by Brendan Eich, the original creator of JavaScript. Narcissus is written in JavaScript for quick prototyping of new JavaScript features.</span></p></div><div class="question">That’s a lot of engines. What do they have in common?</div><div class="answer"><p>This plethora of implementations makes it hard to discuss <em>the</em> implementation of JavaScript. Most engines do have quite a few components in common. Most (if not all) of them execute JavaScript code using JIT (Just-In-Time) compilation. Let’s delve a bit into the concept of JIT compilation before continuing the discussion on the most common parts of a JavaScript engine.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="just-in-time-compilation">VII.1. Just-in-time compilation</h4><div class="question">Ok, what exactly is JIT compilation?</div><div class="answer"><p>JIT compilation means that the compiler is run <em>after</em> the program has started and that program code is compiled (converted to machine code) <em>on the fly</em> (at run-time, dynamically).</p><p>This is in contrast to static compilation, in which source code is translated into machine code once (at compile time). Static compilers have the advantage that the whole of the program can be analysed and optimised. One of the downsides to this approach is that machine code is not portable from machine to machine, it has to be recompiled for every architecture.</p><p>On the other end of the ‘compilation spectrum’ is <em>interpretation</em>. Code is never compiled and is interpreted as-is at run-time. This means the code remains portable across platforms. However, this has the disadvantage that performance is much worse, because every instruction is interpreted separately and no optimisations can be performed.</p><p>At first, a JIT-compiler will just interpret or quickly compile without spending any time on optimising. At the same time, the JIT-compiler profiles the running code to identify ‘hot’ code. Whenever a function or a trace<span class="footnote">A trace is an execution path throughout a program that can span multiple function calls, but will only cover certain branches.</span> is executed often enough, i.e. it is ‘hot’, e.g. a for-loop with many iterations, it will be compiled with another, more advanced compiler which also tries to optimise the code. The code is compiled <em>just in time</em> before execution. Because the resulting code is known to be executed many times, the extra time spent compiling and optimising the code will pay off.</p><p>JIT compilers often try to infer the types of variables to eliminate the type checks. Although the type of variables can change dynamically, it only happens very rarely in practice. For example, the compiler might figure out in advance that <code>a = b + c;</code> is either a string concatenation, or an integer addition. Even if the type would eventually change, the JIT compiler will provide an escape hatch that calls in to the interpreter, which is able to handle all cases.</p><p>Another very common optimisation is function inlining. This means that function calls are replaced by their body with the arguments filled in. This way the overhead of calling the function is eliminated. A similar optimisation named <em>loop unrolling</em> can also be applied. Loops with known bounds can be unrolled (exactly as functions can be inlined). This way, the overhead of checking the loop conditions is removed.</p><p>By using JIT compilation, a midway between interpreted code and compiled code is found. Code remains portable while it is still possible to perform (machine-specific) optimisations and thus not sacrifice performance.</p></div><div class="question">What are the main advantages of JIT compilation?</div><div class="answer"><p>A common goal of all JIT techniques is to reach or surpass the performance of static compilation while maintaining the advantages of interpretation. JIT compilation generally outperforms code interpretation by far (because of compiler-level optimisations). However, it may not be immediately clear how JIT compilation can be faster than static compilation. After all, a static compiler can analyse the entire program, compile and optimise it in its entirety (and has all the time to do so!). However, here are some advantages a JIT compiler has over a static compiler:</p><ul><li>The JIT compiler can optimise for the targeted processor architecture and operating system. For example, SSE2 or another more advanced instruction set can be used when available. To obtain this effect with a static compiler, one must either compile multiple versions (one with, one without SSE2) of the same program, or include multiple versions of the same code in the compiled program (<code>if SSE2 … else …</code>).</li><li>The system can collect information about how the program is currently running in the environment, and optimise code accordingly. For example, when a particular piece of code is <em>very hot</em>, the JIT compiler can perform extra optimisations on just this piece of code, whereas a static compiler must choose between performing these optimisations on the whole program, or not at all. Performing these optimisations on the whole program is often very time-consuming.</li><li>Improvements in compiler technology affect existing programs. A better C compiler will not improve performance of C programs that have already been deployed. However, when a better JavaScript compiler is released, it will improve the performance of existing programs.</li></ul></div></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="components-of-a-javascript-engine">VII.2. Components of a JavaScript engine</h4><div class="question">Why the term ‘engine’, why not just ‘runtime’ or ‘interpreter’?</div><div class="answer"><p>A JavaScript engine comprises multiple parts, not just a ‘runtime’ or ‘interpreter’. It usually consists of the following parts:</p><ul><li>A base compiler or interpreter: parses the JavaScript<span class="footnote">Parsing is also often done as late as possible, i.e. just in time, to keep the initial start-up time low. Web sites heavy on JavaScript often include many libraries, of which not every single function or line of code will be executed. Parsing all the code upfront would be costly and unnecessary.</span> and either generates (not highly optimised) native code or interprets the code.</li><li>An object model: in JavaScript, objects are represented as associative arrays/dicts. However, some engines choose to implement this differently behind the scenes. For example, V8 employs an internal type system using <em>hidden classes</em>, see <a href="#bib-45" class="ref"><span class="bib">45</span> V8 Design Elements</a>.</li><li>A run-time profiler: monitors the system being run and identifies ‘hot’ code. This is code that can/should be optimised.</li><li>An optimising compiler: (re)compiles and optimises the ‘hot’ code.</li><li>Some engines support <em>deoptimization</em>: if the assumptions made about optimised code prove to be too optimistic, the optimised code can be <em>degenerated</em>. This is referred to as a <em>bail-out</em>.</li><li>A garbage collector: manages memory allocation, reclaims memory that is no longer being used. Ideally, the programmer should not need to worry about memory management. However, to write performant and clean programs, it is important to understand how the garbage collector works (the same is true for the other components).</li></ul><p>Source: <a href="#bib-18" class="ref"><span class="bib">18</span> Writing Fast, Memory-Efficient JavaScript</a></p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="garbage-collection">VII.3. Garbage collection</h4><div class="question">How is garbage collection performed in JavaScript?</div><div class="answer"><p>Garbage collection is performed on objects that are no longer referenced. The specific way garbage collection is performed, depends on the engine. As an example, we’ll look at the V8 engine. V8 uses a stop-the-world, generational, accurate, garbage collector. This means that V8:</p><ul><li>Stops program execution when performing a garbage collection cycle.</li><li>Processes only part of the object heap in most garbage collection cycles. This minimises the impact of stopping the application.</li><li>Always knows exactly where all objects and pointers are in memory. This avoids falsely identifying objects as pointers which can result in memory leaks.</li></ul><p>In V8, the object heap is segmented into two parts: new space where objects are created, and old space to which objects surviving a garbage collection cycle are promoted. If an object is moved in a garbage collection cycle, V8 updates all pointers to the object.</p><p>Other engines might use different strategies for garbage collection. For example: JScript, Microsoft’s JavaScript engine, uses a <em>nongenerational mark-and-sweep garbage collector</em>. You can check the sources for more implementation details, but because of the plethora of different engines, we won’t go too far into the details.</p><p>Sources: <a href="#bib-45" class="ref"><span class="bib">45</span> V8 Design Elements</a>, <a href="#bib-15" class="ref"><span class="bib">15</span> How Do The Script Garbage Collectors Work?</a></p></div><div class="question">Can garbage collection be forced?</div><div class="answer"><p>It’s not possible to explicitly force garbage collection in JavaScript. Some programmers try to force this anyway by the use of the <code>delete</code> operator. <code>delete</code> was originally intended to remove values from a hash map, i.e. an object. One should avoid using <code>delete</code> to try and force memory deallocation. JavaScript engines tend to optimise objects behind the scenes and changing the structure of an object manually can force deoptimisation of an object. Another misconception among programmers is that setting an object reference to <code>null</code> implies that the object is deleted from memory, <em>nulled out</em>). This is not true. Only the reference is set to <code>null</code>, the object still lives in memory until it is garbage collected. If the reference you set to <code>null</code> was the last reference, the object will be garbage collected, otherwise it will remain in memory. The only way to manage memory efficiently in JavaScript is to scope your variables properly. Once variables fall out of scope, they will be garbage collected. So it is key to scope your variables as locally as possible. Also, try to avoid global variables. They are <strong>never</strong> garbage collected and will exist for the entire lifetime of your application, or, in case of web browsers, as long as the page is open.</p><p>Source: <a href="#bib-18" class="ref"><span class="bib">18</span> Writing Fast, Memory-Efficient JavaScript</a></p></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="representations">VII.4. Representations</h4><div class="question">Can you tell me some other interesting things about JavaScript engines?</div><div class="answer"><p>Actually, in JavaScript <code>Object</code>s, <code>Array</code>s and <code>Number</code>s are all represented in a peculiar and sometimes rather inefficient fashion.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="numbers">VII.4.1. Numbers</h5><p>For example, the JavaScript standard declares that a JavaScript <code>Number</code> is actually a 64-bit floating point value, following the IEEE 754 standard. As <code>Number</code> is the only numeric type of JavaScript, this means that JavaScript doesn’t support numbers represented by integers.</p><div class="question">Why only one type of numbers and why floating point numbers?</div><div class="answer"><p>Having only one type of number, instead of a whole host of numbers of different size like in C, simplifies things a bit for programmers (and implementers). It’s also obvious to pick floating point numbers instead of integers as <em>the</em> type, as floating point numbers are a superset of integral numbers.</p><p>A possible explanation for this choice is that Brendan Eich, the creator of JavaScript, as he had only limited time to define and implement JavaScript, opted for just one kind of numbers because he was short on time. However, as of yet, integers still haven’t been added in a later JavaScript standard.</p></div><p>Luckily, the standard prescribes that positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the <code>Number</code> type.</p><div class="question">Why is that important?</div><div class="answer"><p>The most common number sizes in programming languages, often called <em>integer</em> and <em>long</em>, are commonly 4 bytes and 8 bytes in size. Integers and longs can hold every integral number that fits in their range. In the case of floating point numbers, this isn’t true, not every single number in the range of a floating point number can be correctly represent by a 4 or 8 byte floating point number. As a matter of fact, it’s impossible, as there are already infinitely many numbers between every two integral numbers. This is a limitation for all programming languages.<span class="footnote">Some programming language provide a data type that allows arbitrary precision, like Java’s <code>BigDecimal</code>.</span></p><p>What would be rather problematic is that some of the numbers that aren’t representable could be integral numbers. Adding, using floating point arithmetic, two integral numbers that sum to a number that is not exactly representable as a floating point number, would result in an incorrect result. Because the standard requires integral number whose magnitude is no greater than 2<sup>53</sup> to be representable, programmers can do calculations with a safe heart, as long as they stay within these bounds. As integers and longs have often respectively 2<sup>31</sup> - 1 and 2<sup>63</sup> - 1 as maximum magnitudes, JavaScript has integral numbers allowing correct calculations up to a magnitude that lies between the common long’s and integer’s magnitude.</p></div><p>It seems rather wasteful to reserve 64 bits for all numbers, however small they might turn out to be, like the majority of loop indexes. Some operations might also prove to be faster on integers than on floating point numbers.</p><p>Many JavaScript engines try to figure out whether a numeric value will remain integral or become a floating point number at some point. When the engine has concluded that a number will remain integral for its lifetime, it will be represented by an integer. Or, V8 might try to represent the number as an integer for as long as it can, eventually converting it to a floating point number. V8 will for example represent most loop indices by integers.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="objects">VII.4.2. Objects</h5><p>As we already mentioned a couple of times, objects in JavaScript are equivalent to hash maps with strings as keys. Performing a lookup in a hash map is, of course, much slower than directly accessing a field of a struct or an object, whose fields or instance variables are located at fixed offsets.</p><p>The V8 engine optimises property lookup in the following way: instead of representing the object as a hash map, it represents it as a <em>hidden class</em> with the properties as fields, offering fast lookup times. When a property is added at a later stage, another hidden class is created which will contain the new property, the original class will be updated to refer to the new class whenever the newly added property is accessed. See <a href="#bib-45" class="ref"><span class="bib">45</span> V8 Design Elements</a> for more details.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="arrays">VII.4.3. Arrays</h5><p>Another peculiarity of JavaScript is the way <code>Array</code>s are implemented. As an <code>Array</code> is an object, properties can be added and removed. Have a look at the following interactions with an array:</p><pre>var a = [1, 2, 3];
// We can add properties
a.foo = 3;
a.foo; // 3
a['foo']; // 3
// Without apparent effects on the contents of the array
a; // [1, 2, 3]
a.length; // 3
a[0]; // 1
// The indexes are in fact converted to strings
a['0']; // 1
// By deleting an element in the middle of the array, we make it a
// sparse array.
delete a[1];
a; // [1, , 3]
a.length; // 3
a[1]; // undefined</pre><p>An <code>Array</code> is in fact implemented as an <code>Object</code>, the indices are just the keys. And because the keys of an object must be strings, they are first converted to a string.</p><p>In most languages array accesses can be performed in constant time. Let’s compare an array lookup in JavaScript with an array lookup in the C programming language. Array accesses in other languages are often implemented similarly to the way they are implemented in C. In C, accessing an element <code>x</code> in array <code>a</code> at index <code>i</code> is equivalent to accessing a memory location of which the address is determined by adding <code>i</code> to <code>a</code>, which is actually a pointer. On most computer architectures, this can be achieved with one instruction.</p><p>In JavaScript we have to convert the index to a string, and then perform a lookup in a hash map. This clearly takes a lot more than one instruction! Fortunately, most JavaScript engines optimise <code>Array</code>s by representing them as arrays like they are used in C. The indexes won’t have to be converted to strings and the lookup can happen almost just as quickly as in C. There is a catch however, as soon as the array is made sparse, i.e. non contiguous, the optimisation has to be undone, because the <code>Array</code> starts to behave as a regular object again.</p><div class="question">It seems like the <code>Object</code>s, <code>Array</code>s, and <code>Number</code>s are all designed without performance in mind. If we combine this with the dynamic nature, JavaScript must be very slow language. Is this the case?</div><div class="answer"><p>The dynamic nature of JavaScript indeed hinders optimisations like inlining. As almost everything can be changed at run-time, including methods and inheritance relations, it is very difficult to optimise JavaScript. But as we mentioned, most JavaScript engines have become very good at optimising JavaScript via the use of JIT compilation. <code>Object</code>s, <code>Array</code>s, and <code>Number</code>s can often be represented by a more optimal format. If the programmer sticks to some guidelines, like keeping <code>Array</code>s contiguous, not adding properties to <code>Object</code>s after creating them, not changing the type of a variable, i.e. limiting the dynamic nature of JavaScript, JavaScript can be efficiently executed.</p><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="benchmarks">VII.5. Benchmarks</h4><p>Let’s have a look at some performance benchmarks. Keep in mind that it’s very difficult to benchmark programming languages. These benchmarks are often unfair as the program used in the benchmark will differ in the degree of optimisation from language to language. Programs written for a benchmark are seldomly written in idiomatic style, and will be optimised much more than real world programs. Benchmarks rarely are an accurate yardstick to measure performance of a programming language for real word programs. But they can give you an idea of the raw speed a programming language can achieve when properly optimised.<span class="footnote">Keep in mind that making a programming language or a program faster is the same as decreasing the number of instructions to be executed to accomplish the same results.</span></p><img src="img/alioth.png" alt="benchmark" title="Benchmark results" width="400" height="300" /><p>The results show that in this benchmark C++ is the fastest language,<span class="footnote">Most programmers expect C to be the fastest, but again, this benchmark is not representative for all programs. It could be caused by the aggressive inlining that is done by C++ compilers.</span> next comes C, then Java, Common Lisp, Haskell, OCaml, <em>JavaScript</em> (using Google’s V8 engine), Smalltalk, PHP, Ruby, Python, and finally Perl. What is remarkable is that except for Common Lisp, JavaScript is the fastest dynamicly typed language. Common Lisp has existed for a much longer time than JavaScript, thus giving more time for compiler writers to optimise. Languages like Ruby, Perl, Python and Smalltalk are all older than JavaScript and have the same dynamic nature, but still prove to be an order of magnitude slower than JavaScript.</p><div class="question">How come JavaScript seems to be much faster than the other dynamic languages?</div><div class="answer"><p>A lot of man-hours have been invested in optimising JavaScript engines, as JavaScript is the lingua franca of the web, and will not be going away any time soon. Every browser contains a JavaScript engine, and one of the ways to lure users over, as the browser market is a competitive one, is to have a faster browser. A performant JavaScript engine is a big part of this. This is actually an example of the free market principles: competition pushes companies, in this case Mozilla, Google, Microsoft, … to improve their product, the browser, in order to win over customers.</p></div></div></div><span class="to-top"><a href="#top">↑ To top</a></span><h4 id="concurrency-parallelism">VII.6. Concurrency & parallelism</h4><div class="question">What kind of concurrency model does JavaScript have?</div><div class="answer"><p>Being intended as a quick and easy scripting language for a web browser, JavaScript didn’t come equipped with support for threads or other concurrency primitives. Each JavaScript program in the web browser is executed by a single thread.</p><p>In web browsers it is very common for a user to interact with a page via events, e.g. clicking on an item or typing some text. These events are handled asynchronously. They are all put together in a single queue and are handled sequentially. A callback can be bound to an event. A callback is a function/closure passed as an argument that will be invoked whenever the associated event is triggered, also see <a href="#callback-hell" class="ref">Callback hell</a>. This is another area where the presence of first-class functions in JavaScript comes in handy.</p><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="node-js">VII.6.1. Node.js</h5><p>This event-driven model actually inspired Ryan Dahl to create Node.js, a server-side version of JavaScript.<span class="footnote">With Node.js you can run JavaScript programs outside the web browser, like regular programs.</span> He combined Google’s V8 JavaScript engine with a self-written C library libuv that implements non-blocking I/O, based on events. Node.js is intended for scalable Internet applications, primarily web servers, which are particularly event-driven.</p><p>The premise of Node.js is that by performing all I/O operations asynchronously and minimising computations, the application will scale. Node.js programs are single-threaded. The program thread will continuously process incoming events that are triggered by completed I/O operations or incoming requests. Because of the minimal amount of computation, these events can be handled very quickly, allowing a larger number of ‘concurrent’ operations, as most time is spent waiting on the I/O anyway.</p><div class="question">Does the event-driven model scale well?</div><div class="answer"><p>The scalability of this model collapses as soon as an event requires a large computation or performs a blocking I/O operation. Another disadvantage of such programs is that they don’t profit from multiple cores or processors. To take advantage of multiple cores, multiple processes running the same program have to be started, which is much less efficient than having multiple threads within one process.<span class="footnote">Python has a similar problem with the GIL, the global interpreter lock.</span></p><p>The event-driven model is still suitable for event-driven programs with non-blocking I/O, such as web servers, the application Node.js was originally intended for.</p></div><span class="to-top"><a href="#top">↑ To top</a></span><h5 id="callback-hell">VII.6.2. Callback hell</h5><p>When doing synchronous I/O, the program can be written in typical imperative style. However, when doing I/O asynchronously, programs can no longer be written as sequences of instructions where each instruction can refer to results of previous instructions. Asynchronous operations are performed in the background while the program continues execution. It’s obvious that the next statement in the program cannot simply use the result of a previously started asynchronous I/O operation, as it is performed in the background. To use such a result, we would have to wait for the asynchronous I/O operation to complete, which essentially makes the program blocking, i.e. synchronous again.</p><p>The solution to this problem is to put the code to be executed after the asynchronous I/O operation completes inside a function, a callback, essentially a <em>continuation</em>. This function will then be executed when the result of the I/O operation is available. Compare the synchronous program below with the asynchronous one.</p><pre class="NodeJS">// Synchronous, blocking program
var x = longSyncComputation();
var y = slowSyncFileRead(x);
var z = largeSyncFileDownload(y);
//...
// Asynchronous, non-blocking program
longAsyncComputation(function(x) {
slowAsyncFileRead(x, function(y) {
largeAsyncFileDownload(function(z) {
//...
});
});
});</pre><p>You can already see that the latter example requires much more code and is harder to read. The nesting will keep increasing for every I/O operation you wish to perform. This phenomenon is called <em>callback hell</em>. Callbacks force the programmer to manually transform his program to continuation passing style. <a href="https://github.com/joyent/node/wiki/modules#wiki-async-flow" target="_blank">Various libraries</a> exist to ease the pain. Programmers familiar with <em>monads</em> will see an excellent opportunity to apply monads. A notation similar to Haskell’s <code>do</code>-syntax or Scala’s <code>for</code>-expressions would make the code readable again and resemble the synchronous variant. Lisp macros are also a viable option.<span class="footnote">See <a href="#bib-16" class="ref"><span class="bib">16</span> Escaping Callback Hell with ClojureScript macros</a>, a blog post about writing a macro to solve callback hell in ClojureScript, a variant of the Clojure programming language that compiles to JavaScript. Also see <a href="#compiling-to-javascript" class="ref">Compiling to JavaScript</a>.</span></p></div></div>
<div class="chapter" id="chapter-8"><h3 id="compiling-to-javascript">VIII. Compiling to JavaScript</h3><p>In the last decade the Internet has grown enormously. Web 2.0<span class="footnote">Web 2.0 is the term bestowed upon the rise of social media and the importance of user-generated content, e.g. social networks, video sharing, blogs, wikis, and all kinds of web applications.</span> applications have become more powerful and advanced. As the size of these web applications, in essence JavaScript programs, increased, it became more and more obvious that JavaScript isn’t suited for building large programs, and never was intended for that purpose anyway.</p><p>Many features targeted at managing increasing complexity are absent in JavaScript, or have to be emulated by the programmer. We have discussed many of them: the lack of static types, emulating <a href="#modularity" class="ref">Modularity</a>, emulating classes via prototypes, …</p><p>Thankfully, JavaScript is equipped with enough powerful building blocks (first-class functions, closures, prototype-based programming) to emulate many of the desired features, but the emulation requires lots of boilerplate code. The solution people have come up with for this problem is to create new languages that compile to JavaScript. Initially it will sound odd, to <em>compile to a high-level language</em>. But in this case it actually makes sense. JavaScript is already supported by (virtually) every browser, and it would be an insurmountable obstacle to create a new language supported by all browser vendors.<span class="footnote">Standards compliance of JavaScript, HTML and CSS is already a problem in the browser landscape.</span> The current JavaScript engines are plenty fast.</p><p>JavaScript has become the <em>assembly language of the web</em>.<span class="footnote">Some people argue that <em>VM</em> (Virtual Machine) would be more accurate.</span></p><p>Here follows a selection of interesting languages, in no particular order, that compile to JavaScript:</p><ul><li><a href="https://developers.google.com/web-toolkit/" target="_blank">Google Web Toolkit</a> compiles Java to JavaScript.</li><li><a href="http://coffeescript.org/" target="_blank">CoffeeScript</a> is a layer of syntactic sugar over JavaScript inspired by Ruby, Python and Haskell. Of all the languages compiling to JavaScript, CoffeeScript is probably the most popular.</li><li><a href="http://livescript.net/" target="_blank">LiveScript</a> is a descendant of CoffeeScript with an emphasis on functional programming.<span class="footnote">Indeed, LiveScript briefly was the <a href="#naming-history">official name</a> of JavaScript in 1995.</span></li><li><a href="https://github.com/clojure/clojurescript" target="_blank">ClojureScript</a>, a variant of Clojure, which was originally targeted at the JVM.</li><li><a href="http://elm-lang.org/" target="_blank">Elm</a>, a type inferenced language intended for <a href="http://en.wikipedia.org/wiki/Functional_reactive_programming" target="_blank">Functional Reactive Programming</a>.</li><li><a href="http://haxe.org/" target="_blank">Haxe</a>, a high-level multiplatform language. Other than to JavaScript, Haxe can also be compiled to Flash, PHP, …</li><li><a href="http://cappuccino.org/" target="_blank">Objective-J</a> is to JavaScript as Objective-C is to C. Objective-J is tightly connected to the Cappuccino framework.</li><li><a href="http://impredicative.com/ur/" target="_blank">Ur</a> is a functional language in which the impossibility of invalid HTML, code-injection attacks, … is enforced by the type checker.</li><li><a href="http://opalang.org/" target="_blank">Opa</a> is a language and multi-tiered (server-side, client-side, and database) framework for writing secure and scalable web applications.</li><li><a href="http://www.dartlang.org/" target="_blank">Dart</a> is Google’s attempt to develop a more Java-like language for the web with support for classes, modules, and optional typing.</li><li><a href="http://www.typescriptlang.org/" target="_blank">TypeScript</a> is Microsoft’s answer to Dart.</li></ul><p>Besides the languages above, there exist ports of Haskell, F#, Objective-C, ActionScript, Ruby, Python, OCaml, SML, C#, Smalltalk, C<span class="footnote">Via <a href="https://github.com/kripken/emscripten" target="_blank">Emscripten</a>, a LLVM bitcode to JavaScript compiler. Many <a href="https://github.com/kripken/emscripten/wiki" target="_blank">existing programs</a> written in C have been ported to the browser through the use of this compiler, e.g. SQLite, OpenJPEG, even a PDF viewer.</span>, Basic, Io, Logo, Tcl, and Erlang to JavaScript. There are especially many Lisp dialects that can be compiled to JavaScript or are created from scratch on top of JavaScript, which demonstrates the similarity of the two languages. For a more comprehensive list see <a href="https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS" target="_blank">List of languages that compile to JS</a> and <a href="http://altjs.org/" target="_blank">altJS</a>.</p></div>
<div class="chapter" id="chapter-9"><h3 id="closing-thoughts">Closing thoughts</h3><p>Most programmers know JavaScript as a weird and ugly language, used to hack together little scripts to enhance web pages. When encountered with some of JavaScript’s unfortunate design choices (<a href="#semicolons">semicolon insertion</a>, <a href="#-undefined-null-">undefined & null</a>, …) programmers’ perception only evolves further in the negative direction.<span class="footnote">Also see <a href="#bib-8" class="ref"><span class="bib">8</span> JavaScript: The World's Most Misunderstood Programming Language</a>.</span></p><p>But when taking a longer look at the language, the good parts start to shine through: first-class functions, closures, prototypes, …<span class="footnote">Funnily enough (or not?), the three enumerated features are all <a href="#influences">borrowed from other languages</a>.</span> Combined, they provide the programmer great power.</p><p>We bet most programmers didn’t know JavaScript supports monkey patching, traits<span class="footnote">Not full-blown traits like in Scala though.</span>, or higher-order functions.</p></div>
<div id="bibliography">
<h3>Bibliography</h3>
<ol>
<li class="book" id="bib-1"><span class="author">Abelson, H., & Sussman, G.J.</span> <span class="year">(1984)</span>. <span class="title">Structure and Interpretation of Computer Programs</span>. <span class="publisher-address">Cambridge, MA</span>: <span class="publisher">MIT Press</span>.</li>
<li class="blog" id="bib-2"><span class="authors">Buckler, C.</span> (October 10, 2012). <span class="title">How to Create Custom Events in JavaScript</span>. Message posted to <a href="http://jspro.com/raw-javascript/how-to-create-custom-events-in-javascript/">http://jspro.com/raw-javascript/how-to-create-custom-events-in-javascript/</a></li>
<li class="blog" id="bib-3"><span class="authors">Buckler, C.</span> (December 1, 2010). <span class="title">JavaScript Execution and Browser Limits</span>. Message posted to <a href="http://www.sitepoint.com/javascript-execution-browser-limits/">http://www.sitepoint.com/javascript-execution-browser-limits/</a></li>
<li class="blog" id="bib-4"><span class="authors">Cherry, B.</span> (March 12, 2010). <span class="title">JavaScript Module Pattern: In-Depth</span>. Message posted to <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth</a></li>
<li class="blog" id="bib-5"><span class="authors">Cornford, R.</span> (March, 2004). <span class="title">Javascript Closures</span>. Message posted to <a href="http://jibbering.com/faq/notes/closures/">http://jibbering.com/faq/notes/closures/</a></li>
<li class="blog" id="bib-6"><span class="authors">Crockford, D.</span> <span class="title">The Little JavaScripter</span>. Message posted to <a href="http://crockford.com/javascript/little.html">http://crockford.com/javascript/little.html</a></li>
<li class="book" id="bib-7"><span class="author">Crockford, D.</span> <span class="year">(2008)</span>. <span class="title">JavaScript: The Good Parts</span>. <span class="publisher-address">Sebastopol, CA</span>: <span class="publisher">O'Reilly Media</span>.</li>
<li class="blog" id="bib-8"><span class="authors">Crockford, D.</span> (2001). <span class="title">JavaScript: The World's Most Misunderstood Programming Language</span>. Message posted to <a href="http://javascript.crockford.com/javascript.html">http://javascript.crockford.com/javascript.html</a></li>
<li class="blog" id="bib-9"><span class="authors">De Rosa, A.</span> (October 15, 2012). <span class="title">Five Useful Functions Missing in JavaScript</span>. Message posted to <a href="http://jspro.com/raw-javascript/5-useful-functions-missing-in-javascript/">http://jspro.com/raw-javascript/5-useful-functions-missing-in-javascript/</a></li>
<li class="blog" id="bib-10"><span class="authors">Edwards, J.</span> (October 15, 2012). <span class="title">Modular Design Patterns: Private, Privileged, and Protected Members in JavaScript</span>. Message posted to <a href="http://jspro.com/raw-javascript/modular-design-patterns-in-javascript/">http://jspro.com/raw-javascript/modular-design-patterns-in-javascript/</a></li>
<li class="blog" id="bib-11"><span class="authors">Eich, B.</span> (April 3, 2008). <span class="title">Popularity</span>. Message posted to <a href="https://brendaneich.com/2008/04/popularity/">https://brendaneich.com/2008/04/popularity/</a></li>
<li class="blog" id="bib-12"><span class="authors">Eich, B.</span> (July 21, 2010). <span class="title">A Brief History of JavaScript</span>. Message posted to <a href="https://brendaneich.com/2010/07/a-brief-history-of-javascript/">https://brendaneich.com/2010/07/a-brief-history-of-javascript/</a></li>
<li class="blog" id="bib-13"><span class="authors">Eich, B.</span> (August 23, 2008). <span class="title">TraceMonkey: JavaScript Lightspeed</span>. Message posted to <a href="https://brendaneich.com/2008/08/tracemonkey-javascript-lightspeed/">https://brendaneich.com/2008/08/tracemonkey-javascript-lightspeed/</a></li>
<li class="book" id="bib-14"><span class="author">Flanagan, D.</span> <span class="year">(2011)</span>. <span class="title">JavaScript: The Definitive Guide</span> <span class="edition">(6th ed.)</span>. <span class="publisher-address">Sebastopol, CA</span>: <span class="publisher">O'Reilly Media</span>.</li>
<li class="blog" id="bib-15"><span class="authors">Lippert, E.</span> (September 17, 2003). <span class="title">How Do The Script Garbage Collectors Work?</span>. Message posted to <a href="http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53038.aspx">http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53038.aspx</a></li>
<li class="blog" id="bib-16"><span class="authors">McKenna, B.</span> (July 24, 2011). <span class="title">Escaping Callback Hell with ClojureScript macros</span>. Message posted to <a href="http://brianmckenna.org/blog/cps_transform_js">http://brianmckenna.org/blog/cps_transform_js</a></li>
<li class="book" id="bib-17"><span class="author">Okasaki, C.</span> <span class="year">(1999)</span>. <span class="title">Purely Functional Data Structures</span>. <span class="publisher-address">Cambridge, England</span>: <span class="publisher">Cambridge University Press</span>.</li>
<li class="blog" id="bib-18"><span class="authors">Osmani, A.</span> (November 5, 2012). <span class="title">Writing Fast, Memory-Efficient JavaScript</span>. Message posted to <a href="http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/">http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/</a></li>
<li class="blog" id="bib-19"><span class="authors">Padburry, D.</span> (August 21, 2011). <span class="title">JavaScript Modules</span>. Message posted to <a href="http://blog.davidpadbury.com/2011/08/21/javascript-modules/">http://blog.davidpadbury.com/2011/08/21/javascript-modules/</a></li>
<li class="blog" id="bib-20"><span class="authors">Rauschmayer, A.</span> (December 17, 2011). <span class="title">Fake operator overloading in JavaScript</span>. Message posted to <a href="http://www.2ality.com/2011/12/fake-operator-overloading.html">http://www.2ality.com/2011/12/fake-operator-overloading.html</a></li>
<li class="blog" id="bib-21"><span class="authors">Resig, J.</span> (August 22, 2008). <span class="title">TraceMonkey</span>. Message posted to <a href="http://ejohn.org/blog/tracemonkey/">http://ejohn.org/blog/tracemonkey/</a></li>
<li class="journal-article" id="bib-22"><span class="authors">Severance, C.</span> <span class="year">(2012)</span>. <span class="title">JavaScript: Designing a Language in 10 Days</span>. <span class="journal">Computer</span>, <span class="volume">45</span>, <span class="pages">7-8</span>. <span class="publisher-address">Los Alamitos, CA</span>: <span class="publisher">IEEE Computer Society</span>.</li>
<li class="blog" id="bib-23"><span class="authors">Shariff, D.</span> (June 19, 2011). <span class="title">What is the Execution Context & Stack in JavaScript?</span>. Message posted to <a href="http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/">http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/</a></li>
<li class="blog" id="bib-24"><span class="authors">Smith, N.</span> (September 14, 2012). <span class="title">Functional Programming in JavaScript</span>. Message posted to <a href="http://dailyjs.com/2012/09/14/functional-programming/">http://dailyjs.com/2012/09/14/functional-programming/</a></li>
<li class="blog" id="bib-25"><span class="authors">Sofer, D.</span> (May 26, 2010). <span class="title">Concurrency, JavaScript and JQuery</span>. Message posted to <a href="http://blog.sofer.com/tech/2010/05/26/concurrency-javascript-jquery.html">http://blog.sofer.com/tech/2010/05/26/concurrency-javascript-jquery.html</a></li>
<li class="blog" id="bib-26"><span class="authors">Tetlaw, A.</span> (November 11, 2008). <span class="title">arguments: A JavaScript Oddity</span>. Message posted to <a href="http://www.sitepoint.com/arguments-a-javascript-oddity/">http://www.sitepoint.com/arguments-a-javascript-oddity/</a></li>
<li class="blog" id="bib-27"><span class="authors">Willison, S.</span> (March 7, 2006). <span class="title">A re-introduction to JavaScript (JS Tutorial)</span>. Message posted to <a href="https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript">https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript</a></li>
<li class="blog" id="bib-28"><span class="authors">Wilton-Jones, M.</span> <span class="title">JavaScript History</span>. Message posted to <a href="http://www.howtocreate.co.uk/jshistory.html">http://www.howtocreate.co.uk/jshistory.html</a></li>
<li class="website" id="bib-29"><span class="siteName">About.com</span>. <span class="title">A Brief History of Javascript</span>. Retrieved November 3, 2012, from <a href="http://javascript.about.com/od/reference/a/history.htm">http://javascript.about.com/od/reference/a/history.htm</a></li>
<li class="encyc" id="bib-30"><span class="title">ECMAScript</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 3, 2012, from <a href="http://en.wikipedia.org/wiki/ECMAScript">http://en.wikipedia.org/wiki/ECMAScript</a></li>
<li class="encyc" id="bib-31"><span class="title">ECMAScript Syntax</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 3, 2012, from <a href="http://en.wikipedia.org/wiki/ECMAScript_syntax">http://en.wikipedia.org/wiki/ECMAScript_syntax</a></li>
<li class="website" id="bib-32"><span class="siteName">JSON</span>. <span class="title">Introducing JSON</span>. <a href="http://www.json.org">http://www.json.org</a></li>
<li class="website" id="bib-33"><span class="siteName">Mozilla Developer Network</span>. (2012). <span class="title">JavaScript - Reference - Functions and function scope - arguments</span>. Retrieved November 3, 2012, from <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments</a></li>
<li class="encyc" id="bib-34"><span class="title">JavaScript History</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 3, 2012, from <a href="http://en.wikipedia.org/wiki/JavaScript#History">http://en.wikipedia.org/wiki/JavaScript#History</a></li>
<li class="encyc" id="bib-35"><span class="title">JavaScript Syntax</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 13, 2012, from <a href="http://en.wikipedia.org/wiki/JavaScript_syntax">http://en.wikipedia.org/wiki/JavaScript_syntax</a></li>
<li class="website" id="bib-36"><span class="siteName">About.com</span>. <span class="title">JavaScript and JScript: What's the Difference?</span>. Retrieved November 3, 2012, from <a href="http://javascript.about.com/od/reference/a/jscript.htm">http://javascript.about.com/od/reference/a/jscript.htm</a></li>
<li class="website" id="bib-37"><span class="siteName">WebScanNotes.com</span>. (2012). <span class="title">Javascript Semantics for Computer Scientists</span>. Retrieved November 3, 2012, from <a href="http://webscannotes.com/2012/06/19/javascript-semantics-for-computer-scientists-part-1-variables-and-scope/">http://webscannotes.com/2012/06/19/javascript-semantics-for-computer-scientists-part-1-variables-and-scope/</a></li>
<li class="encyc" id="bib-38"><span class="title">Just-in-time compilation</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 10, 2012, from <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation">http://en.wikipedia.org/wiki/Just-in-time_compilation</a></li>
<li class="encyc" id="bib-39"><span class="title">List of ECMAScript engines</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 10, 2012, from <a href="http://en.wikipedia.org/wiki/List_of_ECMAScript_engines">http://en.wikipedia.org/wiki/List_of_ECMAScript_engines</a></li>
<li class="website" id="bib-40"><span class="siteName">Dev.Opera</span>. (2008). <span class="title">MAMA: Key findings</span>. Retrieved November 3, 2012, from <a href="http://dev.opera.com/articles/view/mama-key-findings/">http://dev.opera.com/articles/view/mama-key-findings/</a></li>
<li class="encyc" id="bib-41"><span class="title">Monkey patch</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 9, 2012, from <a href="http://en.wikipedia.org/wiki/Monkey_patch">http://en.wikipedia.org/wiki/Monkey_patch</a></li>
<li class="encyc" id="bib-42"><span class="title">Node.js</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 11, 2012, from <a href="http://en.wikipedia.org/wiki/Node.js">http://en.wikipedia.org/wiki/Node.js</a></li>
<li class="website" id="bib-43"><span class="siteName">Node.js</span>. (2012). <span class="title">Node.js v0.8.14 Manual & Documentation - Modules</span>. <a href="http://nodejs.org/api/modules.html">http://nodejs.org/api/modules.html</a></li>
<li class="encyc" id="bib-44"><span class="title">Prototype-based programming</span>. In <span class="encyc">Wikipedia</span>. Retrieved November 1, 2012, from <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">http://en.wikipedia.org/wiki/Prototype-based_programming</a></li>
<li class="website" id="bib-45"><span class="siteName">Google Developers</span>. (2012). <span class="title">V8 Design Elements</span>. <a href="https://developers.google.com/v8/design">https://developers.google.com/v8/design</a></li>
<li class="website" id="bib-46"><span class="siteName">Google Developers</span>. (2012). <span class="title">V8 Introduction</span>. <a href="https://developers.google.com/v8/intro">https://developers.google.com/v8/intro</a></li>
<li class="website" id="bib-47"><span class="siteName">Dev.Opera</span>. (2009). <span class="title">What can you do with JavaScript?</span>. Retrieved November 3, 2012, from <a href="http://dev.opera.com/articles/view/javascript-uses/">http://dev.opera.com/articles/view/javascript-uses/</a></li></ol>
</div>
</body>
</html>