Skip to content

Instantly share code, notes, and snippets.

@tonystubblebine
Created May 2, 2019 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonystubblebine/9415ff6616a4db45e9b23a051296ecda to your computer and use it in GitHub Desktop.
Save tonystubblebine/9415ff6616a4db45e9b23a051296ecda to your computer and use it in GitHub Desktop.
<div data-post-id="31535030616b" data-source="post_page" data-collection-id="d0b105d10f0a" data-tracking-context="postPage" data-scroll="native">
<section>
<div>
<div>
<p>When we were getting ready to launch&nbsp;<a href="http://medium.com/better-programming" target="_blank" data-href="http://medium.com/better-programming">Better Programming</a>, I reached out to someone I consider a master of programming,&nbsp;<a href="http://raganwald.com/" target="_blank" rel="nofollow noopener" data-href="http://raganwald.com/">Reginald Braithwaite</a>&nbsp;(known as&nbsp;<a href="https://twitter.com/raganwald" target="_blank" rel="nofollow noopener" data-href="https://twitter.com/raganwald">Raganwald</a>&nbsp;in many quarters). What I wanted to know is if he&rsquo;d contribute a sample chapter from his book&nbsp;<a href="https://leanpub.com/javascriptallongesix" target="_blank" rel="nofollow noopener" data-href="https://leanpub.com/javascriptallongesix">JavaScript Allong&eacute;, the &ldquo;Six&rdquo; Edition</a>.</p>
<p>His reaction, instead, was simply to change the copyright terms on his book to Creative Commons: Attribution/Share-alike and tell me to run wild with it. (Maybe wild is an overstatement).</p>
<p>So below is a section of the book, a very long section, that I found valuable in a very particular way. There are lots of javascript tutorials for people who&rsquo;ve never programmed before. But I&rsquo;ve programmed forever, at least since 1994 (or even the 80s if you count moving an on-screen turtle with Logo).</p>
<p>However, when the programming world jumped to Javascript, I got a little lost. It took me a while to realize why, although it&rsquo;s obvious in hindsight. I never really understood the fundamentals of the Javascript language. I&rsquo;d previously always had the experience of languages being similar enough that I was mostly just looking up the occasional syntax detail. For example, I shipped my first PHP and Rails projects with a mental model that was based on Perl web development. Javascript was just a bit too different though, and so I find myself needing to go back and study the fundamentals.</p>
<p>That&rsquo;s where Reginald&rsquo;s book comes in. I find his writing to be pedantic in ways that remind me of my computer science professors. And that&rsquo;s exactly what I&rsquo;m looking for &mdash; this isn&rsquo;t a tutorial for first-time programmers. Plus, I imagine that Reginald would say that having pedantically detailed knowledge of your programming languages is pragmatic &mdash; you&rsquo;ll work faster and make fewer mistakes.</p>
<p>The tutorial below does start with the extreme basics: values and then variables. I found it valuable to get that refresher. But the real meat came when he gets into functions.</p>
<p>I read the below in Chrome with my Javascript console on like so. That way I could test my own versions of the code as I went.</p>
<figure>
<div>
<div data-image-id="1*JgwCpVJgIazqXPhXhUkfdQ.png" data-width="2866" data-height="1486" data-action="zoom" data-action-value="1*JgwCpVJgIazqXPhXhUkfdQ.png" data-scroll="native"><canvas width="75" height="38"></canvas><img src="https://cdn-images-1.medium.com/max/1600/1*JgwCpVJgIazqXPhXhUkfdQ.png" alt="" data-src="https://cdn-images-1.medium.com/max/1600/1*JgwCpVJgIazqXPhXhUkfdQ.png" /></div>
</div>
<figcaption>Open the Javascript console by right clicking &gt; Inspect &gt;&nbsp;Console</figcaption>
</figure>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Prelude: Values and Expressions over&nbsp;Coffee</h3>
<p><em>The following material is extremely basic, however like most stories, the best way to begin is to start at the very beginning.</em></p>
<p>Imagine we are visiting our favourite coffee shop. They will make for you just about any drink you desire, from a short, intense espresso ristretto through a dry cappuccino, up to those coffee-flavoured desert concoctions featuring various concentrated syrups and milks. (You tolerate the existence of sugary drinks because they provide a sufficient profit margin to the establishment to finance your hanging out there all day using their WiFi and ordering a $3 drink every few hours.)</p>
<p>You express your order at one end of their counter, the folks behind the counter perform their magic, and deliver the coffee you value at the other end. This is exactly how the JavaScript environment works for the purpose of this book. We are going to dispense with web servers, browsers, and other complexities and deal with this simple model: You give the computer an expression, and it returns a value, just as you express your wishes to a barista and receive a coffee in return.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>values are expressions</h4>
<p>All values are expressions. Say you hand the barista a caf&eacute; Cubano. Yup, you hand over a cup with some coffee infused through partially caramelized sugar. You say, &ldquo;I want one of these.&rdquo; The barista is no fool, she gives it straight back to you, and you get exactly what you want. Thus, a caf&eacute; Cubano is an expression (you can use it to place an order) and a value (you get it back from the barista).</p>
<p>Let&rsquo;s try this with something the computer understands easily:</p>
<pre><code>42</code></pre>
<p>Is this an expression? A value? Neither? Or both?</p>
<p>The answer is, this is both an expression&nbsp;<em>and</em>&nbsp;a value. The way you can tell that it&rsquo;s both is very easy: When you type it into JavaScript, you get the same thing back, just like our caf&eacute; Cubano:</p>
<pre><code>42</code> <br /><code>//=&gt; 42</code></pre>
<p>All values are expressions. That&rsquo;s easy! Are there any other kinds of expressions? Sure! let&rsquo;s go back to the coffee shop. Instead of handing over the finished coffee, we can hand over the ingredients. Let&rsquo;s hand over some ground coffee plus some boiling water.</p>
<p>Astute readers will realize we&rsquo;re omitting something. Congratulations! Take a sip of espresso. We&rsquo;ll get to that in a moment.</p>
<p>Now the barista gives us back an espresso. And if we hand over the espresso, we get the espresso right back. So, boiling water plus ground coffee is an expression, but it isn&rsquo;t a value. Boiling water is a value. Ground coffee is a value. Espresso is a value. Boiling water plus ground coffee is an expression.</p>
<p>Let&rsquo;s try this as well with something else the computer understands easily:</p>
<pre><code>"JavaScript"</code> <code>+</code> <code>" "</code> <code>+</code> <code>"Allonge"</code> <br /><code>//=&gt; "JavaScript Allonge"</code></pre>
<p>Now we see that &ldquo;strings&rdquo; are values, and you can make an expression out of strings and an operator&nbsp;<code>+</code>. Since strings are values, they are also expressions by themselves. But strings with operators are not values, they are expressions. Now we know what was missing with our &ldquo;coffee grounds plus hot water&rdquo; example. The coffee grounds were a value, the boiling hot water was a value, and the &ldquo;plus&rdquo; operator between them made the whole thing an expression that was not a value.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>values and&nbsp;identity</h4>
<p>In JavaScript, we test whether two values are identical with the&nbsp;<code>===</code>&nbsp;operator, and whether they are not identical with the&nbsp;<code>!==</code>&nbsp;operator:</p>
<pre><code>2</code> <code>===</code> <code>2</code> <br /><code>//=&gt; true</code> </pre>
<pre><code>'hello'</code> <code>!==</code> <code>'goodbye'</code> <br /><code>//=&gt; true</code></pre>
<p>How does&nbsp;<code>===</code>&nbsp;work, exactly? Imagine that you&rsquo;re shown a cup of coffee. And then you&rsquo;re shown another cup of coffee. Are the two cups &ldquo;identical?&rdquo; In JavaScript, there are four possibilities:</p>
<p>First, sometimes, the cups are of different kinds. One is a demitasse, the other a mug. This corresponds to comparing two things in JavaScript that have different&nbsp;<em>types</em>. For example, the string&nbsp;<code>"2"</code>&nbsp;is not the same thing as the number&nbsp;<code>2</code>. Strings and numbers are different types, so strings and numbers are never identical:</p>
<pre><code>2</code> <code>===</code> <code>'2'</code> <br /><code>//=&gt; false</code> </pre>
<pre><code>true</code> <code>!==</code> <code>'true'</code> <br /><code>//=&gt; true</code></pre>
<p>Second, sometimes, the cups are of the same type&ndash;perhaps two espresso cups&ndash;but they have different contents. One holds a single, one a double. This corresponds to comparing two JavaScript values that have the same type but different &ldquo;content.&rdquo; For example, the number&nbsp;<code>5</code>&nbsp;is not the same thing as the number&nbsp;<code>2</code>.</p>
<pre><code>true</code> <code>===</code> <code>false</code> <br /><code>//=&gt; false</code> </pre>
<pre><code>2</code> <code>!==</code> <code>5</code> <br /><code>//=&gt; true</code> </pre>
<pre><code>'two'</code> <code>===</code> <code>'five'</code> <br /><code>//=&gt; false</code></pre>
<p>What if the cups are of the same type&nbsp;<em>and</em>&nbsp;the contents are the same? Well, JavaScript&rsquo;s third and fourth possibilities cover that.</p>
<h4>value types</h4>
<p>Third, some types of cups have no distinguishing marks on them. If they are the same kind of cup, and they hold the same contents, we have no way to tell the difference between them. This is the case with the strings, numbers, and booleans we have seen so far.</p>
<pre><code>2</code> <code>+</code> <code>2</code> <code>===</code> <code>4</code> <br /><code>//=&gt; true</code> </pre>
<pre><code>(2</code> <code>+</code> <code>2</code> <code>===</code> <code>4)</code> <code>===</code> <code>(2</code> <code>!==</code> <code>5)</code> <br /><code>//=&gt; true</code></pre>
<p>Note well what is happening with these examples: Even when we obtain a string, number, or boolean as the result of evaluating an expression, it is identical to another value of the same type with the same &ldquo;content.&rdquo; Strings, numbers, and booleans are examples of what JavaScript calls &ldquo;value&rdquo; or &ldquo;primitive&rdquo; types. We&rsquo;ll use both terms interchangeably.</p>
<p>We haven&rsquo;t encountered the fourth possibility yet. Stretching the metaphor somewhat, some types of cups have a serial number on the bottom. So even if you have two cups of the same type, and their contents are the same, you can still distinguish between them.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>reference types</h4>
<p>So what kinds of values might be the same type and have the same contents, but not be considered identical to JavaScript? Let&rsquo;s meet a data structure that is very common in contemporary programming languages, the&nbsp;<em>Array</em>&nbsp;(other languages sometimes call it a List or a Vector).</p>
<p>An array looks like this:&nbsp;<code>[1, 2, 3]</code>. This is an expression, and you can combine&nbsp;<code>[]</code>&nbsp;with other expressions. Go wild with things like:</p>
<pre><code>[2-1,</code> <code>2,</code> <code>2+1]</code> <br /><code>[1,</code> <code>1+1,</code> <code>1+1+1]</code></pre>
<p>Notice that you are always generating arrays with the same contents. But are they identical the same way that every value of&nbsp;<code>42</code>&nbsp;is identical to every other value of&nbsp;<code>42</code>? Try these for yourself:</p>
<pre><code>[2-1,</code> <code>2,</code> <code>2+1]</code> <code>===</code> <code>[1,2,3]</code> <br /><code>[1,2,3]</code> <code>===</code> <code>[1,</code> <code>2,</code> <code>3]</code> <br /><code>[1,</code> <code>2,</code> <code>3]</code> <code>===</code> <code>[1,</code> <code>2,</code> <code>3]</code></pre>
<p>How about that! When you type&nbsp;<code>[1, 2, 3]</code>&nbsp;or any of its variations, you are typing an expression that generates its own&nbsp;<em>unique</em>&nbsp;array that is not identical to any other array, even if that other array also looks like&nbsp;<code>[1, 2, 3]</code>. It&rsquo;s as if JavaScript is generating new cups of coffee with serial numbers on the bottom.</p>
<p>They look the same, but if you examine them with&nbsp;<code>===</code>, you see that they are different. Every time you evaluate an expression (including typing something in) to create an array, you&rsquo;re creating a new, distinct value even if it&nbsp;<em>appears</em>&nbsp;to be the same as some other array value. As we&rsquo;ll see, this is true of many other kinds of values, including&nbsp;<em>functions</em>, the main subject of this book.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>A Rich Aroma: Basic&nbsp;Numbers</h4>
<blockquote>In computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values such as integers, floating-point numbers, and strings, and usually for booleans and characters; some also have notations for elements of enumerated types and compound values such as arrays, records, and objects. An anonymous function is a literal for the function type. &mdash; <a href="https://en.wikipedia.org/wiki/Literal_%28computer_programming%29" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Literal_(computer_programming)">Wikipedia</a></blockquote>
<p>JavaScript, like most languages, has a collection of literals. We saw that an expression consisting solely of numbers, like&nbsp;<code>42</code>, is a literal. It represents the number forty-two, which is 42 base 10. Not all numbers are base ten. If we start a literal with a zero, it is an octal literal. So the literal&nbsp;<code>042</code>&nbsp;is 42 base 8, which is actually 34 base 10.</p>
<p>Internally, both&nbsp;<code>042</code>&nbsp;and&nbsp;<code>34</code>&nbsp;have the same representation, as&nbsp;<a href="http://en.wikipedia.org/wiki/Double-precision_floating-point_format" target="_blank" rel="nofollow noopener" data-href="http://en.wikipedia.org/wiki/Double-precision_floating-point_format">double-precision floating point</a>&nbsp;numbers. A computer&rsquo;s internal representation for numbers is important to understand. The machine&rsquo;s representation of a number almost never lines up perfectly with our understanding of how a number behaves, and thus there will be places where the computer&rsquo;s behaviour surprises us if we don&rsquo;t know a little about what it&rsquo;s doing &ldquo;under the hood.&rdquo;</p>
<p>For example, the largest integer JavaScript can safely handle is&nbsp;<code>9007199254740991</code>, or&nbsp;<code>2^53 - 1</code>. Like most programming languages, JavaScript does not allow us to use commas to separate groups of digits.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>floating</h4>
<p>Most programmers never encounter the limit on the magnitude of an integer. But we mentioned that numbers are represented internally as floating point, meaning that they need not be just integers. We can, for example, write&nbsp;<code>1.5</code>or&nbsp;<code>33.33</code>, and JavaScript represents these literals as floating point numbers.</p>
<p>It&rsquo;s tempting to think we now have everything we need to do things like handle amounts of money, but as the late John Belushi would say, &ldquo;<a href="https://www.youtube.com/watch?v=4Q4JfaHjAng" target="_blank" rel="nofollow noopener" data-href="https://www.youtube.com/watch?v=4Q4JfaHjAng">Nooooooooooooooooooooo.</a>&rdquo; A computer&rsquo;s internal representation for a floating point number is binary, while our literal number was in base ten. This makes no meaningful difference for integers, but it does for fractions, because some fractions base 10 do not have exact representations base 2.</p>
<p>One of the most oft-repeated examples is this:</p>
<pre><code>1.0</code> <br /><code>//=&gt; 1</code> </pre>
<pre><code>1.0</code> <code>+</code> <code>1.0</code> <br /><code>//=&gt; 2</code> </pre>
<pre><code>1.0</code> <code>+</code> <code>1.0</code> <code>+</code> <code>1.0</code> <br /><code>//=&gt; 3</code></pre>
<p>However:</p>
<pre><code>0.1</code> <br /><code>//=&gt; 0.1</code> </pre>
<pre><code>0.1</code> <code>+</code> <code>0.1</code> <br /><code>//=&gt; 0.2</code> </pre>
<pre><code>0.1</code> <code>+</code> <code>0.1</code> <code>+</code> <code>0.1</code> <br /><code>//=&gt; 0.30000000000000004</code></pre>
<p>This kind of &ldquo;inexactitude&rdquo; can be ignored when performing calculations that have an acceptable deviation. For example, when centering some text on a page, as long as the difference between what you might calculate longhand and JavaScript&rsquo;s calculation is less than a pixel, there is no observable error.</p>
<p>But as a rule, if you need to work with real numbers, you should have more than a nodding acquaintance with the&nbsp;<a href="https://en.wikipedia.org/wiki/IEEE_floating_point" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/IEEE_floating_point">IEEE Standard for Floating-Point Arithmetic</a>. Professional programmers almost never use floating point numbers to represent monetary amounts. For example, &ldquo;$43.21&rdquo; will nearly always be presented as two numbers:&nbsp;<code>43</code>&nbsp;for dollars and&nbsp;<code>21</code>&nbsp;for cents, not&nbsp;<code>43.21</code>. In this book, we need not think about such details, but outside of this book, we must.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>operations on&nbsp;numbers</h4>
<p>As we&rsquo;ve seen, JavaScript has many common arithmetic operators. We can create expressions that look very much like mathematical expressions, for example, we can write&nbsp;<code>1 + 1</code>&nbsp;or&nbsp;<code>2 * 3</code>&nbsp;or&nbsp;<code>42 - 34</code>&nbsp;or even&nbsp;<code>6 / 2</code>. These can be combined to make more complex expressions, like&nbsp;<code>2 * 5 + 1</code>.</p>
<p>In JavaScript, operators have an order of precedence designed to mimic the way humans typically parse written arithmetic. So:</p>
<pre><code>2</code> <code>*</code> <code>5</code> <code>+</code> <code>1</code> <br /><code>//=&gt; 11</code> </pre>
<pre><code>1</code> <code>+</code> <code>5</code> <code>*</code> <code>2</code> <br /><code>//=&gt; 11</code></pre>
<p>JavaScript treats the expressions as if we had written&nbsp;<code>(2 * 5) + 1</code>&nbsp;and&nbsp;<code>1 + (5 * 2)</code>, because the&nbsp;<code>*</code>&nbsp;operator has a&nbsp;<em>higher precedence</em>&nbsp;than the&nbsp;<code>+</code>&nbsp;operator. JavaScript has many more operators. In a sense, they behave like little functions. If we write&nbsp;<code>1 + 2</code>, this is conceptually similar to writing&nbsp;<code>plus(1, 2)</code>&nbsp;(assuming we have a function that adds two numbers bound to the name&nbsp;<code>plus</code>, of course).</p>
<p>In addition to the common&nbsp;<code>+</code>,&nbsp;<code>-</code>,&nbsp;<code>*</code>, and&nbsp;<code>/</code>, JavaScript also supports modulus,&nbsp;<code>%</code>, and unary negation,&nbsp;<code>-</code>:</p>
<pre><code>-(457</code> <code>%</code> <code>3)</code> <br /><code>//=&gt; -1</code></pre>
<p>There are lots and lots more operators that can be used with numbers, including bitwise operators like&nbsp;<code>|</code>&nbsp;and&nbsp;<code>&amp;</code>&nbsp;that allow you to operate directly on a number&rsquo;s binary representation, and a number of other operators that perform assignment or logical comparison that we will look at later.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>As Little As Possible About Functions, But No&nbsp;Less</h3>
<p>In JavaScript, functions are values, but they are also much more than simple numbers, strings, or even complex data structures like trees or maps. Functions represent computations to be performed. Like numbers, strings, and arrays, they have a representation. Let&rsquo;s start with the second simplest possible function. In JavaScript, it looks like this:</p>
<pre><code>()</code> <code>=&gt;</code> <code>0</code></pre>
<p>This is a function that is applied to no values and returns&nbsp;<code>0</code>. Let&rsquo;s verify that our function is a value like all others:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>0)</code> <br /><code>//=&gt; [Function]</code></pre>
<p>What!? Why didn&rsquo;t it type back&nbsp;<code>() =&gt; 0</code>&nbsp;for us? This&nbsp;<em>seems</em>&nbsp;to break our rule that if an expression is also a value, JavaScript will give the same value back to us. What&rsquo;s going on? The simplest and easiest answer is that although the JavaScript interpreter does indeed return that value, displaying it on the screen is a slightly different matter.&nbsp;<code>[Function]</code>&nbsp;is a choice made by the people who wrote Node.js, the JavaScript environment that hosts the JavaScript REPL. If you try the same thing in a browser, you may see something else.</p>
<p>I&rsquo;d prefer something else, but I must accept that what gets typed back to us on the screen is arbitrary, and all that really counts is that it is somewhat useful for a human to read. But we must understand that whether we see&nbsp;<code>[Function]</code>&nbsp;or&nbsp;<code>() =&gt; 0</code>, internally JavaScript has a full and proper function.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>functions and identities</h4>
<p>You recall that we have two types of values with respect to identity: Value types and reference types. Value types share the same identity if they have the same contents. Reference types do not.</p>
<p>Which kind are functions? Let&rsquo;s try them out and see. For reasons of appeasing the JavaScript parser, we&rsquo;ll enclose our functions in parentheses:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>0)</code> <code>===</code> <code>(()</code> <code>=&gt;</code> <code>0)</code> <br /><code>//=&gt; false</code></pre>
<p>Like arrays, every time you evaluate an expression to produce a function, you get a new function that is not identical to any other function, even if you use the same expression to generate it. &ldquo;Function&rdquo; is a reference type.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>applying functions</h4>
<p>Let&rsquo;s put functions to work. The way we use functions is to&nbsp;<em>apply</em>&nbsp;them to zero or more values called&nbsp;<em>arguments</em>. Just as&nbsp;<code>2 + 2</code>&nbsp;produces a value (in this case&nbsp;<code>4</code>), applying a function to zero or more arguments produces a value as well.</p>
<p>Here&rsquo;s how we apply a function to some values in JavaScript: Let&rsquo;s say that&nbsp;<em>fn_expr</em>&nbsp;is an expression that when evaluated, produces a function. Let&rsquo;s call the arguments&nbsp;<em>args</em>. Here&rsquo;s how to apply a function to some arguments:</p>
<pre><em>fn_expr</em><code>(</code><em>args</em><code>)</code></pre>
<p>Right now, we only know about one such expression:&nbsp;<code>() =&gt; 0</code>, so let&rsquo;s use it. We&rsquo;ll put it in parentheses to keep the parser happy, like we did above:&nbsp;<code>(() =&gt; 0)</code>. Since we aren&rsquo;t giving it any arguments, we&rsquo;ll simply write&nbsp;<code>()</code>&nbsp;after the expression. So we write:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>0)()</code> <br /><code>//=&gt; 0</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>functions that return values and evaluate expressions</h4>
<p>We&rsquo;ve seen&nbsp;<code>() =&gt; 0</code>. We know that&nbsp;<code>(() =&gt; 0)()</code>&nbsp;returns&nbsp;<code>0</code>, and this is unsurprising. Likewise, the following all ought to be obvious:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>1)()</code> <br /><code>//=&gt; 1</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>"Hello, JavaScript")()</code> <br /><code>//=&gt; "Hello, JavaScript"</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>Infinity)()</code> <br /><code>//=&gt; Infinity</code></pre>
<p>Well, the last one&rsquo;s a doozy, but still, the general idea is this: We can make a function that returns a value by putting the value to the right of the arrow.</p>
<p>In the prelude, we looked at expressions. Values like&nbsp;<code>0</code>&nbsp;are expressions, as are things like&nbsp;<code>40 + 2</code>. Can we put an expression to the right of the arrow?</p>
<pre><code>(()</code> <code>=&gt;</code> <code>1</code> <code>+</code> <code>1)()</code> <br /><code>//=&gt; 2</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>"Hello, "</code> <code>+</code> <code>"JavaScript")()</code> <br /><code>//=&gt; "Hello, JavaScript"</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>Infinity</code> <code>*</code> <code>Infinity)()</code> <br /><code>//=&gt; Infinity</code></pre>
<p>Yes, we can. We can put any expression to the right of the arrow. For example,&nbsp;<code>(() =&gt; 0)()</code>&nbsp;is an expression. Can we put it to the right of an arrow, like this:&nbsp;<code>() =&gt; (() =&gt; 0)()</code>?</p>
<p>Let&rsquo;s try it:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>(()</code> <code>=&gt;</code> <code>0)())()</code> <br /><code>//=&gt; 0</code></pre>
<p>Yes, we can! Functions can return the value of evaluating another function.</p>
<p>When dealing with expressions that have a lot of the same characters (like parentheses), you may find it helpful to format the code to make things stand out. So we can also write:</p>
<pre><code>(()</code> <code>=&gt;</code><br /> <code>(()</code> <code>=&gt;</code> <code>0</code><br /> <code>)()</code><br /><code>)()</code><br /><code>//=&gt; 0</code></pre>
<p>It evaluates to the same thing,&nbsp;<code>0</code>.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>commas</h4>
<p>The comma operator in JavaScript is interesting. It takes two arguments, evaluates them both, and itself evaluates to the value of the right-hand argument. In other words:</p>
<pre><code>(1,</code> <code>2)</code> <br /><code>//=&gt; 2</code> </pre>
<pre><code>(1</code> <code>+</code> <code>1,</code> <code>2</code> <code>+</code> <code>2)</code> <br /><code>//=&gt; 4</code></pre>
<p>We can use commas with functions to create functions that evaluate multiple expressions:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>(1</code> <code>+</code> <code>1,</code> <code>2</code> <code>+</code> <code>2))()</code> <br /><code>//=&gt; 4</code></pre>
<p>This is useful when trying to do things that might involve&nbsp;<em>side-effects</em>, but we&rsquo;ll get to that later. In most cases, JavaScript does not care whether things are separated by spaces, tabs, or line breaks. So we can also write:</p>
<pre><code>()</code> <code>=&gt;</code> <br /> <code>(1</code> <code>+</code> <code>1,</code> <code>2</code> <code>+</code> <code>2)</code></pre>
<p>Or even:</p>
<pre><code>()</code> <code>=&gt;</code> <code>(</code> <br /> <code>1</code> <code>+</code> <code>1,</code> <br /> <code>2</code> <code>+</code> <code>2</code> <br /><code>)</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>the simplest possible&nbsp;block</h4>
<p>There&rsquo;s another thing we can put to the right of an arrow, a&nbsp;<em>block</em>. A block has zero or more&nbsp;<em>statements</em>, separated by semicolons.</p>
<p>So, this is a valid function:</p>
<pre><code>()</code> <code>=&gt;</code> <code>{}</code></pre>
<p>It returns the result of evaluating a block that has no statements. What would that be? Let&rsquo;s try it:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>{})()</code> <br /><code>//=&gt; undefined</code></pre>
<p>What is this&nbsp;<code>undefined</code>?</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4><code>undefined</code></h4>
<p>In JavaScript, the absence of a value is written&nbsp;<code>undefined</code>, and it means there is no value. It will crop up again.&nbsp;<code>undefined</code>&nbsp;is its own type of value, and it acts like a value type:</p>
<pre><code>undefined</code> <br /><code>//=&gt; undefined</code></pre>
<p>Like numbers, booleans and strings, JavaScript can print out the value&nbsp;<code>undefined</code>.</p>
<pre><code>undefined</code> <code>===</code> <code>undefined</code> <br /><code>//=&gt; true</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{})()</code> <code>===</code> <code>(()</code> <code>=&gt;</code> <code>{})()</code> <br /><code>//=&gt; true</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{})()</code> <code>===</code> <code>undefined</code> <br /><code>//=&gt; true</code></pre>
<p>No matter how you evaluate&nbsp;<code>undefined</code>, you get an identical value back.&nbsp;<code>undefined</code>&nbsp;is a value that means &ldquo;I don&rsquo;t have a value.&rdquo; But it&rsquo;s still a value&nbsp;:-)</p>
<p>You might think that&nbsp;<code>undefined</code>&nbsp;in JavaScript is equivalent to&nbsp;<code>NULL</code>&nbsp;in SQL. No. In SQL, two things that are&nbsp;<code>NULL</code>&nbsp;are not equal to nor share the same identity, because two unknowns can&rsquo;t be equal. In JavaScript, every&nbsp;<code>undefined</code>&nbsp;is identical to every other&nbsp;<code>undefined</code>.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>void</h4>
<p>We&rsquo;ve seen that JavaScript represents an undefined value by typing&nbsp;<code>undefined</code>, and we&rsquo;ve generated undefined values in two ways:</p>
<ol>
<li>By evaluating a function that doesn&rsquo;t return a value&nbsp;<code>(() =&gt; {})()</code>, and;</li>
<li>By writing&nbsp;<code>undefined</code>&nbsp;ourselves.</li>
</ol>
<p>There&rsquo;s a third way, with JavaScript&rsquo;s&nbsp;<code>void</code>&nbsp;operator. Behold:</p>
<pre><code>void</code> <code>0</code> <br /><code>//=&gt; undefined</code> </pre>
<pre><code>void</code> <code>1</code> <br /><code>//=&gt; undefined</code> </pre>
<pre><code>void</code> <code>(2</code> <code>+</code> <code>2)</code> <br /><code>//=&gt; undefined</code></pre>
<p><code>void</code>&nbsp;is an operator that takes any value and evaluates to&nbsp;<code>undefined</code>, always. So, when we deliberately want an undefined value, should we use the first, second, or third form? The answer is, use&nbsp;<code>void</code>. By convention, use&nbsp;<code>void 0</code>.</p>
<p>The first form works but it&rsquo;s cumbersome. The second form works most of the time, but it is possible to break it by reassigning&nbsp;<code>undefined</code>&nbsp;to a different value. The third form is guaranteed to always work, so that&rsquo;s what we will use.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>back on the&nbsp;block</h4>
<p>Back to our function. We evaluated this:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>{})()</code> <br /><code>//=&gt; undefined</code></pre>
<p>We said that the function returns the result of evaluating a&nbsp;<em>block</em>, and we said that a block is a (possibly empty) list of JavaScript&nbsp;<em>statements</em>&nbsp;separated by semicolons.</p>
<p>Something like:&nbsp;<code>{</code>&nbsp;statement1<code>;</code>&nbsp;statement2<code>;</code>&nbsp;statement3<code>;&nbsp;...&nbsp;;</code>statementn&nbsp;<code>}</code></p>
<p>We haven&rsquo;t discussed these&nbsp;<em>statements</em>. What&rsquo;s a statement?</p>
<p>There are many kinds of JavaScript statements, but the first kind is one we&rsquo;ve already met. An expression is a JavaScript statement. Although they aren&rsquo;t very practical, these are valid JavaScript functions, and they return&nbsp;<code>undefined</code>&nbsp;when applied:</p>
<pre><code>()</code> <code>=&gt;</code> <code>{</code> <code>2</code> <code>+</code> <code>2</code> <code>}</code> </pre>
<pre><code>()</code> <code>=&gt;</code> <code>{</code> <code>1</code> <code>+</code> <code>1;</code> <code>2</code> <code>+</code> <code>2</code> <code>}</code></pre>
<p>As we saw with commas above, we can rearrange these functions onto multiple lines when we feel its more readable that way:</p>
<pre><code>()</code> <code>=&gt;</code> <code>{</code> <br /> <code>1</code> <code>+</code> <code>1;</code> <br /> <code>2</code> <code>+</code> <code>2</code> <br /><code>}</code></pre>
<p>But no matter how we arrange them, a block with one or more expressions still evaluates to&nbsp;<code>undefined</code>:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>2</code> <code>+</code> <code>2</code> <code>})()</code> <br /><code>//=&gt; undefined</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>1</code> <code>+</code> <code>1;</code> <code>2</code> <code>+</code> <code>2</code> <code>})()</code> <br /><code>//=&gt; undefined</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <br /> <code>1</code> <code>+</code> <code>1;</code> <br /> <code>2</code> <code>+</code> <code>2</code> <br /><code>})()</code> <br /><code>//=&gt; undefined</code></pre>
<p>As you can see, a block with one expression does not behave like an expression, and a block with more than one expression does not behave like an expression constructed with the comma operator:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>2</code> <code>+</code> <code>2)()</code> <br /><code>//=&gt; 4</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>2</code> <code>+</code> <code>2</code> <code>})()</code> <br /><code>//=&gt; undefined</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>(1</code> <code>+</code> <code>1,</code> <code>2</code> <code>+</code> <code>2))()</code> <br /><code>//=&gt; 4</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>1</code> <code>+</code> <code>1;</code> <code>2</code> <code>+</code> <code>2</code> <code>})()</code> <br /><code>//=&gt; undefined</code></pre>
<p>So how do we get a function that evaluates a block to return a value when applied? With the&nbsp;<code>return</code>&nbsp;keyword and any expression:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>return</code> <code>0</code> <code>})()</code> <br /><code>//=&gt; 0</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>return</code> <code>1</code> <code>})()</code> <br /><code>//=&gt; 1</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <code>return</code> <code>'Hello '</code> <code>+</code> <code>'World'</code> <code>})()</code> <br /><code>// 'Hello World'</code></pre>
<p>The&nbsp;<code>return</code>&nbsp;keyword creates a&nbsp;<em>return statement</em>&nbsp;that immediately terminates the function application and returns the result of evaluating its expression. For example:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <br /> <code>1</code> <code>+</code> <code>1;</code> <br /> <code>return</code> <code>2</code> <code>+</code> <code>2</code> <br /><code>})()</code> <br /><code>//=&gt; 4</code></pre>
<p>And also:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <br /> <code>return</code> <code>1</code> <code>+</code> <code>1;</code> <br /> <code>2</code> <code>+</code> <code>2</code> <br /><code>})()</code> <br /><code>//=&gt; 2</code></pre>
<p>The return statement is the first statement we&rsquo;ve seen, and it behaves differently than an expression. For example, you can&rsquo;t use one as the expression in a simple function, because it isn&rsquo;t an expression:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>return</code> <code>0)()</code> <br /><code>//=&gt; ERROR</code></pre>
<p>Statements belong inside blocks and only inside blocks. Some languages simplify this by making everything an expression, but JavaScript maintains this distinction, so when learning JavaScript we also learn about statements like function declarations, for loops, if statements, and so forth. We&rsquo;ll see a few more of these later.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>functions that evaluate to functions</h4>
<p>If an expression that evaluates to a function is, well, an expression, and if a return statement can have any expression on its right side&hellip;&nbsp;<em>Can we put an expression that evaluates to a function on the right side of a function expression?</em></p>
<p>Yes:</p>
<pre><code>()</code> <code>=&gt;</code> <code>()</code> <code>=&gt;</code> <code>0</code></pre>
<p>That&rsquo;s a function! It&rsquo;s a function that when applied, evaluates to a function that when applied, evaluates to&nbsp;<code>0</code>. So we have&nbsp;<em>a function, that returns a function, that returns zero</em>. Likewise:</p>
<pre><code>()</code> <code>=&gt;</code> <code>()</code> <code>=&gt;</code> <code>true</code></pre>
<p>That&rsquo;s a function, that returns a function, that returns&nbsp;<code>true</code>:</p>
<pre><code>(()</code> <code>=&gt;</code> <code>()</code> <code>=&gt;</code> <code>true)()()</code> <br /><code>//=&gt; true</code></pre>
<p>We could, of course, do the same thing with a block if we wanted:</p>
<pre><code>()</code> <code>=&gt;</code> <code>()</code> <code>=&gt;</code> <code>{</code> <code>return</code> <code>true;</code> <code>}</code></pre>
<p>But we generally don&rsquo;t.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<p>Well. We&rsquo;ve been very clever, but so far this all seems very abstract.</p>
<p>Diffraction of a crystal is beautiful and interesting in its own right, but you can&rsquo;t blame us for wanting to be shown a practical use for it, like being able to determine the composition of a star millions of light years away. So&hellip; In the next section, we&rsquo;ll see how to make functions practical.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Ah. I&rsquo;d Like to Have an Argument, Please.</h3>
<p>Up to now, we&rsquo;ve looked at functions without arguments. We haven&rsquo;t even said what an argument&nbsp;<em>is</em>, only that our functions don&rsquo;t have any.</p>
<p>Most programmers are perfectly familiar with arguments (often called &ldquo;parameters&rdquo;). Secondary school mathematics discusses this. So you know what they are, and I know that you know what they are, but please be patient with the explanation!</p>
<p>Let&rsquo;s make a function with an argument:</p>
<pre><code>(room)</code> <code>=&gt;</code> <code>{}</code></pre>
<p>This function has one argument,&nbsp;<code>room</code>, and an empty body. Here&rsquo;s a function with two arguments and an empty body:</p>
<pre><code>(room,</code> <code>board)</code> <code>=&gt;</code> <code>{}</code></pre>
<p>I&rsquo;m sure you are perfectly comfortable with the idea that this function has two arguments,&nbsp;<code>room</code>, and&nbsp;<code>board</code>. What does one do with the arguments? Use them in the body, of course. What do you think this is?</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>3.14159265</code></pre>
<p>It&rsquo;s a function for calculating the circumference of a circle given the diameter. I read that aloud as &ldquo;When applied to a value representing the diameter, this function&nbsp;<em>returns</em>&nbsp;the diameter times 3.14159265.&rdquo;</p>
<p>Remember that to apply a function with no arguments, we wrote&nbsp;<code>(() =&gt; {})()</code>. To apply a function with an argument (or arguments), we put the argument (or arguments) within the parentheses, like this:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>3.14159265)(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>You won&rsquo;t be surprised to see how to write and apply a function to two arguments:</p>
<pre><code>((room,</code> <code>board)</code> <code>=&gt;</code> <code>room</code> <code>+</code> <code>board)(800,</code> <code>150)</code> <br /><code>//=&gt; 950</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>a quick summary of functions and&nbsp;bodies</h4>
<p>How arguments are used in a body&rsquo;s expression is probably perfectly obvious to you from the examples, especially if you&rsquo;ve used any programming language (except for the dialect of BASIC&ndash;which I recall from my secondary school&ndash;that didn&rsquo;t allow parameters when you called a procedure).</p>
<p>Expressions consist either of representations of values (like&nbsp;<code>3.14159265</code>,&nbsp;<code>true</code>, and&nbsp;<code>undefined</code>), operators that combine expressions (like&nbsp;<code>3 + 2</code>), some special forms like&nbsp;<code>[1, 2, 3]</code>&nbsp;for creating arrays out of expressions, or&nbsp;<code>function (</code><em>arguments</em><code>) {</code><em>body-statements</em><code>}</code>&nbsp;for creating functions.</p>
<p>One of the important possible statements is a return statement. A return statement accepts any valid JavaScript expression.</p>
<p>This loose definition is recursive, so we can intuit (or use our experience with other languages) that since a function can contain a return statement with an expression, we can write a function that returns a function, or an array that contains another array expression. Or a function that returns an array, an array of functions, a function that returns an array of functions, and so forth:</p>
<pre><code>()</code> <code>=&gt;</code> <code>()</code> <code>=&gt;</code> <code>{};</code> </pre>
<pre><code>()</code> <code>=&gt;</code> <code>[</code> <code>1,</code> <code>2,</code> <code>3];</code> </pre>
<pre><code>[1,</code> <code>[2,</code> <code>3],</code> <code>4];</code> </pre>
<pre><code>()</code> <code>=&gt;</code> <code>[</code> <br /> <code>()</code> <code>=&gt;</code> <code>1,</code> <br /> <code>()</code> <code>=&gt;</code> <code>2,</code> <br /> <code>()</code> <code>=&gt;</code> <code>3</code> <br /><code>];</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>call by&nbsp;value</h4>
<p>Like most contemporary programming languages, JavaScript uses the &ldquo;call by value&rdquo; evaluation strategy. That means that when you write some code that appears to apply a function to an expression or expressions, JavaScript evaluates all of those expressions and applies the functions to the resulting value(s).</p>
<p>So when you write:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>3.14159265)(1</code> <code>+</code> <code>1)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>What happened internally is that the expression&nbsp;<code>1 + 1</code>&nbsp;was evaluated first, resulting in&nbsp;<code>2</code>. Then our circumference function was applied to&nbsp;<code>2</code>.</p>
<p>We&rsquo;ll see below that while JavaScript always calls by value, the notion of a &ldquo;value&rdquo; has additional subtlety. But before we do, let&rsquo;s look at variables.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>variables and&nbsp;bindings</h4>
<p>Right now everything looks simple and straightforward, and we can move on to talk about arguments in more detail. And we&rsquo;re going to work our way up from&nbsp;<code>(diameter) =&gt; diameter * 3.14159265</code>&nbsp;to functions like:</p>
<pre><code>(x)</code> <code>=&gt;</code> <code>(y)</code> <code>=&gt;</code> <code>x</code></pre>
<p><code>(x) =&gt; (y) =&gt; x</code>&nbsp;just looks crazy, as if we are learning English as a second language and the teacher promises us that soon we will be using words like&nbsp;<em>antidisestablishmentarianism</em>. Besides a desire to use long words to sound impressive, this is not going to seem attractive until we find ourselves wanting to discuss the role of the Church of England in 19th-century British politics.</p>
<p>But there&rsquo;s another reason for learning the word&nbsp;<em>antidisestablishmentarianism</em>: We might learn how prefixes and postfixes work in English grammar. It&rsquo;s the same thing with&nbsp;<code>(x) =&gt; (y) =&gt; x</code>. It has a certain important meaning in its own right, and it&rsquo;s also an excellent excuse to learn about functions that make functions, environments, variables, and more.</p>
<p>In order to talk about how this works, we should agree on a few terms (you may already know them, but let&rsquo;s check-in together and &ldquo;synchronize our dictionaries&rdquo;). The first&nbsp;<code>x</code>, the one in&nbsp;<code>(x) =&gt;&nbsp;...</code>, is an&nbsp;<em>argument</em>. The&nbsp;<code>y</code>in&nbsp;<code>function (y)&nbsp;...</code>&nbsp;is another argument. The second&nbsp;<code>x</code>, the one in&nbsp;<code>=&gt; x</code>, is not an argument,&nbsp;<em>it&rsquo;s an expression referring to a variable</em>. Arguments and variables work the same way whether we&rsquo;re talking about&nbsp;<code>(x) =&gt; (y) =&gt; x</code>&nbsp;or just plain&nbsp;<code>(x) =&gt; x</code>.</p>
<p>Every time a function is invoked (&ldquo;invoked&rdquo; means &ldquo;applied to zero or more arguments&rdquo;), a new&nbsp;<em>environment</em>&nbsp;is created. An environment is a (possibly empty) dictionary that maps variables to values by name. The&nbsp;<code>x</code>&nbsp;in the expression that we call a &ldquo;variable&rdquo; is itself an expression that is evaluated by looking up the value in the environment.</p>
<p>How does the value get put in the environment? Well for arguments, that is very simple. When you apply the function to the arguments, an entry is placed in the dictionary for each argument. So when we write:</p>
<pre><code>((x)</code> <code>=&gt;</code> <code>x)(2)</code> <br /><code>//=&gt; 2</code></pre>
<p>What happens is this:</p>
<ol>
<li>JavaScript parses this whole thing as an expression made up of several sub-expressions.</li>
<li>It then starts evaluating the expression, including evaluating sub-expressions</li>
<li>One sub-expression,&nbsp;<code>(x) =&gt; x</code>&nbsp;evaluates to a function.</li>
<li>Another,&nbsp;<code>2</code>, evaluates to the number 2.</li>
<li>JavaScript now evaluates applying the function to the argument&nbsp;<code>2</code>. Here&rsquo;s where it gets interesting&hellip;</li>
<li>An environment is created.</li>
<li>The value &lsquo;2&rsquo; is bound to the name &lsquo;x&rsquo; in the environment.</li>
<li>The expression &lsquo;x&rsquo; (the right side of the function) is evaluated within the environment we just created.</li>
<li>The value of a variable when evaluated in an environment is the value bound to the variable&rsquo;s name in that environment, which is &lsquo;2&rsquo;</li>
<li>And that&rsquo;s our result.</li>
</ol>
<p>When we talk about environments, we&rsquo;ll use an&nbsp;<a href="http://json.org/" target="_blank" rel="nofollow noopener" data-href="http://json.org/">unsurprising syntax</a>&nbsp;for showing their bindings:&nbsp;<code>{x: 2,&nbsp;...}</code>. meaning, that the environment is a dictionary, and that the value&nbsp;<code>2</code>&nbsp;is bound to the name&nbsp;<code>x</code>, and that there might be other stuff in that dictionary we aren&rsquo;t discussing right now.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>call by&nbsp;sharing</h4>
<p>Earlier, we distinguished JavaScript&rsquo;s&nbsp;<em>value types</em>&nbsp;from its&nbsp;<em>reference types</em>. At that time, we looked at how JavaScript distinguishes objects that are identical from objects that are not. Now it is time to take another look at the distinction between value and reference types.</p>
<p>There is a property that JavaScript strictly maintains: When a value&ndash;any value&ndash;is passed as an argument to a function, the value bound in the function&rsquo;s environment must be identical to the original.</p>
<p>We said that JavaScript binds names to values, but we didn&rsquo;t say what it means to bind a name to a value. Now we can elaborate: When JavaScript binds a value-type to a name, it makes a copy of the value and places the copy in the environment. As you recall, value types like strings and numbers are identical to each other if they have the same content. So JavaScript can make as many copies of strings, numbers, or booleans as it wishes.</p>
<p>What about reference types? JavaScript does not place copies of reference values in any environment. JavaScript places&nbsp;<em>references</em>&nbsp;to reference types in environments, and when the value needs to be used, JavaScript uses the reference to obtain the original.</p>
<p>Because many references can share the same value, and because JavaScript passes references as arguments, JavaScript can be said to implement &ldquo;call by sharing&rdquo; semantics. Call by sharing is generally understood to be a specialization of call by value, and it explains why some values are known as value types and other values are known as reference types.</p>
<p>And with that, we&rsquo;re ready to look at&nbsp;<em>closures</em>. When we combine our knowledge of value types, reference types, arguments, and closures, we&rsquo;ll understand why this function always evaluates to&nbsp;<code>true</code>&nbsp;no matter what argument you apply it to:</p>
<pre><code>(value)</code> <code>=&gt;</code> <code>((ref1,</code> <code>ref2)</code> <code>=&gt;</code> <code>ref1</code> <code>===</code> <code>ref2)(value,</code> <code>value)</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Closures and&nbsp;Scope</h3>
<p>It&rsquo;s time to see how a function within a function works:</p>
<pre><code>((x)</code> <code>=&gt;</code> <code>(y)</code> <code>=&gt;</code> <code>x)(1)(2)</code> <br /><code>//=&gt; 1</code></pre>
<p>First off, let&rsquo;s use what we learned above. Given&nbsp;<code>(</code><em>some function</em><code>)(</code><em>some argument</em><code>)</code>, we know that we apply the function to the argument, create an environment, bind the value of the argument to the name, and evaluate the function&rsquo;s expression. So we do that first with this code:</p>
<pre><code>((x)</code> <code>=&gt;</code> <code>(y)</code> <code>=&gt;</code> <code>x)(1)</code> <br /><code>//=&gt; [Function]</code></pre>
<p>The environment belonging to the function with signature&nbsp;<code>(x) =&gt;&nbsp;...</code>becomes&nbsp;<code>{x: 1,&nbsp;...}</code>, and the result of applying the function is another function value. It makes sense that the result value is a function, because the expression for&nbsp;<code>(x) =&gt;&nbsp;...</code>&rsquo;s body is:</p>
<pre><code>(y)</code> <code>=&gt;</code> <code>x</code></pre>
<p>So now we have a value representing that function. Then we&rsquo;re going to take the value of that function and apply it to the argument&nbsp;<code>2</code>, something like this:</p>
<pre><code>((y)</code> <code>=&gt;</code> <code>x)(2)</code></pre>
<p>So we seem to get a new environment&nbsp;<code>{y: 2,&nbsp;...}</code>. How is the expression&nbsp;<code>x</code>going to be evaluated in that function&rsquo;s environment? There is no&nbsp;<code>x</code>&nbsp;in its environment, it must come from somewhere else.</p>
<p>This, by the way, is one of the great defining characteristics of JavaScript and languages in the same family: Whether they allow things like functions to nest inside each other, and if so, how they handle variables from &ldquo;outside&rdquo; of a function that are referenced inside a function. For example, here&rsquo;s the equivalent code in Ruby:</p>
<pre><code>lambda</code> <code>{</code> <code>|x|</code> <code>lambda</code> <code>{</code> <code>|y|</code> <code>x</code> <code>}</code> <code>}[1][2]</code> <br /><code>#=&gt; 1</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>if functions without free variables are pure, are closures&nbsp;impure?</h4>
<p>The function&nbsp;<code>(y) =&gt; x</code>&nbsp;is interesting. It contains a&nbsp;<em>free variable</em>,&nbsp;<code>x</code>. A free variable is one that is not bound within the function. Up to now, we&rsquo;ve only seen one way to &ldquo;bind&rdquo; a variable, namely by passing in an argument with the same name. Since the function&nbsp;<code>(y) =&gt; x</code>&nbsp;doesn&rsquo;t have an argument named&nbsp;<code>x</code>, the variable&nbsp;<code>x</code>&nbsp;isn&rsquo;t bound in this function, which makes it &ldquo;free.&rdquo;</p>
<p>Now that we know that variables used in a function are either bound or free, we can bifurcate functions into those with free variables and those without:</p>
<ul>
<li>Functions containing no free variables are called&nbsp;<em>pure functions</em>.</li>
<li>Functions containing one or more free variables are called&nbsp;<em>closures</em>.</li>
</ul>
<p>Pure functions are easiest to understand. They always mean the same thing wherever you use them. Here are some pure functions we&rsquo;ve already seen:</p>
<pre><code>()</code> <code>=&gt;</code> <code>{}</code> <br /><code>(x)</code> <code>=&gt;</code> <code>x</code> <br /><code>(x)</code> <code>=&gt;</code> <code>(y)</code> <code>=&gt;</code> <code>x</code></pre>
<p>The first function doesn&rsquo;t have any variables, therefore doesn&rsquo;t have any free variables. The second doesn&rsquo;t have any free variables, because its only variable is bound. The third one is actually two functions, one inside the other.&nbsp;<code>(y) =&gt;&nbsp;...</code>&nbsp;has a free variable, but the entire expression refers to&nbsp;<code>(x) =&gt;&nbsp;...</code>, and it doesn&rsquo;t have a free variable: The only variable anywhere in its body is&nbsp;<code>x</code>, which is certainly bound within&nbsp;<code>(x) =&gt;&nbsp;...</code>.</p>
<p>From this, we learn something: A pure function can contain a closure.</p>
<p>If pure functions can contain closures, can a closure contain a pure function? Using only what we&rsquo;ve learned so far, attempt to compose a closure that contains a pure function. If you can&rsquo;t, give your reasoning for why it&rsquo;s impossible.</p>
<p>Pure functions always mean the same thing because all of their &ldquo;inputs&rdquo; are fully defined by their arguments. Not so with a closure. If I present to you this pure function&nbsp;<code>(x, y) =&gt; x + y</code>, we know exactly what it does with&nbsp;<code>(2, 2)</code>. But what about this closure:&nbsp;<code>(y) =&gt; x + y</code>? We can&rsquo;t say what it will do with argument&nbsp;<code>(2)</code>&nbsp;without understanding the magic for evaluating the free variable&nbsp;<code>x</code>.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>it&rsquo;s always the environment</h4>
<p>To understand how closures are evaluated, we need to revisit environments. As we&rsquo;ve said before, all functions are associated with an environment. We also hand-waved something when describing our environment. Remember that we said the environment for&nbsp;<code>((x) =&gt; (y) =&gt; x)(1)</code>&nbsp;is&nbsp;<code>{x: 1,&nbsp;...}</code>&nbsp;and that the environment for&nbsp;<code>((y) =&gt; x)(2)</code>&nbsp;is&nbsp;<code>{y: 2,&nbsp;...}</code>? Let&rsquo;s fill in the blanks!</p>
<p>The environment for&nbsp;<code>((y) =&gt; x)(2)</code>&nbsp;is&nbsp;<em>actually</em>&nbsp;<code>{y: 2, '..': {x: 1,&nbsp;...}}</code>.&nbsp;<code>'..'</code>&nbsp;means something like &ldquo;parent&rdquo; or &ldquo;enclosure&rdquo; or &ldquo;super-environment.&rdquo; It&rsquo;s&nbsp;<code>(x) =&gt;&nbsp;...</code>&rsquo;s environment, because the function&nbsp;<code>(y) =&gt; x</code>is within&nbsp;<code>(x) =&gt;&nbsp;...</code>&rsquo;s body. So whenever a function is applied to arguments, its environment always has a reference to its parent environment.</p>
<p>And now you can guess how we evaluate&nbsp;<code>((y) =&gt; x)(2)</code>&nbsp;in the environment&nbsp;<code>{y: 2, '..': {x: 1,&nbsp;...}}</code>. The variable&nbsp;<code>x</code>&nbsp;isn&rsquo;t in&nbsp;<code>(y) =&gt;&nbsp;...</code>&rsquo;s immediate environment, but it is in its parent&rsquo;s environment, so it evaluates to&nbsp;<code>1</code>&nbsp;and that&rsquo;s what&nbsp;<code>((y) =&gt; x)(2)</code>&nbsp;returns even though it ended up ignoring its own argument.</p>
<p><code>(x) =&gt; x</code>&nbsp;is called the I Combinator, or the&nbsp;<em>Identity Function</em>.&nbsp;<code>(x) =&gt; (y) =&gt; x</code>&nbsp;is called the K Combinator, or&nbsp;<em>Kestrel</em>. Some people get so excited by this that they write entire books about them, some are&nbsp;<a href="http://www.amzn.com/0192801422?tag=raganwald001-20" target="_blank" rel="nofollow noopener" data-href="http://www.amzn.com/0192801422?tag=raganwald001-20">great</a>, some &mdash; how shall I put this &mdash; are&nbsp;<a title="Kestrels, Quirky Birds, and Hopeless Egocentricity" href="https://leanpub.com/combinators" target="_blank" rel="nofollow noopener" data-href="https://leanpub.com/combinators">interesting</a>&nbsp;if you use Ruby.</p>
<p>Functions can have grandparents too:</p>
<pre><code>(x)</code> <code>=&gt;</code> <code>(y)</code> <code>=&gt;</code> <code>(z)</code> <code>=&gt;</code> <code>x</code> <code>+</code> <code>y</code> <code>+</code> <code>z</code></pre>
<p>This function does much the same thing as:</p>
<pre><code>(x,</code> <code>y,</code> <code>z)</code> <code>=&gt;</code> <code>x</code> <code>+</code> <code>y</code> <code>+</code> <code>z</code></pre>
<p>Only you call it with&nbsp;<code>(1)(2)(3)</code>&nbsp;instead of&nbsp;<code>(1, 2, 3)</code>. The other big difference is that you can call it with&nbsp;<code>(1)</code>&nbsp;and get a function back that you can later call with&nbsp;<code>(2)(3)</code>.</p>
<p>The first function is the result of&nbsp;<a href="https://en.wikipedia.org/wiki/Currying" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Currying">currying</a>&nbsp;the second function. Calling a curried function with only some of its arguments is sometimes called&nbsp;<a href="https://en.wikipedia.org/wiki/Partial_application" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Partial_application">partial application</a>. Some programming languages automatically curry and partially evaluate functions without the need to manually nest them.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>shadowy variables from a shadowy&nbsp;planet</h4>
<p>An interesting thing happens when a variable has the same name as an ancestor environment&rsquo;s variable. Consider:</p>
<pre><code>(x)</code> <code>=&gt;</code> <code>(x,</code> <code>y)</code> <code>=&gt;</code> <code>x</code> <code>+</code> <code>y</code></pre>
<p>The function&nbsp;<code>(x, y) =&gt; x + y</code>&nbsp;is a pure function, because its&nbsp;<code>x</code>&nbsp;is defined within its own environment. Although its parent also defines an&nbsp;<code>x</code>, it is ignored when evaluating&nbsp;<code>x + y</code>. JavaScript always searches for a binding starting with the functions own environment and then each parent in turn until it finds one. The same is true of:</p>
<pre><code>(x)</code> <code>=&gt;</code> <br /> <code>(x,</code> <code>y)</code> <code>=&gt;</code> <br /> <code>(w,</code> <code>z)</code> <code>=&gt;</code> <br /> <code>(w)</code> <code>=&gt;</code> <br /> <code>x</code> <code>+</code> <code>y</code> <code>+</code> <code>z</code></pre>
<p>When evaluating&nbsp;<code>x + y + z</code>, JavaScript will find&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>&nbsp;in the great-grandparent scope and&nbsp;<code>z</code>&nbsp;in the parent scope. The&nbsp;<code>x</code>&nbsp;in the great-great-grandparent scope is ignored, as are both&nbsp;<code>w</code>s. When a variable has the same name as an ancestor environment&rsquo;s binding, it is said to&nbsp;<em>shadow</em>&nbsp;the ancestor.</p>
<p>This is often a good thing.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>which came first, the chicken or the&nbsp;egg?</h4>
<p>This behaviour of pure functions and closures has many, many consequences that can be exploited to write software. We are going to explore them in some detail as well as look at some of the other mechanisms JavaScript provides for working with variables and mutable state.</p>
<p>But before we do so, there&rsquo;s one final question: Where does the ancestry start? If there&rsquo;s no other code in a file, what is&nbsp;<code>(x) =&gt; x</code>&rsquo;s parent environment?</p>
<p>JavaScript always has the notion of at least one environment we do not control: A global environment in which many useful things are bound such as libraries full of standard functions. So when you invoke&nbsp;<code>((x) =&gt; x)(1)</code>in the REPL, its full environment is going to look like this:&nbsp;<code>{x: 1, '..':&nbsp;</code><em>global environment</em><code>}</code>.</p>
<p>Sometimes, programmers wish to avoid this. If you don&rsquo;t want your code to operate directly within the global environment, what can you do? Create an environment for them, of course. Many programmers choose to write every JavaScript file like this:</p>
<pre><code>// top of the file</code> </pre>
<pre><code>(()</code> <code>=&gt;</code> <code>{</code> <br /> <code>// ... lots of JavaScript ...</code> <br /><code>})();</code> </pre>
<pre><code>// bottom of the file</code></pre>
<p>The effect is to insert a new, empty environment in between the global environment and your own functions:&nbsp;<code>{x: 1, '..': {'..':&nbsp;</code><em>global environment</em><code>}}</code>. his helps to prevent programmers from accidentally changing the global state that is shared by all code in the program.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>That Constant Coffee&nbsp;Craving</h3>
<p>Up to now, all we&rsquo;ve really seen are&nbsp;<em>anonymous functions</em>, functions that don&rsquo;t have a name. This feels very different from programming in most other languages, where the focus is on naming functions, methods, and procedures. Naming things is a critical part of programming, but all we&rsquo;ve seen so far is how to name arguments.</p>
<p>There are other ways to name things in JavaScript, but before we learn some of those, let&rsquo;s see how to use what we already have to name things. Let&rsquo;s revisit a very simple example:</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>3.14159265</code></pre>
<p>What is this &ldquo;3.14159265&rdquo; number?&nbsp;<a href="https://en.wikipedia.org/wiki/Pi" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Pi">PI</a>, obviously. We&rsquo;d like to name it so that we can write something like:</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code></pre>
<p>In order to bind&nbsp;<code>3.14159265</code>&nbsp;to the name&nbsp;<code>PI</code>, we&rsquo;ll need a function with a parameter of&nbsp;<code>PI</code>&nbsp;applied to an argument of&nbsp;<code>3.14159265</code>. If we put our function expression in parentheses, we can apply it to the argument of&nbsp;<code>3.14159265</code>:</p>
<pre><code>((PI)</code> <code>=&gt;</code> <br /><code>// ????</code> <br /><code>)(3.14159265)</code></pre>
<p>What do we put inside our new function that binds&nbsp;<code>3.14159265</code>&nbsp;to the name&nbsp;<code>PI</code>&nbsp;when evaluated? Our circumference function, of course:</p>
<pre><code>((PI)</code> <code>=&gt;</code> <br /> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code> <br /><code>)(3.14159265)</code></pre>
<p>This expression, when evaluated, returns a function that calculates circumferences. That sounds bad, but when we think about it,&nbsp;<code>(diameter) =&gt; diameter * 3.14159265</code>&nbsp;is also an expression, that when evaluated, returns a function that calculates circumferences. All of our &ldquo;functions&rdquo; are expressions. This one has a few more moving parts, that&rsquo;s all. But we can use it just like&nbsp;<code>(diameter) =&gt; diameter * 3.14159265</code>.</p>
<p>Let&rsquo;s test it:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>3.14159265)(2)</code> <br /><code>//=&gt; 6.2831853</code> </pre>
<pre><code>((PI)</code> <code>=&gt;</code> <br /> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code> <br /><code>)(3.14159265)(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>That works! We can bind anything we want in an expression by wrapping it in a function that is immediately invoked with the value we want to bind.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>inside-out</h4>
<p>There&rsquo;s another way we can make a function that binds&nbsp;<code>3.14159265</code>&nbsp;to the name&nbsp;<code>PI</code>&nbsp;and then uses that in its expression. We can turn things inside-out by putting the binding inside our diameter calculating function, like this:</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <br /> <code>((PI)</code> <code>=&gt;</code> <br /> <code>diameter</code> <code>*</code> <code>PI)(3.14159265)</code></pre>
<p>It produces the same result as our previous expressions for a diameter-calculating function:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>3.14159265)(2)</code> <br /><code>//=&gt; 6.2831853</code> </pre>
<pre><code>((PI)</code> <code>=&gt;</code> <br /> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code> <br /><code>)(3.14159265)(2)</code> <br /><code>//=&gt; 6.2831853</code> </pre>
<pre><code>((diameter)</code> <code>=&gt;</code> <br /> <code>((PI)</code> <code>=&gt;</code> <br /> <code>diameter</code> <code>*</code> <code>PI)(3.14159265))(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>Which one is better? Well, the first one seems simplest, but a half-century of experience has taught us that names matter. A &ldquo;magic literal&rdquo; like&nbsp;<code>3.14159265</code>is anathema to sustainable software development.</p>
<p>The third one is easiest for most people to read. It separates concerns nicely: The &ldquo;outer&rdquo; function describes its parameters:</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <code>// ...</code></pre>
<p>Everything else is encapsulated in its body. That&rsquo;s how it should be, naming&nbsp;<code>PI</code>&nbsp;is its concern, not ours. The other formulation:</p>
<pre><code>((PI)</code> <code>=&gt;</code> <code>// ...</code> <code>)(3.14159265)</code></pre>
<p>&ldquo;Exposes&rdquo; naming&nbsp;<code>PI</code>&nbsp;first, and we have to look inside to find out why we care. So, should we always write this?</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <br /> <code>((PI)</code> <code>=&gt;</code> <br /> <code>diameter</code> <code>*</code> <code>PI)(3.14159265)</code></pre>
<p>Well, the wrinkle with this is that typically, invoking functions is considerably more expensive than evaluating expressions. Every time we invoke the outer function, we&rsquo;ll invoke the inner function. We could get around this by writing</p>
<pre><code>((PI)</code> <code>=&gt;</code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code> <code>)(3.14159265)</code></pre>
<p>But then we&rsquo;ve obfuscated our code, and we don&rsquo;t want to do that unless we absolutely have to.</p>
<p>What would be very nice is if the language gave us a way to bind names inside of blocks without incurring the cost of a function invocation. And JavaScript does.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>const</h4>
<p>Another way to write our &ldquo;circumference&rdquo; function would be to pass&nbsp;<code>PI</code>&nbsp;along with the diameter argument, something like this:</p>
<pre><code>(diameter,</code> <code>PI)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code></pre>
<p>And we could use it like this:</p>
<pre><code>((diameter,</code> <code>PI)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI)(2,</code> <code>3.14159265)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>This differs from our example above in that there is only one environment, rather than two. We have one binding in the environment representing our regular argument, and another our &ldquo;constant.&rdquo; That&rsquo;s more efficient, and it&rsquo;s&nbsp;<em>almost</em>&nbsp;what we wanted all along: A way to bind&nbsp;<code>3.14159265</code>&nbsp;to a readable name.</p>
<p>JavaScript gives us a way to do that, the&nbsp;<code>const</code>&nbsp;keyword. We&rsquo;ll learn a lot more about&nbsp;<code>const</code>&nbsp;in future sections, but here&rsquo;s the most important thing we can do with&nbsp;<code>const</code>:</p>
<pre><code>(diameter)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;</code> </pre>
<pre><code> return</code> <code>diameter</code> <code>*</code> <code>PI</code> <br /><code>}</code></pre>
<p>The&nbsp;<code>const</code>&nbsp;keyword introduces one or more bindings in the block that encloses it. It doesn&rsquo;t incur the cost of a function invocation. That&rsquo;s great. Even better, it puts the symbol (like&nbsp;<code>PI</code>) close to the value (<code>3.14159265</code>). That&rsquo;s much better than what we were writing.</p>
<p>We use the&nbsp;<code>const</code>&nbsp;keyword in a&nbsp;<em>const statement</em>.&nbsp;<code>const</code>&nbsp;statements occur inside blocks, we can&rsquo;t use them when we write a fat arrow that has an expression as its body.</p>
<p>It works just as we want. Instead of:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <br /> <code>((PI)</code> <code>=&gt;</code> <br /> <code>diameter</code> <code>*</code> <code>PI)(3.14159265))(2)</code></pre>
<p>Or:</p>
<pre><code>((diameter,</code> <code>PI)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI)(2,</code> <code>3.14159265)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>We write:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;</code> <br /> <br /> <code>return</code> <code>diameter</code> <code>*</code> <code>PI</code> <br /><code>})(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>We can bind any expression. Functions are expressions, so we can bind helper functions:</p>
<pre><code>(d)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>calc</code> <code>=</code> <code>(diameter)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;</code> </pre>
<pre><code> return</code> <code>diameter</code> <code>*</code> <code>PI</code> <br /> <code>};<br /></code> <br /> <code>return</code> <code>"The circumference is "</code> <code>+</code> <code>calc(d)</code> <br /><code>}</code></pre>
<p>Notice&nbsp;<code>calc(d)</code>? This underscores what we&rsquo;ve said: if we have an expression that evaluates to a function, we apply it with&nbsp;<code>()</code>. A name that&rsquo;s bound to a function is a valid expression evaluating to a function.</p>
<p>Amazing how such an important idea&ndash;naming functions&ndash;can be explained&nbsp;<em>en passant</em>&nbsp;in just a few words. That emphasizes one of the things JavaScript gets really, really right: Functions as &ldquo;first class entities.&rdquo; Functions are values that can be bound to names like any other value, passed as arguments, returned from other functions, and so forth.</p>
<p>We can bind more than one name-value pair by separating them with commas. For readability, most people put one binding per line:</p>
<pre><code>(d)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265,</code> <br /> <code>calc</code> <code>=</code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI;</code> </pre>
<pre><code> return</code> <code>"The circumference is "</code> <code>+</code> <code>calc(d)</code> <br /><code>}</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>nested blocks</h4>
<p>Up to now, we&rsquo;ve only ever seen blocks we use as the body of functions. But there are other kinds of blocks. One of the places you can find blocks is in an&nbsp;<code>if</code>&nbsp;statement. In JavaScript, an&nbsp;<code>if</code>&nbsp;statement looks like this:</p>
<pre><code>(n)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>even</code> <code>=</code> <code>(x)</code> <code>=&gt;</code> <code>{</code> <br /> <code>if</code> <code>(x</code> <code>===</code> <code>0)</code> <br /> <code>return</code> <code>true;</code> <br /> <code>else</code> <br /> <code>return</code> <code>!even(x</code> <code>-</code> <code>1);</code> <br /> <code>}</code> <br /> <code>return</code> <code>even(n)</code> <br /><code>}</code></pre>
<p>And it works for fairly small numbers:</p>
<pre><code>((n)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>even</code> <code>=</code> <code>(x)</code> <code>=&gt;</code> <code>{</code> <br /> <code>if</code> <code>(x</code> <code>===</code> <code>0)<br /></code> <code>return</code> <code>true;<br /></code> <code>else<br /></code> <code>return</code> <code>!even(x</code> <code>-</code> <code>1);<br /></code> <code>}<br /></code> <code>return</code> <code>even(n)</code> <br /><code>})(13)</code> <code>//=&gt; false</code></pre>
<p>The&nbsp;<code>if</code>&nbsp;statement is a statement, not an expression (an unfortunate design choice), and its clauses are statements or blocks. So we could also write something like:</p>
<pre><code>(n)</code> <code>=&gt;</code> <code>{</code> <br /> <code>const</code> <code>even</code> <code>=</code> <code>(x)</code> <code>=&gt;</code> <code>{</code> <br /> <code>if</code> <code>(x</code> <code>===</code> <code>0)</code> <br /> <code>return</code> <code>true;</code> <br /> <code>else</code> <code>{</code> <br /> <code>const</code> <code>odd</code> <code>=</code> <code>(y)</code> <code>=&gt;</code> <code>!even(y);<br /></code> <code>return</code> <code>odd(x</code> <code>-</code> <code>1);</code> <br /> <code>}</code> <br /> <code>}<br /></code> <code>return</code> <code>even(n)</code> <br /><code>}</code></pre>
<p>And this also works:</p>
<pre><code>((n)</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>even</code> <code>=</code> <code>(x)</code> <code>=&gt;</code> <code>{<br /></code> <code>if</code> <code>(x</code> <code>===</code> <code>0)<br /></code> <code>return</code> <code>true;<br /></code> <code>else</code> <code>{<br /></code> <code>const</code> <code>odd</code> <code>=</code> <code>(y)</code> <code>=&gt;</code> <code>!even(y);<br /></code> <code>return</code> <code>odd(x</code> <code>-</code> <code>1);<br /></code> <code>}<br /></code> <code>}<br /></code> <code>return</code> <code>even(n)<br /></code> <code>})(42)</code> <code>//=&gt; true</code></pre>
<p>We&rsquo;ve used a block as the&nbsp;<code>else</code>&nbsp;clause, and since it&rsquo;s a block, we&rsquo;ve placed a&nbsp;<code>const</code>&nbsp;statement inside it.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>const and lexical&nbsp;scope</h4>
<p>This seems very straightforward, but alas, there are some semantics of binding names that we need to understand if we&rsquo;re to place&nbsp;<code>const</code>&nbsp;anywhere we like. The first thing to ask ourselves is, what happens if we use&nbsp;<code>const</code>to bind two different values to the &ldquo;same&rdquo; name?</p>
<p>Let&rsquo;s back up and reconsider how closures work. What happens if we use parameters to bind two different values to the same name?</p>
<p>Here&rsquo;s the second formulation of our diameter function, bound to a name using an IIFE:</p>
<pre><code>((diameter_fn)</code> <code>=&gt;<br /></code> <code>// ...<br />)(<br /></code> <code>((PI)</code> <code>=&gt;<br /></code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI<br /></code> <code>)(3.14159265)</code> <code>)</code></pre>
<p>It&rsquo;s more than a bit convoluted, but it binds&nbsp;<code>((PI) =&gt; (diameter) =&gt; diameter * PI)(3.14159265)</code>&nbsp;to&nbsp;<code>diameter_fn</code>&nbsp;and evaluates the expression that we&rsquo;ve elided. We can use any expression in there, and that expression can invoke&nbsp;<code>diameter_fn</code>. For example:</p>
<pre><code>((diameter_fn)</code> <code>=&gt;<br /></code> <code>diameter_fn(2)</code> <code>)(<br /></code> <code>((PI)</code> <code>=&gt;<br /></code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI<br /></code> <code>)(3.14159265)<br />)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>We know this from the section on closures, but even though&nbsp;<code>PI</code>&nbsp;is not bound when we invoke&nbsp;<code>diameter_fn</code>&nbsp;by evaluating&nbsp;<code>diameter_fn(2)</code>,&nbsp;<code>PI</code>&nbsp;<em>is</em>&nbsp;bound when we evaluated&nbsp;<code>(diameter) =&gt; diameter * PI</code>, and thus the expression&nbsp;<code>diameter * PI</code>&nbsp;is able to access values for&nbsp;<code>PI</code>&nbsp;and&nbsp;<code>diameter</code>&nbsp;when we evaluate&nbsp;<code>diameter_fn</code>.</p>
<p>This is called&nbsp;<a href="https://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scope_vs._dynamic_scope" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scope_vs._dynamic_scope">lexical scoping</a>, because we can discover where a name is bound by looking at the source code for the program. We can see that&nbsp;<code>PI</code>&nbsp;is bound in an environment surrounding&nbsp;<code>(diameter) =&gt; diameter * PI</code>, we don&rsquo;t need to know where&nbsp;<code>diameter_fn</code>&nbsp;is invoked.</p>
<p>We can test this by deliberately creating a &ldquo;conflict:&rdquo;</p>
<pre><code>((diameter_fn)</code> <code>=&gt;<br /></code> <code>((PI)</code> <code>=&gt;<br /></code> <code>diameter_fn(2)<br /></code> <code>)(3)<br /></code> <code>)(<br /></code> <code>((PI)</code> <code>=&gt;<br /></code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI<br /></code> <code>)(3.14159265)<br />)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>Although we have bound&nbsp;<code>3</code>&nbsp;to&nbsp;<code>PI</code>&nbsp;in the environment surrounding&nbsp;<code>diameter_fn(2)</code>, the value that counts is&nbsp;<code>3.14159265</code>, the value we bound to&nbsp;<code>PI</code>&nbsp;in the environment surrounding (diameter) &rArr; diameter * PI.</p>
<p>That much we can carefully work out from the way closures work. Does&nbsp;<code>const</code>&nbsp;work the same way? Let&rsquo;s find out:</p>
<pre><code>((diameter_fn)</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3;<br /></code> <code>return</code> <code>diameter_fn(2)<br />})(<br /></code> <code>(()</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;<br /></code> <code>return</code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI<br /></code> <code>})()<br />)<br />//=&gt; 6.2831853</code></pre>
<p>Yes. Binding values to names with&nbsp;<code>const</code>&nbsp;works just like binding values to names with parameter invocations, it uses lexical scope.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>are consts also from a shadowy&nbsp;planet?</h4>
<p>We just saw that values bound with&nbsp;<code>const</code>&nbsp;use lexical scope, just like values bound with parameters. They are looked up in the environment where they are declared. And we know that functions create environments. Parameters are declared when we create functions, so it makes sense that parameters are bound to environments created when we invoke functions.</p>
<p>But&nbsp;<code>const</code>&nbsp;statements can appear inside blocks, and we saw that blocks can appear inside of other blocks, including function bodies. So where are&nbsp;<code>const</code>variables bound? In the function environment? Or in an environment corresponding to the block?</p>
<p>We can test this by creating another conflict. But instead of binding two different variables to the same name in two different places, we&rsquo;ll bind two different values to the same name, but one environment will be completely enclosed by the other.</p>
<p>Let&rsquo;s start, as above, by doing this with parameters. We&rsquo;ll start with:</p>
<pre><code>((PI)</code> <code>=&gt;<br /></code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI</code> <code>)(3.14159265)</code></pre>
<p>And gratuitously wrap it in another IIFE so that we can bind&nbsp;<code>PI</code>&nbsp;to something else:</p>
<pre><code>((PI)</code> <code>=&gt;<br /></code> <code>((PI)</code> <code>=&gt;<br /></code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI<br /></code> <code>)(3.14159265)<br /></code> <code>)(3)</code></pre>
<p>This still evaluates to a function that calculates diameters:</p>
<pre><code>((PI)</code> <code>=&gt;<br /></code> <code>((PI)</code> <code>=&gt;<br /></code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI<br /></code> <code>)(3.14159265)<br /></code> <code>)(3)(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>And we can see that our&nbsp;<code>diameter * PI</code>&nbsp;expression uses the binding for&nbsp;<code>PI</code>&nbsp;in the closest parent environment. but one question: Did binding&nbsp;<code>3.14159265</code>&nbsp;to&nbsp;<code>PI</code>&nbsp;somehow change the binding in the &ldquo;outer&rdquo; environment? Let&rsquo;s rewrite things slightly differently:</p>
<pre><code>((PI)</code> <code>=&gt;</code> <code>{<br /></code> <code>((PI)</code> <code>=&gt;</code> <code>{})(3);<br /></code> <code>return</code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI;<br /></code> <code>})(3.14159265)</code></pre>
<p>Now we bind&nbsp;<code>3</code>&nbsp;to&nbsp;<code>PI</code>&nbsp;in an otherwise empty IIFE inside of our IIFE that binds&nbsp;<code>3.14159265</code>&nbsp;to&nbsp;<code>PI</code>. Does that binding &ldquo;overwrite&rdquo; the outer one? Will our function return&nbsp;<code>6</code>&nbsp;or&nbsp;<code>6.2831853</code>? This is a book, you&rsquo;ve already scanned ahead, so you know that the answer is&nbsp;<strong>no</strong>, the inner binding does not overwrite the outer binding:</p>
<pre><code>((PI)</code> <code>=&gt;</code> <code>{<br /></code> <code>((PI)</code> <code>=&gt;</code> <code>{})(3);<br /></code> <code>return</code> <code>(diameter)</code> <code>=&gt;</code> <code>diameter</code> <code>*</code> <code>PI;<br /></code> <code>})(3.14159265)(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>We say that when we bind a variable using a parameter inside another binding, the inner binding&nbsp;<em>shadows</em>&nbsp;the outer binding. It has effect inside its own scope, but does not affect the binding in the enclosing scope.</p>
<p>So what about&nbsp;<code>const</code>. Does it work the same way?</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;<br /></code> <br /> <code>(()</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3;<br /></code> <code>})();<br /></code> <br /> <code>return</code> <code>diameter</code> <code>*</code> <code>PI;<br /></code> <code>})(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>Yes, names bound with&nbsp;<code>const</code>&nbsp;shadow enclosing bindings just like parameters. But wait! There&rsquo;s more!!!</p>
<p>Parameters are only bound when we invoke a function. That&rsquo;s why we made all these IIFEs. But&nbsp;<code>const</code>&nbsp;statements can appear inside blocks. What happens when we use a&nbsp;<code>const</code>&nbsp;inside of a block?</p>
<p>We&rsquo;ll need a gratuitous block. We&rsquo;ve seen&nbsp;<code>if</code>&nbsp;statements, what could be more gratuitous than:</p>
<pre><code>if</code> <code>(true)</code> <code>{</code> <code>// an immediately invoked block statement (IIBS)</code> <code>}</code></pre>
<p>Let&rsquo;s try it:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3;</code></pre>
<pre> <code>if</code> <code>(true)</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;</code> <br /> <code>return</code> <code>diameter</code> <code>*</code> <code>PI;<br /></code> <code>}<br /></code> <code>})(2)<br />//=&gt; 6.2831853</code> </pre>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;<br /></code> <br /> <code>if</code> <code>(true)</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3;<br /></code> <code>}<br /></code> <code>return</code> <code>diameter</code> <code>*</code> <code>PI;<br /></code> <code>})(2)</code> <br /><code>//=&gt; 6.2831853</code></pre>
<p>Ah!&nbsp;<code>const</code>&nbsp;statements don&rsquo;t just shadow values bound within the environments created by functions, they shadow values bound within environments created by blocks!</p>
<p>This is enormously important. Consider the alternative: What if&nbsp;<code>const</code>&nbsp;could be declared inside of a block, but it always bound the name in the function&rsquo;s scope. In that case, we&rsquo;d see things like this:</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;<br /></code> <code>if</code> <code>(true)</code> <code>{<br /> </code> <code>const</code> <code>PI</code> <code>=</code> <code>3;<br /> </code> <code>}<br /></code> <code>return</code> <code>diameter</code> <code>*</code> <code>PI;</code> <code>})(2)</code> </pre>
<pre><code>//=&gt; would return 6 if const had function scope</code></pre>
<p>If&nbsp;<code>const</code>&nbsp;always bound its value to the name defined in the function&rsquo;s environment, placing a&nbsp;<code>const</code>&nbsp;statement inside of a block would merely rebind the existing name, overwriting its old contents. That would be super-confusing. And this code would &ldquo;work:&rdquo;</p>
<pre><code>((diameter)</code> <code>=&gt;</code> <code>{<br /></code> <code>if</code> <code>(true)</code> <code>{<br /></code> <code>const</code> <code>PI</code> <code>=</code> <code>3.14159265;<br /></code> <code>}<br /></code> <code>return</code> <code>diameter</code> <code>*</code> <code>PI;<br /></code> <code>})(2)</code> <br /><code>//=&gt; would return 6.2831853 if const had function scope</code></pre>
<p>Again, confusing. Typically, we want to bind our names as close to where we need them as possible. This design rule is called the&nbsp;<a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">Principle of Least Privilege</a>, and it has both quality and security implications. Being able to bind a name inside of a block means that if the name is only needed in the block, we are not &ldquo;leaking&rdquo; its binding to other parts of the code that do not need to interact with it.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>rebinding</h4>
<p>By default, JavaScript permits us to&nbsp;<em>rebind</em>&nbsp;new values to names bound with a parameter. For example, we can write:</p>
<pre><code>const</code> <code>evenStevens</code> <code>=</code> <code>(n)</code> <code>=&gt;</code> <code>{<br /></code> <code>if</code> <code>(n</code> <code>===</code> <code>0)</code> <code>{<br /></code> <code>return</code> <code>true;<br /></code> <code>}<br /></code> <code>else</code> <code>if</code> <code>(n</code> <code>==</code> <code>1)</code> <code>{<br /></code> <code>return</code> <code>false;<br /></code> <code>}<br /></code> <code>else</code> <code>{<br /></code> <code>n</code> <code>=</code> <code>n</code> <code>-</code> <code>2;<br /></code> <code>return</code> <code>evenStevens(n);<br /></code> <code>}<br /></code> <code>}</code></pre>
<pre> <code>evenStevens(42)</code> <code>//=&gt; true</code></pre>
<p>The line&nbsp;<code>n = n - 2;</code>&nbsp;<em>rebinds</em>&nbsp;a new value to the name&nbsp;<code>n</code>. Let&rsquo;s try a similar thing with a name bound using&nbsp;<code>const</code>. We&rsquo;ve already bound&nbsp;<code>evenStevens</code>using&nbsp;<code>const</code>, let&rsquo;s try rebinding it:</p>
<pre><code>evenStevens</code> <code>=</code> <code>(n)</code> <code>=&gt;</code> <code>{<br /></code> <code>if</code> <code>(n</code> <code>===</code> <code>0)</code> <code>{<br /></code> <code>return</code> <code>true;<br /></code> <code>}<br /></code> <code>else</code> <code>if</code> <code>(n</code> <code>==</code> <code>1)</code> <code>{<br /></code> <code>return</code> <code>false;<br /></code> <code>}<br /></code> <code>else</code> <code>{<br /></code> <code>return</code> <code>evenStevens(n</code> <code>-</code> <code>2);<br /></code> <code>}<br />}</code> <br /><code>//=&gt; ERROR, evenStevens is read-only</code></pre>
<p>JavaScript does not permit us to rebind a name that has been bound with&nbsp;<code>const</code>. We can&nbsp;<em>shadow</em>&nbsp;it by using&nbsp;<code>const</code>&nbsp;to declare a new binding with a new function or block scope, but we cannot rebind a name that was bound with&nbsp;<code>const</code>&nbsp;in an existing scope.</p>
<p>This is valuable, as it greatly simplifies the analysis of programs to see at a glance that when something is bound with&nbsp;<code>const</code>, we need never worry that its value may change.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Naming Functions</h3>
<p>Let&rsquo;s get right to it. This code does&nbsp;<em>not</em>&nbsp;name a function:</p>
<pre><code>const</code> <code>repeat</code> <code>=</code> <code>(str)</code> <code>=&gt;</code> <code>str</code> <code>+</code> <code>str</code></pre>
<p>It doesn&rsquo;t name the function &ldquo;repeat&rdquo; for the same reason that&nbsp;<code>const answer = 42</code>&nbsp;doesn&rsquo;t name the number&nbsp;<code>42</code>. This syntax binds an anonymous function to a name in an environment, but the function itself remains anonymous.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>the&nbsp;<code>function</code>&nbsp;keyword</h4>
<p>JavaScript&nbsp;<em>does</em>&nbsp;have a syntax for naming a function, we use the&nbsp;<code>function</code>keyword. Until ECMAScript 2015 was created,&nbsp;<code>function</code>&nbsp;was the usual syntax for writing functions.</p>
<p>Here&rsquo;s our&nbsp;<code>repeat</code>&nbsp;function written using a &ldquo;fat arrow&rdquo;</p>
<pre><code>(str)</code> <code>=&gt;</code> <code>str</code> <code>+</code> <code>str</code></pre>
<p>And here&rsquo;s (almost) the exact same function written using the&nbsp;<code>function</code>keyword:</p>
<pre><code>function</code> <code>(str)</code> <code>{</code> <code>return</code> <code>str</code> <code>+</code> <code>str</code> <code>}</code></pre>
<p>Let&rsquo;s look at the obvious differences:</p>
<ol>
<li>We introduce a function with the&nbsp;<code>function</code>&nbsp;keyword.</li>
<li>Something else we&rsquo;re about to discuss is optional.</li>
<li>We have arguments in parentheses, just like fat arrow functions.</li>
<li>We do not have a fat arrow, we go directly to the body.</li>
<li>We always use a block, we cannot write&nbsp;<code>function (str) str + str</code>. This means that if we want our functions to return a value, we always need to use the&nbsp;<code>return</code>&nbsp;keyword</li>
</ol>
<p>If we leave out the &ldquo;something optional&rdquo; that comes after the&nbsp;<code>function</code>keyword, we can translate all of the fat arrow functions that we&rsquo;ve seen into&nbsp;<code>function</code>&nbsp;keyword functions, e.g.</p>
<pre><code>(n)</code> <code>=&gt;</code> <code>(1.618**n</code> <code>-</code> <code>-1.618**-n)</code> <code>/</code> <code>2.236</code></pre>
<p>Can be written as:</p>
<pre><code>function</code> <code>(n)</code> <code>{</code> <code>return</code> <code>(1.618**n</code> <code>-</code> <code>-1.618**-n)</code> <code>/</code> <code>2.236;</code> <code>}</code></pre>
<p>This still does not&nbsp;<em>name</em>&nbsp;a function, but as we noted above, functions written with the&nbsp;<code>function</code>&nbsp;keyword have an optional &ldquo;something else.&rdquo; Could that &ldquo;something else&rdquo; name a function? Yes, of course.</p>
<p>Here are our example functions written with names:</p>
<pre><code>const</code> <code>repeat</code> <code>=</code> <code>function</code> <code>repeat</code> <code>(str)</code> <code>{<br /></code> <code>return</code> <code>str</code> <code>+</code> <code>str;<br />};</code> </pre>
<pre><code>const</code> <code>fib</code> <code>=</code> <code>function</code> <code>fib</code> <code>(n)</code> <code>{<br /></code> <code>return</code> <code>(1.618**n</code> <code>-</code> <code>-1.618**-n)</code> <code>/</code> <code>2.236;</code> <br /><code>};</code></pre>
<p>Placing a name between the&nbsp;<code>function</code>&nbsp;keyword and the argument list names the function. Confusingly, the name of the function is not exactly the same thing as the name we may choose to bind to the value of the function. For example, we can write:</p>
<pre><code>const</code> <code>double</code> <code>=</code> <code>function</code> <code>repeat</code> <code>(str)</code> <code>{</code> <br /> <code>return</code> <code>str</code> <code>+</code> <code>str;</code> <br /><code>}</code></pre>
<p>In this expression,&nbsp;<code>double</code>&nbsp;is the name in the environment, but&nbsp;<code>repeat</code>&nbsp;is the function&rsquo;s actual name. This is a&nbsp;<em>named function expression</em>. That may seem confusing, but think of the binding names as properties of the environment, not of the function. While the name of the function is a property of the function, not of the environment.</p>
<p>And indeed the name&nbsp;<em>is</em>&nbsp;a property:</p>
<pre><code>double.name</code> <code>//=&gt; 'repeat'</code></pre>
<p>In this book we are not examining JavaScript&rsquo;s tooling such as debuggers baked into browsers, but we will note that when you are navigating call stacks in all modern tools, the function&rsquo;s binding name is ignored but its actual name is displayed, so naming functions is very useful even if they don&rsquo;t get a formal binding, e.g.</p>
<pre><code>someBackboneView.on('click',</code> <code>function</code> <code>clickHandler</code> <code>()</code> <code>{</code> <code>//...</code> <code>});</code></pre>
<p>Now, the function&rsquo;s actual name has no effect on the environment in which it is used. To whit:</p>
<pre><code>const</code> <code>bindingName</code> <code>=</code> <code>function</code> <code>actualName</code> <code>()</code> <code>{</code> <code>//...</code> <code>};</code> <br /><code>bindingName</code> <br /><code>//=&gt; [Function: actualName]</code> </pre>
<pre><code>actualName</code> <br /><code>//=&gt; ReferenceError: actualName is not defined</code></pre>
<p>So &ldquo;actualName&rdquo; isn&rsquo;t bound in the environment where we use the named function expression. Is it bound anywhere else? Yes it is. Here&rsquo;s a function that determines whether a positive integer is even or not. We&rsquo;ll use it in an IIFE so that we don&rsquo;t have to bind it to a name with&nbsp;<code>const</code>:</p>
<pre><code>(function</code> <code>even</code> <code>(n)</code> <code>{<br /></code> <code>if</code> <code>(n</code> <code>===</code> <code>0)</code> <code>{<br /></code> <code>return</code> <code>true<br /></code> <code>}<br /></code> <code>else</code> <code>return</code> <code>!even(n</code> <code>-</code> <code>1)<br />})(5)</code> <br /><code>//=&gt; false</code> </pre>
<pre><code>(function</code> <code>even</code> <code>(n)</code> <code>{<br /></code> <code>if</code> <code>(n</code> <code>===</code> <code>0)</code> <code>{<br /></code> <code>return</code> <code>true<br /></code> <code>}<br /></code> <code>else</code> <code>return</code> <code>!even(n</code> <code>-</code> <code>1)</code> <br /><code>})(2)</code> <br /><code>//=&gt; true</code></pre>
<p>Clearly, the name&nbsp;<code>even</code>&nbsp;is bound to the function&nbsp;<em>within the function&rsquo;s body</em>. Is it bound to the function outside of the function&rsquo;s body?</p>
<pre><code>even</code> <code>//=&gt; Can't find variable: even</code></pre>
<p><code>even</code>&nbsp;is bound within the function itself, but not outside it. This is useful for making recursive functions as we see above, and it speaks to the principle of least privilege: If you don&rsquo;t&nbsp;<em>need</em>&nbsp;to name it anywhere else, you needn&rsquo;t.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>function declarations</h4>
<p>There is another syntax for naming and/or defining a function. It&rsquo;s called a&nbsp;<em>function declaration statement</em>, and it looks a lot like a named function expression, only we use it as a statement:</p>
<pre><code>function</code> <code>someName</code> <code>()</code> <code>{</code> <code>// ...</code> <code>}</code></pre>
<p>This behaves a&nbsp;<em>little</em>&nbsp;like:</p>
<pre><code>const</code> <code>someName</code> <code>=</code> <code>function</code> <code>someName</code> <code>()</code> <code>{</code> <code>// ...</code> <code>}</code></pre>
<p>In that it binds a name in the environment to a named function. However, there are two important differences. First, function declarations are&nbsp;<em>hoisted</em>&nbsp;to the top of the function in which they occur.</p>
<p>Consider this example where we try to use the variable&nbsp;<code>fizzbuzz</code>&nbsp;as a function before we bind a function to it with&nbsp;<code>const</code>:</p>
<pre><code>(function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>fizzbuzz();<br /></code> <br /> <code>const</code> <code>fizzbuzz</code> <code>=</code> <code>function</code> <code>fizzbuzz</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>"Fizz"</code> <code>+</code> <code>"Buzz";<br /></code> <code>}</code> <br /><code>})()</code> </pre>
<pre><code>//=&gt; undefined is not a function (evaluating 'fizzbuzz()')</code></pre>
<p>We haven&rsquo;t actually bound a function to the name&nbsp;<code>fizzbuzz</code>&nbsp;before we try to use it, so we get an error. But a function&nbsp;<em>declaration</em>&nbsp;works differently:</p>
<pre><code>(function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>fizzbuzz();<br /></code> <br /> <code>function</code> <code>fizzbuzz</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>"Fizz"</code> <code>+</code> <code>"Buzz";<br /></code> <code>}</code> </pre>
<pre><code>})()</code> <br /><code>//=&gt; 'FizzBuzz'</code></pre>
<p>Although&nbsp;<code>fizzbuzz</code>&nbsp;is declared later in the function, JavaScript behaves as if we&rsquo;d written:</p>
<pre><code>(function</code> <code>()</code> <code>{<br /></code> <code>const</code> <code>fizzbuzz</code> <code>=</code> <code>function</code> <code>fizzbuzz</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>"Fizz"</code> <code>+</code> <code>"Buzz";<br /></code> <code>}</code> <br /> <code>return</code> <code>fizzbuzz();</code> <br /><code>})()</code></pre>
<p>The definition of the&nbsp;<code>fizzbuzz</code>&nbsp;is &ldquo;hoisted&rdquo; to the top of its enclosing scope (an IIFE in this case). This behaviour is intentional on the part of JavaScript&rsquo;s design to facilitate a certain style of programming where you put the main logic up front, and the &ldquo;helper functions&rdquo; at the bottom. It is not necessary to declare functions in this way in JavaScript, but understanding the syntax and its behaviour (especially the way it differs from&nbsp;<code>const</code>) is essential for working with production code.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>function declaration caveats</h4>
<p>Function declarations are formally only supposed to be made at what we might call the &ldquo;top level&rdquo; of a function. Although some JavaScript environments permit the following code, this example is technically illegal and definitely a bad idea:</p>
<pre><code>(function</code> <code>(camelCase)</code> <code>{<br /></code> <code>return</code> <code>fizzbuzz();<br /></code> <br /> <code>if</code> <code>(camelCase)</code> <code>{<br /></code> <code>function</code> <code>fizzbuzz</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>"Fizz"</code> <code>+</code> <code>"Buzz";<br /></code> <code>}<br /></code> <code>}<br /></code> <code>else</code> <code>{<br /></code> <code>function</code> <code>fizzbuzz</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>"Fizz"</code> <code>+</code> <code>"Buzz";<br /></code> <code>}<br /></code> <code>}</code> <br /><code>})(true)</code> </pre>
<pre><code>//=&gt; 'FizzBuzz'? Or ERROR: Can't find variable: fizzbuzz?</code></pre>
<p>Function declarations are not supposed to occur inside of blocks. The big trouble with expressions like this is that they may work just fine in your test environment but work a different way in production. Or it may work one way today and a different way when the JavaScript engine is updated, say with a new optimization.</p>
<p>Another caveat is that a function declaration cannot exist inside of&nbsp;<em>any</em>expression, otherwise it&rsquo;s a function expression. So this is a function declaration:</p>
<pre><code>function</code> <code>trueDat</code> <code>()</code> <code>{</code> <code>return</code> <code>true</code> <code>}</code></pre>
<p>But this is not:</p>
<pre><code>(function</code> <code>trueDat</code> <code>()</code> <code>{</code> <code>return</code> <code>true</code> <code>})</code></pre>
<p>The parentheses make this an expression, not a function declaration.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Combinators and Function Decorators</h3>
<h4>higher-order functions</h4>
<p>As we&rsquo;ve seen, JavaScript functions take values as arguments and return values. JavaScript functions are values, so JavaScript functions can take functions as arguments, return functions, or both. Generally speaking, a function that either takes functions as arguments, or returns a function, or both, is referred to as a &ldquo;higher-order&rdquo; function.</p>
<p>Here&rsquo;s a very simple higher-order function that takes a function as an argument:</p>
<pre><code>const</code> <code>repeat</code> <code>=</code> <code>(num,</code> <code>fn)</code> <code>=&gt;<br /></code> <code>(num</code> <code>&gt;</code> <code>0)<br /></code> <code>?</code> <code>(repeat(num</code> <code>-</code> <code>1,</code> <code>fn),</code> <code>fn(num))<br /></code> <code>:</code> <code>undefined</code></pre>
<pre><code>repeat(3,</code> <code>function</code> <code>(n)</code> <code>{<br /></code> <code>console.log(`Hello ${n}`)<br />})</code> </pre>
<pre><code>//=&gt;</code> <code>'Hello 1'</code> <code>'Hello 2'</code> <code>'Hello 3'</code> <code>undefined</code></pre>
<p>Higher-order functions dominate&nbsp;<em>JavaScript Allong&eacute;</em>. But before we go on, we&rsquo;ll talk about some specific types of higher-order functions.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>combinators</h4>
<p>The word &ldquo;combinator&rdquo; has a precise technical meaning in mathematics:</p>
<blockquote>&ldquo;A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments.&rdquo;&ndash;<a title="Combinatory Logic" href="https://en.wikipedia.org/wiki/Combinatory_logic" target="_blank" rel="nofollow noopener" data-href="https://en.wikipedia.org/wiki/Combinatory_logic">Wikipedia</a></blockquote>
<p>If we were learning Combinatorial Logic, we&rsquo;d start with the most basic combinators like&nbsp;<code>S</code>,&nbsp;<code>K</code>, and&nbsp;<code>I</code>, and work up from there to practical combinators. We&rsquo;d learn that the fundamental combinators are named after birds following the example of Raymond Smullyan&rsquo;s famous book&nbsp;<a href="http://www.amazon.com/gp/product/B00A1P096Y/ref=as_li_ss_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=B00A1P096Y&amp;linkCode=as2&amp;tag=raganwald001-20" target="_blank" rel="nofollow noopener" data-href="http://www.amazon.com/gp/product/B00A1P096Y/ref=as_li_ss_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=B00A1P096Y&amp;linkCode=as2&amp;tag=raganwald001-20">To Mock a Mockingbird</a>.</p>
<p>In this book, we will be using a looser definition of &ldquo;combinator:&rdquo; Higher-order pure functions that take only functions as arguments and return a function. We won&rsquo;t be strict about using only previously defined combinators in their construction.</p>
<p>Let&rsquo;s start with a useful combinator: Most programmers call it&nbsp;<em>Compose</em>, although the logicians call it the B combinator or &ldquo;Bluebird.&rdquo; Here is the typical programming implementation:</p>
<pre><code>const</code> <code>compose</code> <code>=</code> <code>(a,</code> <code>b)</code> <code>=&gt;<br /></code> <code>(c)</code> <code>=&gt;</code> <code>a(b(c))</code></pre>
<p>Let&rsquo;s say we have:</p>
<pre><code>const</code> <code>addOne</code> <code>=</code> <code>(number)</code> <code>=&gt;</code> <code>number</code> <code>+</code> <code>1;</code> <br /><code>const</code> <code>doubleOf</code> <code>=</code> <code>(number)</code> <code>=&gt;</code> <code>number</code> <code>*</code> <code>2;</code></pre>
<p>With&nbsp;<code>compose</code>, anywhere you would write</p>
<pre><code>const</code> <code>doubleOfAddOne</code> <code>=</code> <code>(number)</code> <code>=&gt;</code> <code>doubleOf(addOne(number));</code></pre>
<p>You could also write:</p>
<p><code>const</code>&nbsp;<code>doubleOfAddOne</code>&nbsp;<code>=</code>&nbsp;<code>compose(doubleOf,</code>&nbsp;<code>addOne);</code></p>
<p>This is, of course, just one example of many. While some programmers believe &ldquo;There Should Only Be One Way To Do It,&rdquo; having combinators available as well as explicitly writing things out with lots of symbols and keywords has some advantages when used judiciously.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>a balanced statement about combinators</h4>
<p>Code that uses a lot of combinators tends to name the verbs and adverbs (like&nbsp;<code>doubleOf</code>,&nbsp;<code>addOne</code>, and&nbsp;<code>compose</code>) while avoiding language keywords and the names of nouns (like&nbsp;<code>number</code>). So one perspective is that combinators are useful when you want to emphasize what you&rsquo;re doing and how it fits together, and more explicit code is useful when you want to emphasize what you&rsquo;re working with.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>function decorators</h4>
<p>A&nbsp;<em>function decorator</em>&nbsp;is a higher-order function that takes one function as an argument, returns another function, and the returned function is a variation of the argument function. Here&rsquo;s a ridiculously simple decorator:</p>
<pre><code>const</code> <code>not</code> <code>=</code> <code>(fn)</code> <code>=&gt;</code> <code>(x)</code> <code>=&gt;</code> <code>!fn(x)</code></pre>
<p>So instead of writing&nbsp;<code>!someFunction(42)</code>, we can write&nbsp;<code>not(someFunction)(42)</code>. Hardly progress. But like&nbsp;<code>compose</code>, we could write either:</p>
<pre><code>const</code> <code>something</code> <code>=</code> <code>(x)</code> <code>=&gt;</code> <code>x</code> <code>!=</code> <code>null;</code></pre>
<p>And elsewhere, write:</p>
<pre><code>const</code> <code>nothing</code> <code>=</code> <code>(x)</code> <code>=&gt;</code> <code>!something(x);</code></pre>
<p>Or we could write:</p>
<pre><code>const</code> <code>nothing</code> <code>=</code> <code>not(something);</code></pre>
<p><code>not</code>&nbsp;is a function decorator because it modifies a function while remaining strongly related to the original function&rsquo;s semantics. Function decorators aren&rsquo;t strict about being pure functions, so there&rsquo;s more latitude for making decorators than combinators.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Building Blocks</h3>
<p>When you look at functions within functions in JavaScript, there&rsquo;s a bit of a &ldquo;spaghetti code&rdquo; look to it. The strength of JavaScript is that you can do anything. The weakness is that you will. There are ifs, fors, returns, everything thrown higgledy piggledy together. Although you needn&rsquo;t restrict yourself to a small number of simple patterns, it can be helpful to understand the patterns so that you can structure your code around some basic building blocks.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>composition</h4>
<p>One of the most basic of these building blocks is&nbsp;<em>composition</em>:</p>
<pre><code>const</code> <code>cookAndEat</code> <code>=</code> <code>(food)</code> <code>=&gt;</code> <code>eat(cook(food));</code></pre>
<p>It&rsquo;s really that simple: Whenever you are chaining two or more functions together, you&rsquo;re composing them. You can compose them with explicit JavaScript code as we&rsquo;ve just done. You can also generalize composition with the B Combinator or &ldquo;compose&rdquo; that we saw in Combinators and Decorators:</p>
<pre><code>const</code> <code>compose</code> <code>=</code> <code>(a,</code> <code>b)</code> <code>=&gt;</code> <code>(c)</code> <code>=&gt;</code> <code>a(b(c));</code> <br /><code>const</code> <code>cookAndEat</code> <code>=</code> <code>compose(eat,</code> <code>cook);</code></pre>
<p>If that was all there was to it, composition wouldn&rsquo;t matter much. But like many patterns, using it when it applies is only 20% of the benefit. The other 80% comes from organizing your code such that you can use it: Writing functions that can be composed in various ways.</p>
<p>Of course, you needn&rsquo;t use combinators to implement either of these ideas, you can use if statements. But&nbsp;<code>once</code>&nbsp;and&nbsp;<code>maybe</code>&nbsp;compose, so you can chain them together as you see fit:</p>
<pre><code>const</code> <code>actuallyTransfer =</code> <code>(from,</code> <code>to,</code> <code>amount)</code> <code>=&gt;</code> <code>// do something</code> <code>const</code> <code>invokeTransfer</code> <code>=</code> <code>once(maybe(actuallyTransfer(...)));</code></pre>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>partial application</h4>
<p>Another basic building block is&nbsp;<em>partial application</em>. When a function takes multiple arguments, we &ldquo;apply&rdquo; the function to the arguments by evaluating it with all of the arguments, producing a value. But what if we only supply some of the arguments? In that case, we can&rsquo;t get the final value, but we can get a function that represents&nbsp;<em>part</em>&nbsp;of our application.</p>
<p>Code is easier than words for this. The&nbsp;<a href="http://underscorejs.org/" target="_blank" rel="nofollow noopener" data-href="http://underscorejs.org">Underscore</a>&nbsp;library provides a higher-order function called&nbsp;<em>map</em>. It applies another function to each element of an array, like this:</p>
<pre><code>_.map([1,</code> <code>2,</code> <code>3],</code> <code>(n)</code> <code>=&gt;</code> <code>n</code> <code>*</code> <code>n)</code> <code>//=&gt; [1, 4, 9]</code></pre>
<p>We don&rsquo;t want to fool around writing&nbsp;<code>_.</code>, so we can use it by writing:</p>
<p><code>const</code>&nbsp;<code>map</code>&nbsp;<code>=</code>&nbsp;<code>_.map;</code></p>
<p>This code implements a partial application of the map function by applying the function&nbsp;<code>(n) =&gt; n * n</code>&nbsp;as its second argument:</p>
<pre><code>const</code> <code>squareAll</code> <code>=</code> <code>(array)</code> <code>=&gt;</code> <code>map(array,</code> <code>(n)</code> <code>=&gt;</code> <code>n</code> <code>*</code> <code>n);</code></pre>
<p>The resulting function&ndash;<code>squareAll</code>&ndash;is still the map function, it&rsquo;s just that we&rsquo;ve applied one of its two arguments already.&nbsp;<code>squareAll</code>&nbsp;is nice, but why write one function every time we want to partially apply a function to a map? We can abstract this one level higher.&nbsp;<code>mapWith</code>&nbsp;takes any function as an argument and returns a partially applied map function.</p>
<pre><code>const</code> <code>mapWith</code> <code>=</code> <code>(fn)</code> <code>=&gt;</code> <br /> <code>(array)</code> <code>=&gt;</code> <code>map(array,</code> <code>fn);</code> </pre>
<pre><code>const</code> <code>squareAll</code> <code>=</code> <code>mapWith((n)</code> <code>=&gt;</code> <code>n</code> <code>*</code> <code>n);</code> </pre>
<pre><code>squareAll([1,</code> <code>2,</code> <code>3])</code> <code>//=&gt; [1, 4, 9]</code></pre>
<p>The important thing to see is that partial application is orthogonal to composition, and that they both work together nicely:</p>
<pre><code>const</code> <code>safeSquareAll</code> <code>=</code> <code>mapWith(maybe((n)</code> <code>=&gt;</code> <code>n</code> <code>*</code> <code>n));</code> </pre>
<pre><code>safeSquareAll([1,</code> <code>null,</code> <code>2,</code> <code>3])</code> <code>//=&gt; [1, null, 4, 9]</code></pre>
<p>We generalized composition with the&nbsp;<code>compose</code>&nbsp;combinator.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h3>Magic Names</h3>
<p>When a function is applied to arguments (or &ldquo;called&rdquo;), JavaScript binds the values of arguments to the function&rsquo;s argument names in an environment created for the function&rsquo;s execution. What we haven&rsquo;t discussed so far is that JavaScript also binds values to some &ldquo;magic&rdquo; names in addition to any you put in the argument list.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>the function&nbsp;keyword</h4>
<p>There are two separate rules for these &ldquo;magic&rdquo; names, one for when you invoke a function using the&nbsp;<code>function</code>&nbsp;keyword, and another for functions defined with &ldquo;fat arrows.&rdquo; We&rsquo;ll begin with how things work for functions defined with the&nbsp;<code>function</code>&nbsp;keyword.</p>
<p>The first magic name is&nbsp;<code>this</code>, and it is bound to something called the function&rsquo;s context. We will explore&nbsp;<code>this</code>&nbsp;in more detail when we start discussing objects and classes&nbsp;<em>[editor: not in this article, but in the book and maybe in a future excerpt]</em>. The second magic name is very interesting, it&rsquo;s called&nbsp;<code>arguments</code>, and the most interesting thing about it is that it contains a list of arguments passed to a function:</p>
<pre><code>const</code> <code>plus</code> <code>=</code> <code>function</code> <code>(a,</code> <code>b)</code> <code>{</code> <br /> <code>return</code> <code>arguments[0]</code> <code>+</code> <code>arguments[1];</code> <br /><code>}</code> </pre>
<pre><code>plus(2,3)</code> <br /><code>//=&gt; 5</code></pre>
<p>Although&nbsp;<code>arguments</code>&nbsp;looks like an array, it isn&rsquo;t an array: It&rsquo;s more like an object that happens to bind some values to properties with names that look like integers starting with zero:</p>
<pre><code>const</code> <code>args</code> <code>=</code> <code>function</code> <code>(a,</code> <code>b)</code> <code>{<br /></code> <code>return</code> <code>arguments;</code> <br /><code>}</code> </pre>
<pre><code>args(2,3)</code> <br /><code>//=&gt; { '0': 2, '1': 3 }</code></pre>
<p><code>arguments</code>&nbsp;always contains all of the arguments passed to a function, regardless of how many are declared. Therefore, we can write&nbsp;<code>plus</code>&nbsp;like this:</p>
<pre><code>const</code> <code>plus</code> <code>=</code> <code>function</code> <code>()</code> <code>{</code> <code>return</code> <code>arguments[0]</code> <code>+</code> <code>arguments[1];</code> <code>}</code> </pre>
<pre><code>plus(2,3)</code> <br /><code>//=&gt; 5</code></pre>
<p>When discussing objects, we&rsquo;ll discuss properties in more depth. Here&rsquo;s something interesting about&nbsp;<code>arguments</code>:</p>
<pre><code>const</code> <code>howMany</code> <code>=</code> <code>function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>arguments['length'];</code> <br /><code>}</code> </pre>
<pre><code>howMany()</code> </pre>
<pre><code>//=&gt; 0</code> </pre>
<pre><code>howMany('hello')</code> <br /><code>//=&gt; 1</code> </pre>
<pre><code>howMany('sharks',</code> <code>'are',</code> <code>'apex',</code> <code>'predators')</code> <br /><code>//=&gt; 4</code></pre>
<p>The most common use of the&nbsp;<code>arguments</code>&nbsp;binding is to build functions that can take a variable number of arguments.</p>
</div>
</div>
</section>
<section>
<div><hr /></div>
<div>
<div>
<h4>magic names and fat&nbsp;arrows</h4>
<p>The magic names&nbsp;<code>this</code>&nbsp;and&nbsp;<code>arguments</code>&nbsp;have a different behaviour when you invoke a function that was defined with a fat arrow: Instead of being bound when the function is invoked, the fat arrow function always acquires the bindings for&nbsp;<code>this</code>&nbsp;and&nbsp;<code>arguments</code>&nbsp;from its enclosing scope, just like any other binding.</p>
<p>For example, when this expression&rsquo;s inner function is defined with&nbsp;<code>function</code>,&nbsp;<code>arguments[0]</code>&nbsp;refers to its only argument,&nbsp;<code>"inner"</code>:</p>
<pre><code>(function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>(function</code> <code>()</code> <code>{</code> <code>return</code> <code>arguments[0];</code> <code>})('inner');</code> <br /><code>})('outer')</code> </pre>
<pre><code>//=&gt; "inner"</code></pre>
<p>But if we use a fat arrow,&nbsp;<code>arguments</code>&nbsp;will be defined in the outer environment, the one defined with&nbsp;<code>function</code>. And thus&nbsp;<code>arguments[0]</code>&nbsp;will refer to&nbsp;<code>"outer"</code>, not to&nbsp;<code>"inner"</code>:</p>
<pre><code>(function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>(()</code> <code>=&gt;</code> <code>arguments[0])('inner');</code> <br /><code>})('outer')</code> </pre>
<pre><code>//=&gt; "outer"</code></pre>
<p>Although it seems quixotic for the two syntaxes to have different semantics, it makes sense when you consider the design goal: Fat arrow functions are designed to be very lightweight and are often used with constructs like mapping or callbacks to emulate syntax.</p>
<p>To give a contrived example, this function takes a number and returns an array representing a row in a hypothetical multiplication table. It uses&nbsp;<code>mapWith</code>, which we discussed in&nbsp;<a href="https://medium.com/better-programming/an-intro-to-javascript-for-experienced-programmers-who-could-use-a-strong-dose-of-fundamentals-31535030616b#buildingblocks" data-href="#buildingblocks">Building Blocks</a>.<a href="https://medium.com/better-programming/an-intro-to-javascript-for-experienced-programmers-who-could-use-a-strong-dose-of-fundamentals-31535030616b#fn-mapWith" rel="footnote" data-href="#fn-mapWith">24</a>&nbsp;We&rsquo;ll use&nbsp;<code>arguments</code>&nbsp;just to show the difference between using a fat arrow and the function keyword:</p>
<pre><code>const</code> <code>row</code> <code>=</code> <code>function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>mapWith((column)</code> <code>=&gt;</code> <code>column</code> <code>*</code> <code>arguments[0])(<br /></code> <code>[1,</code> <code>2,</code> <code>3,</code> <code>4,</code> <code>5,</code> <code>6,</code> <code>7,</code> <code>8,</code> <code>9,</code> <code>10,</code> <code>11,</code> <code>12]<br /></code> <code>)</code> <br /><code>}</code> </pre>
<pre><code>row(3)</code> </pre>
<pre><code>//=&gt; [3,6,9,12,15,18,21,24,27,30,33,36</code></pre>
<p>This works just fine, because&nbsp;<code>arguments[0]</code>&nbsp;refers to the&nbsp;<code>3</code>&nbsp;we passed to the function&nbsp;<code>row</code>. Our &ldquo;fat arrow&rdquo; function&nbsp;<code>(column) =&gt; column * arguments[0]</code>doesn&rsquo;t bind&nbsp;<code>arguments</code>&nbsp;when it&rsquo;s invoked. But if we rewrite&nbsp;<code>row</code>to use the&nbsp;<code>function</code>&nbsp;keyword, it stops working:</p>
<pre><code>const</code> <code>row</code> <code>=</code> <code>function</code> <code>()</code> <code>{<br /></code> <code>return</code> <code>mapWith(function</code> <code>(column)</code> <code>{</code> <code>return</code> <code>column</code> <code>*</code> <code>arguments[0]</code> <code>})(<br /></code> <code>[1,</code> <code>2,</code> <code>3,</code> <code>4,</code> <code>5,</code> <code>6,</code> <code>7,</code> <code>8,</code> <code>9,</code> <code>10,</code> <code>11,</code> <code>12]<br /></code> <code>)</code> <code>}</code> </pre>
<pre><code>row(3)</code> </pre>
<pre><code>//=&gt; [1,4,9,16,25,36,49,64,81,100,121,144]</code></pre>
<p>Now our inner function binds&nbsp;<code>arguments[0]</code>&nbsp;every time it is invoked, so we get the same result as if we&rsquo;d written&nbsp;<code>function (column) { return column * column }</code>.</p>
<p>Although this example is clearly unrealistic, there is a general design principle that deserves attention. Sometimes, a function is meant to be used as a Big-F function. It has a name, it is called by different pieces of code, it&rsquo;s a first-class entity in the code.</p>
<p>But sometimes, a function is a small-f function. It&rsquo;s a simple representation of an expression to be computed. In our example above,&nbsp;<code>row</code>&nbsp;is a Big-F function, but&nbsp;<code>(column) =&gt; column * arguments[0]</code>&nbsp;is a small-f function, it exists just to give&nbsp;<code>mapWith</code>&nbsp;something to apply.</p>
<p>Having magic variables apply to Big-F functions but not to small-f functions makes it much easier to use small-f functions as syntax, treating them as expressions or blocks that can be passed to functions like&nbsp;<code>mapWith</code>.</p>
</div>
</div>
</section>
</div>
<footer>
</footer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment