-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_values.html
More file actions
293 lines (173 loc) · 43.6 KB
/
01_values.html
File metadata and controls
293 lines (173 loc) · 43.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Values, Types, and Operators :: Eloquent JavaScript</title>
<link rel=stylesheet href="js/node_modules/codemirror/lib/codemirror.css">
<script src="js/acorn_codemirror.js"></script>
<link rel=stylesheet href="css/ejs.css">
<script src="js/sandbox.js"></script>
<script src="js/ejs.js"></script><script>var chapNum = 1;</script></head>
<article>
<nav><a href="00_intro.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a> <a href="02_program_structure.html" title="next chapter">▶</a></nav>
<h1><span class=chap_num>Chapter 1</span>Values, Types, and Operators</h1>
<blockquote>
<p><a class="p_ident" id="p_93S4YBaGUf" href="#p_93S4YBaGUf" tabindex="-1" role="presentation"></a>Below the surface of the machine, the program moves. Without effort, it expands and contracts. In great harmony, electrons scatter and regroup. The forms on the monitor are but ripples on the water. The essence stays invisibly below.</p>
<footer>Master Yuan-Ma, <cite>The Book of Programming</cite></footer>
</blockquote><figure class="chapter framed"><img src="img/chapter_picture_1.jpg" alt="Picture of a sea of bits"></figure>
<p><a class="p_ident" id="p_sgNSYKwqbo" href="#p_sgNSYKwqbo" tabindex="-1" role="presentation"></a>Inside the computer’s world, there is only data. You can read data, modify data, create new data—but that which isn’t data cannot be mentioned. All this data is stored as long sequences of bits and is thus fundamentally alike.</p>
<p><a class="p_ident" id="p_W1gJpe5a7/" href="#p_W1gJpe5a7/" tabindex="-1" role="presentation"></a><em>Bits</em> are any kind of two-valued things, usually described as zeros and ones. Inside the computer, they take forms such as a high or low electrical charge, a strong or weak signal, or a shiny or dull spot on the surface of a CD. Any piece of discrete information can be reduced to a sequence of zeros and ones and thus represented in bits.</p>
<p><a class="p_ident" id="p_PDoqiRoGSa" href="#p_PDoqiRoGSa" tabindex="-1" role="presentation"></a>For example, we can express the number 13 in bits. It works the same way as a decimal number, but instead of 10 different digits, you have only 2, and the weight of each increases by a factor of 2 from right to left. Here are the bits that make up the number 13, with the weights of the digits shown below them:</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_+fMMNc3yUt" href="#c_+fMMNc3yUt" tabindex="-1" role="presentation"></a> 0 0 0 0 1 1 0 1
128 64 32 16 8 4 2 1</pre>
<p><a class="p_ident" id="p_0u8qQ2tfMI" href="#p_0u8qQ2tfMI" tabindex="-1" role="presentation"></a>So that’s the binary number 00001101. Its non-zero digits stand for 8, 4, and 1, and add up to 13.</p>
<h2><a class="h_ident" id="h_sVZPaxUSy/" href="#h_sVZPaxUSy/" tabindex="-1" role="presentation"></a>Values</h2>
<p><a class="p_ident" id="p_ySnc2wG5kf" href="#p_ySnc2wG5kf" tabindex="-1" role="presentation"></a>Imagine a sea of bits—an ocean of them. A typical modern computer has more than 30 billion bits in its volatile data storage (working memory). Nonvolatile storage (the hard disk or equivalent) tends to have yet a few orders of magnitude more.</p>
<p><a class="p_ident" id="p_JRdY+sw4TV" href="#p_JRdY+sw4TV" tabindex="-1" role="presentation"></a>To be able to work with such quantities of bits without getting lost, we must separate them into chunks that represent pieces of information. In a JavaScript environment, those chunks are called <em>values</em>. Though all values are made of bits, they play different roles. Every value has a type that determines its role. Some values are numbers, some values are pieces of text, some values are functions, and so on.</p>
<p><a class="p_ident" id="p_+ayfFmFdze" href="#p_+ayfFmFdze" tabindex="-1" role="presentation"></a>To create a value, you must merely invoke its name. This is convenient. You don’t have to gather building material for your values or pay for them. You just call for one, and <em>whoosh</em>, you have it. They are not really created from thin air, of course. Every value has to be stored somewhere, and if you want to use a gigantic amount of them at the same time, you might run out of memory. Fortunately, this is a problem only if you need them all simultaneously. As soon as you no longer use a value, it will dissipate, leaving behind its bits to be recycled as building material for the next generation of values.</p>
<p><a class="p_ident" id="p_lWUuVOz1Pd" href="#p_lWUuVOz1Pd" tabindex="-1" role="presentation"></a>This chapter introduces the atomic elements of JavaScript programs, that is, the simple value types and the operators that can act on such values.</p>
<h2><a class="h_ident" id="h_flOCH3CuFg" href="#h_flOCH3CuFg" tabindex="-1" role="presentation"></a>Numbers</h2>
<p><a class="p_ident" id="p_lB/BspzEbz" href="#p_lB/BspzEbz" tabindex="-1" role="presentation"></a>Values of the <em>number</em> type are, unsurprisingly, numeric values. In a JavaScript program, they are written as follows:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_/u5ErTZbax" href="#c_/u5ErTZbax" tabindex="-1" role="presentation"></a><span class="cm-number">13</span></pre>
<p><a class="p_ident" id="p_nFVjE3kHJh" href="#p_nFVjE3kHJh" tabindex="-1" role="presentation"></a>Use that in a program, and it will cause the bit pattern for the number 13 to come into existence inside the computer’s memory.</p>
<p><a class="p_ident" id="p_TBpgYLjzVr" href="#p_TBpgYLjzVr" tabindex="-1" role="presentation"></a>JavaScript uses a fixed number of bits, 64 of them, to store a single number value. There are only so many patterns you can make with 64 bits, which means that the number of different numbers that can be represented is limited. With <em>N</em> decimal digits, you can represent 10<sup>N</sup> numbers. Similarly, given 64 binary digits, you can represent 2<sup>64</sup> different numbers, which is about 18 quintillion (an 18 with 18 zeros after it). That’s a lot.</p>
<p><a class="p_ident" id="p_WcfWpTcQB6" href="#p_WcfWpTcQB6" tabindex="-1" role="presentation"></a>Computer memory used to be much smaller, and people tended to use groups of 8 or 16 bits to represent their numbers. It was easy to accidentally <em>overflow</em> such small numbers—to end up with a number that did not fit into the given number of bits. Today, even computers that fit in your pocket have plenty of memory, so you are free to use 64-bit chunks, and you need to worry about overflow only when dealing with truly astronomical numbers.</p>
<p><a class="p_ident" id="p_qgS+bpqvEk" href="#p_qgS+bpqvEk" tabindex="-1" role="presentation"></a>Not all whole numbers less than 18 quintillion fit in a JavaScript number, though. Those bits also store negative numbers, so one bit indicates the sign of the number. A bigger issue is that nonwhole numbers must also be represented. To do this, some of the bits are used to store the position of the decimal point. The actual maximum whole number that can be stored is more in the range of 9 quadrillion (15 zeros)—which is still pleasantly huge.</p>
<p><a class="p_ident" id="p_+wzyK91zcb" href="#p_+wzyK91zcb" tabindex="-1" role="presentation"></a>Fractional numbers are written by using a dot.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_tM8nqv41Gp" href="#c_tM8nqv41Gp" tabindex="-1" role="presentation"></a><span class="cm-number">9.81</span></pre>
<p><a class="p_ident" id="p_oofHxZNW9M" href="#p_oofHxZNW9M" tabindex="-1" role="presentation"></a>For very big or very small numbers, you may also use scientific notation by adding an <em>e</em> (for <em>exponent</em>), followed by the exponent of the number.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_6ew5w+VhSM" href="#c_6ew5w+VhSM" tabindex="-1" role="presentation"></a><span class="cm-number">2.998e8</span></pre>
<p><a class="p_ident" id="p_YbACmHw8Kd" href="#p_YbACmHw8Kd" tabindex="-1" role="presentation"></a>That is 2.998 × 10<sup>8</sup> = 299,800,000.</p>
<p><a class="p_ident" id="p_8KgYC0F1fX" href="#p_8KgYC0F1fX" tabindex="-1" role="presentation"></a>Calculations with whole numbers (also called <em>integers</em>) smaller than the aforementioned 9 quadrillion are guaranteed to always be precise. Unfortunately, calculations with fractional numbers are generally not. Just as π (pi) cannot be precisely expressed by a finite number of decimal digits, many numbers lose some precision when only 64 bits are available to store them. This is a shame, but it causes practical problems only in specific situations. The important thing is to be aware of it and treat fractional digital numbers as approximations, not as precise values.</p>
<h3><a class="i_ident" id="i_RfBT3HMnYs" href="#i_RfBT3HMnYs" tabindex="-1" role="presentation"></a>Arithmetic</h3>
<p><a class="p_ident" id="p_PO8MaZIpG1" href="#p_PO8MaZIpG1" tabindex="-1" role="presentation"></a>The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. Here is what they look like in JavaScript:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_bSU4Vtv/mt" href="#c_bSU4Vtv/mt" tabindex="-1" role="presentation"></a><span class="cm-number">100</span> <span class="cm-operator">+</span> <span class="cm-number">4</span> <span class="cm-operator">*</span> <span class="cm-number">11</span></pre>
<p><a class="p_ident" id="p_Gbkt+ofKYQ" href="#p_Gbkt+ofKYQ" tabindex="-1" role="presentation"></a>The <code>+</code> and <code>*</code> symbols are called <em>operators</em>. The first stands for addition, and the second stands for multiplication. Putting an operator between two values will apply it to those values and produce a new value.</p>
<p><a class="p_ident" id="p_UaADJxNSjA" href="#p_UaADJxNSjA" tabindex="-1" role="presentation"></a>But does the example mean “add 4 and 100, and multiply the result by 11,” or is the multiplication done before the adding? As you might have guessed, the multiplication happens first. But as in mathematics, you can change this by wrapping the addition in parentheses.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_ij6V90ZZBQ" href="#c_ij6V90ZZBQ" tabindex="-1" role="presentation"></a>(<span class="cm-number">100</span> <span class="cm-operator">+</span> <span class="cm-number">4</span>) <span class="cm-operator">*</span> <span class="cm-number">11</span></pre>
<p><a class="p_ident" id="p_OSF05nVTV6" href="#p_OSF05nVTV6" tabindex="-1" role="presentation"></a>For subtraction, there is the <code>-</code> operator, and division can be done with the <code>/</code> operator.</p>
<p><a class="p_ident" id="p_sJXEzZnGO0" href="#p_sJXEzZnGO0" tabindex="-1" role="presentation"></a>When operators appear together without parentheses, the order in which they are applied is determined by the <em>precedence</em> of the operators. The example shows that multiplication comes before addition. The <code>/</code> operator has the same precedence as <code>*</code>. Likewise for <code>+</code> and <code>-</code>. When multiple operators with the same precedence appear next to each other, as in <code>1 - 2 + 1</code>, they are applied left to right: <code>(1 - 2) + 1</code>.</p>
<p><a class="p_ident" id="p_epF5qxonWY" href="#p_epF5qxonWY" tabindex="-1" role="presentation"></a>These rules of precedence are not something you should worry about. When in doubt, just add parentheses.</p>
<p><a class="p_ident" id="p_3aZxtaabKD" href="#p_3aZxtaabKD" tabindex="-1" role="presentation"></a>There is one more arithmetic operator, which you might not immediately recognize. The <code>%</code> symbol is used to represent the <em>remainder</em> operation. <code>X % Y</code> is the remainder of dividing <code>X</code> by <code>Y</code>. For example, <code>314 % 100</code> produces <code>14</code>, and <code>144 % 12</code> gives <code>0</code>. The remainder operator’s precedence is the same as that of multiplication and division. You’ll also often see this operator referred to as <em>modulo</em>.</p>
<h3><a class="i_ident" id="i_R4eFf8w7Yz" href="#i_R4eFf8w7Yz" tabindex="-1" role="presentation"></a>Special numbers</h3>
<p><a class="p_ident" id="p_JBBwZano0e" href="#p_JBBwZano0e" tabindex="-1" role="presentation"></a>There are three special values in JavaScript that are considered numbers but don’t behave like normal numbers.</p>
<p><a class="p_ident" id="p_Vk/nIi3mWM" href="#p_Vk/nIi3mWM" tabindex="-1" role="presentation"></a>The first two are <code>Infinity</code> and <code>-Infinity</code>, which represent the positive and negative infinities. <code>Infinity - 1</code> is still <code>Infinity</code>, and so on. Don’t put too much trust in infinity-based computation, though. It isn’t mathematically sound, and it will quickly lead to the next special number: <code>NaN</code>.</p>
<p><a class="p_ident" id="p_kS+V22+tDp" href="#p_kS+V22+tDp" tabindex="-1" role="presentation"></a><code>NaN</code> stands for “not a number”, even though it <em>is</em> a value of the number type. You’ll get this result when you, for example, try to calculate <code>0 / 0</code> (zero divided by zero), <code>Infinity - Infinity</code>, or any number of other numeric operations that don’t yield a meaningful result.</p>
<h2><a class="h_ident" id="h_OBbEvqxHHH" href="#h_OBbEvqxHHH" tabindex="-1" role="presentation"></a>Strings</h2>
<p><a class="p_ident" id="p_JUYnmsnZEA" href="#p_JUYnmsnZEA" tabindex="-1" role="presentation"></a>The next basic data type is the <em>string</em>. Strings are used to represent text. They are written by enclosing their content in quotes.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_JcfC82q1V/" href="#c_JcfC82q1V/" tabindex="-1" role="presentation"></a><span class="cm-string-2">`Down on the sea`</span>
<span class="cm-string">"Lie on the ocean"</span>
<span class="cm-string">'Float on the ocean'</span></pre>
<p><a class="p_ident" id="p_J5Re/uQFh3" href="#p_J5Re/uQFh3" tabindex="-1" role="presentation"></a>You can use single quotes, double quotes, or backticks to mark strings, as long as the quotes at the start and the end of the string match.</p>
<p><a class="p_ident" id="p_zqSxAQbLww" href="#p_zqSxAQbLww" tabindex="-1" role="presentation"></a>Almost anything can be put between quotes, and JavaScript will make a string value out of it. But a few characters are more difficult. You can imagine how putting quotes between quotes might be hard. <em>Newlines</em> (the characters you get when you press <span class="keyname">enter</span>) can be included without escaping only when the string is quoted with backticks (<code>`</code>).</p>
<p><a class="p_ident" id="p_Fhyuks46v3" href="#p_Fhyuks46v3" tabindex="-1" role="presentation"></a>To make it possible to include such characters in a string, the following notation is used: whenever a backslash (<code>\</code>) is found inside quoted text, it indicates that the character after it has a special meaning. This is called <em>escaping</em> the character. A quote that is preceded by a backslash will not end the string but be part of it. When an <code>n</code> character occurs after a backslash, it is interpreted as a newline. Similarly, a <code>t</code> after a backslash means a tab character. Take the following string:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_L1XyfWLjvh" href="#c_L1XyfWLjvh" tabindex="-1" role="presentation"></a><span class="cm-string">"This is the first line\nAnd this is the second"</span></pre>
<p><a class="p_ident" id="p_rtFNX67M4o" href="#p_rtFNX67M4o" tabindex="-1" role="presentation"></a>The actual text contained is this:</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_dbS7S3Fqly" href="#c_dbS7S3Fqly" tabindex="-1" role="presentation"></a>This is the first line
And this is the second</pre>
<p><a class="p_ident" id="p_RcQxEVsohZ" href="#p_RcQxEVsohZ" tabindex="-1" role="presentation"></a>There are, of course, situations where you want a backslash in a string to be just a backslash, not a special code. If two backslashes follow each other, they will collapse together, and only one will be left in the resulting string value. This is how the string “<em>A newline character is written like <code>"</code>\n<code>"</code>.</em>” can be expressed:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_AuMrnbfo/X" href="#c_AuMrnbfo/X" tabindex="-1" role="presentation"></a><span class="cm-string">"A newline character is written like \"\\n\"."</span></pre>
<p id="unicode"><a class="p_ident" id="p_FkxXOQHt6a" href="#p_FkxXOQHt6a" tabindex="-1" role="presentation"></a>Strings, too, have to be modeled as a series of bits to be able to exist inside the computer. The way JavaScript does this is based on the <em>Unicode</em> standard. This standard assigns a number to virtually every character you would ever need, including characters from Greek, Arabic, Japanese, Armenian, and so on. If we have a number for every character, a string can be described by a sequence of numbers.</p>
<p><a class="p_ident" id="p_FZTkxxFJHy" href="#p_FZTkxxFJHy" tabindex="-1" role="presentation"></a>And that’s what JavaScript does. But there’s a complication: JavaScript’s representation uses 16 bits per string element, which can describe up to 2<sup>16</sup> different characters. But Unicode defines more characters than that—about twice as many, at this point. So some characters, such as many emoji, take up two “character positions” in JavaScript strings. We’ll come back to this in <a href="05_higher_order.html#code_units">Chapter 5</a>.</p>
<p><a class="p_ident" id="p_+y5+JTiKgR" href="#p_+y5+JTiKgR" tabindex="-1" role="presentation"></a>Strings cannot be divided, multiplied, or subtracted, but the <code>+</code> operator <em>can</em> be used on them. It does not add, but it <em>concatenates</em>—it glues two strings together. The following line will produce the string <code>"concatenate"</code>:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_eCO7oekmP9" href="#c_eCO7oekmP9" tabindex="-1" role="presentation"></a><span class="cm-string">"con"</span> <span class="cm-operator">+</span> <span class="cm-string">"cat"</span> <span class="cm-operator">+</span> <span class="cm-string">"e"</span> <span class="cm-operator">+</span> <span class="cm-string">"nate"</span></pre>
<p><a class="p_ident" id="p_f802i8aCZi" href="#p_f802i8aCZi" tabindex="-1" role="presentation"></a>String values have a number of associated functions (<em>methods</em>) that can be used to perform other operations on them. I’ll say more about these in <a href="04_data.html#methods">Chapter 4</a>.</p>
<p><a class="p_ident" id="p_3NJXrCLWRR" href="#p_3NJXrCLWRR" tabindex="-1" role="presentation"></a>Strings written with single or double quotes behave very much the same—the only difference is in which type of quote you need to escape inside of them. Backtick-quoted strings, usually called <em>template
literals</em>, can do a few more tricks. Apart from being able to span lines, they can also embed other values.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_1ObyeNEDOw" href="#c_1ObyeNEDOw" tabindex="-1" role="presentation"></a><span class="cm-string-2">`half of 100 is ${</span><span class="cm-number">100</span> <span class="cm-operator">/</span> <span class="cm-number">2</span><span class="cm-string-2">}</span><span class="cm-string-2">`</span></pre>
<p><a class="p_ident" id="p_ogkFBzzZhi" href="#p_ogkFBzzZhi" tabindex="-1" role="presentation"></a>When you write something inside <code>${}</code> in a template literal, its result will be computed, converted to a string, and included at that position. The example produces “<em>half of 100 is 50</em>”.</p>
<h2><a class="h_ident" id="h_ygn12/ieo+" href="#h_ygn12/ieo+" tabindex="-1" role="presentation"></a>Unary operators</h2>
<p><a class="p_ident" id="p_GyQlmgK5IK" href="#p_GyQlmgK5IK" tabindex="-1" role="presentation"></a>Not all operators are symbols. Some are written as words. One example is the <code>typeof</code> operator, which produces a string value naming the type of the value you give it.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_iWT//VyY7j" href="#c_iWT//VyY7j" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">typeof</span> <span class="cm-number">4.5</span>)
<span class="cm-comment">// → number</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">typeof</span> <span class="cm-string">"x"</span>)
<span class="cm-comment">// → string</span></pre>
<p id="console.log"><a class="p_ident" id="p_edv0ySDJvj" href="#p_edv0ySDJvj" tabindex="-1" role="presentation"></a>We will use <code>console.log</code> in example code to indicate that we want to see the result of evaluating something. More about that in the <a href="02_program_structure.html">next chapter</a>.</p>
<p><a class="p_ident" id="p_fvxC7oK7dT" href="#p_fvxC7oK7dT" tabindex="-1" role="presentation"></a>The other operators shown all operated on two values, but <code>typeof</code> takes only one. Operators that use two values are called <em>binary</em> operators, while those that take one are called <em>unary</em> operators. The minus operator can be used both as a binary operator and as a unary operator.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_VpL89RFAPj" href="#c_VpL89RFAPj" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-operator">-</span> (<span class="cm-number">10</span> <span class="cm-operator">-</span> <span class="cm-number">2</span>))
<span class="cm-comment">// → -8</span></pre>
<h2><a class="h_ident" id="h_cTPxJxlmFR" href="#h_cTPxJxlmFR" tabindex="-1" role="presentation"></a>Boolean values</h2>
<p><a class="p_ident" id="p_OL3ZufvGRE" href="#p_OL3ZufvGRE" tabindex="-1" role="presentation"></a>It is often useful to have a value that distinguishes between only two possibilities, like “yes” and “no” or “on” and “off”. For this purpose, JavaScript has a <em>Boolean</em> type, which has just two values, true and false, which are written as those words.</p>
<h3><a class="i_ident" id="i_Lfz4mKO9Tg" href="#i_Lfz4mKO9Tg" tabindex="-1" role="presentation"></a>Comparison</h3>
<p><a class="p_ident" id="p_T4yLn4fXDH" href="#p_T4yLn4fXDH" tabindex="-1" role="presentation"></a>Here is one way to produce Boolean values:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_GaxnXrIPwC" href="#c_GaxnXrIPwC" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">3</span> <span class="cm-operator">></span> <span class="cm-number">2</span>)
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">3</span> <span class="cm-operator"><</span> <span class="cm-number">2</span>)
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_j0tOwzfb6M" href="#p_j0tOwzfb6M" tabindex="-1" role="presentation"></a>The <code>></code> and <code><</code> signs are the traditional symbols for “is greater than” and “is less than”, respectively. They are binary operators. Applying them results in a Boolean value that indicates whether they hold true in this case.</p>
<p><a class="p_ident" id="p_NxTGvCsM4s" href="#p_NxTGvCsM4s" tabindex="-1" role="presentation"></a>Strings can be compared in the same way.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Qud5plnVuV" href="#c_Qud5plnVuV" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Aardvark"</span> <span class="cm-operator"><</span> <span class="cm-string">"Zoroaster"</span>)
<span class="cm-comment">// → true</span></pre>
<p><a class="p_ident" id="p_No3uOP/bY2" href="#p_No3uOP/bY2" tabindex="-1" role="presentation"></a>The way strings are ordered is roughly alphabetic but not really what you’d expect to see in a dictionary: uppercase letters are always “less” than lowercase ones, so <code>"Z" < "a"</code>, and nonalphabetic characters (!, -, and so on) are also included in the ordering. When comparing strings, JavaScript goes over the characters from left to right, comparing the Unicode codes one by one.</p>
<p><a class="p_ident" id="p_fGKTuK5BBc" href="#p_fGKTuK5BBc" tabindex="-1" role="presentation"></a>Other similar operators are <code>>=</code> (greater than or equal to), <code><=</code> (less than or equal to), <code>==</code> (equal to), and <code>!=</code> (not equal to).</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_9h4L8Mnvdg" href="#c_9h4L8Mnvdg" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Itchy"</span> <span class="cm-operator">!=</span> <span class="cm-string">"Scratchy"</span>)
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Apple"</span> <span class="cm-operator">==</span> <span class="cm-string">"Orange"</span>)
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_tLooHn2QPj" href="#p_tLooHn2QPj" tabindex="-1" role="presentation"></a>There is only one value in JavaScript that is not equal to itself, and that is <code>NaN</code> (“not a number”).</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Vhz09Rgw3h" href="#c_Vhz09Rgw3h" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">NaN</span> <span class="cm-operator">==</span> <span class="cm-atom">NaN</span>)
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_rcMZUIfGYR" href="#p_rcMZUIfGYR" tabindex="-1" role="presentation"></a><code>NaN</code> is supposed to denote the result of a nonsensical computation, and as such, it isn’t equal to the result of any <em>other</em> nonsensical computations.</p>
<h3><a class="i_ident" id="i_pdqDW7Pebo" href="#i_pdqDW7Pebo" tabindex="-1" role="presentation"></a>Logical operators</h3>
<p><a class="p_ident" id="p_nRCLrGwcCn" href="#p_nRCLrGwcCn" tabindex="-1" role="presentation"></a>There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: <em>and</em>, <em>or</em>, and <em>not</em>. These can be used to “reason” about Booleans.</p>
<p><a class="p_ident" id="p_h6pEyNS4IJ" href="#p_h6pEyNS4IJ" tabindex="-1" role="presentation"></a>The <code>&&</code> operator represents logical <em>and</em>. It is a binary operator, and its result is true only if both the values given to it are true.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_SHi38sNkwM" href="#c_SHi38sNkwM" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">true</span> <span class="cm-operator">&</span><span class="cm-operator">&</span> <span class="cm-atom">false</span>)
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">true</span> <span class="cm-operator">&</span><span class="cm-operator">&</span> <span class="cm-atom">true</span>)
<span class="cm-comment">// → true</span></pre>
<p><a class="p_ident" id="p_T/V30CHY82" href="#p_T/V30CHY82" tabindex="-1" role="presentation"></a>The <code>||</code> operator denotes logical <em>or</em>. It produces true if either of the values given to it is true.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_diXyv7iPd1" href="#c_diXyv7iPd1" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">false</span> <span class="cm-operator">|</span><span class="cm-operator">|</span> <span class="cm-atom">true</span>)
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">false</span> <span class="cm-operator">|</span><span class="cm-operator">|</span> <span class="cm-atom">false</span>)
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_OxH3G7iBRz" href="#p_OxH3G7iBRz" tabindex="-1" role="presentation"></a><em>Not</em> is written as an exclamation mark (<code>!</code>). It is a unary operator that flips the value given to it—<code>!true</code> produces <code>false</code>, and <code>!false</code> gives <code>true</code>.</p>
<p><a class="p_ident" id="p_qSXjNNI5/y" href="#p_qSXjNNI5/y" tabindex="-1" role="presentation"></a>When mixing these Boolean operators with arithmetic and other operators, it is not always obvious when parentheses are needed. In practice, you can usually get by with knowing that of the operators we have seen so far, <code>||</code> has the lowest precedence, then comes <code>&&</code>, then the comparison operators (<code>></code>, <code>==</code>, and so on), and then the rest. This order has been chosen such that, in typical expressions like the following one, as few parentheses as possible are necessary:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_6eZ07bDo11" href="#c_6eZ07bDo11" tabindex="-1" role="presentation"></a><span class="cm-number">1</span> <span class="cm-operator">+</span> <span class="cm-number">1</span> <span class="cm-operator">==</span> <span class="cm-number">2</span> <span class="cm-operator">&</span><span class="cm-operator">&</span> <span class="cm-number">10</span> <span class="cm-operator">*</span> <span class="cm-number">10</span> <span class="cm-operator">></span> <span class="cm-number">50</span></pre>
<p><a class="p_ident" id="p_EWJu4coIAh" href="#p_EWJu4coIAh" tabindex="-1" role="presentation"></a>The last logical operator I will discuss is not unary, not binary, but <em>ternary</em>, operating on three values. It is written with a question mark and a colon, like this:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_G7eVm8ilWm" href="#c_G7eVm8ilWm" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">true</span> <span class="cm-operator">?</span> <span class="cm-number">1</span> : <span class="cm-number">2</span>);
<span class="cm-comment">// → 1</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">false</span> <span class="cm-operator">?</span> <span class="cm-number">1</span> : <span class="cm-number">2</span>);
<span class="cm-comment">// → 2</span></pre>
<p><a class="p_ident" id="p_xZmtGs+CeV" href="#p_xZmtGs+CeV" tabindex="-1" role="presentation"></a>This one is called the <em>conditional</em> operator (or sometimes just the <em>ternary</em> operator since it is the only such operator in the language). The value on the left of the question mark “picks” which of the other two values will come out. When it is true, it chooses the middle value, and when it is false, it chooses the value on the right.</p>
<h2><a class="h_ident" id="h_FewqJ8K2E+" href="#h_FewqJ8K2E+" tabindex="-1" role="presentation"></a>Empty values</h2>
<p><a class="p_ident" id="p_Q/OIPtr8xY" href="#p_Q/OIPtr8xY" tabindex="-1" role="presentation"></a>There are two special values, written <code>null</code> and <code>undefined</code>, that are used to denote the absence of a <em>meaningful</em> value. They are themselves values, but they carry no information.</p>
<p><a class="p_ident" id="p_3veSnHeYus" href="#p_3veSnHeYus" tabindex="-1" role="presentation"></a>Many operations in the language that don’t produce a meaningful value (you’ll see some later) yield <code>undefined</code> simply because they have to yield <em>some</em> value.</p>
<p><a class="p_ident" id="p_43ZLcQuUDk" href="#p_43ZLcQuUDk" tabindex="-1" role="presentation"></a>The difference in meaning between <code>undefined</code> and <code>null</code> is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.</p>
<h2><a class="h_ident" id="h_AY+YGu6qyM" href="#h_AY+YGu6qyM" tabindex="-1" role="presentation"></a>Automatic type conversion</h2>
<p><a class="p_ident" id="p_I6CpHrk6+W" href="#p_I6CpHrk6+W" tabindex="-1" role="presentation"></a>In the Introduction, I mentioned that JavaScript goes out of its way to accept almost any program you give it, even programs that do odd things. This is nicely demonstrated by the following expressions:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_QqYG9KqZ2/" href="#c_QqYG9KqZ2/" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-number">8</span> <span class="cm-operator">*</span> <span class="cm-atom">null</span>)
<span class="cm-comment">// → 0</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"5"</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>)
<span class="cm-comment">// → 4</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"5"</span> <span class="cm-operator">+</span> <span class="cm-number">1</span>)
<span class="cm-comment">// → 51</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"five"</span> <span class="cm-operator">*</span> <span class="cm-number">2</span>)
<span class="cm-comment">// → NaN</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">false</span> <span class="cm-operator">==</span> <span class="cm-number">0</span>)
<span class="cm-comment">// → true</span></pre>
<p><a class="p_ident" id="p_3GSZqcE16B" href="#p_3GSZqcE16B" tabindex="-1" role="presentation"></a>When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it needs, using a set of rules that often aren’t what you want or expect. This is called <em>type coercion</em>. The <code>null</code> in the first expression becomes <code>0</code>, and the <code>"5"</code> in the second expression becomes <code>5</code> (from string to number). Yet in the third expression, <code>+</code> tries string concatenation before numeric addition, so the <code>1</code> is converted to <code>"1"</code> (from number to string).</p>
<p><a class="p_ident" id="p_mw5To5JJ6Q" href="#p_mw5To5JJ6Q" tabindex="-1" role="presentation"></a>When something that doesn’t map to a number in an obvious way (such as <code>"five"</code> or <code>undefined</code>) is converted to a number, you get the value <code>NaN</code>. Further arithmetic operations on <code>NaN</code> keep producing <code>NaN</code>, so if you find yourself getting one of those in an unexpected place, look for accidental type conversions.</p>
<p><a class="p_ident" id="p_XbK88HE+DJ" href="#p_XbK88HE+DJ" tabindex="-1" role="presentation"></a>When comparing values of the same type using <code>==</code>, the outcome is easy to predict: you should get true when both values are the same, except in the case of <code>NaN</code>. But when the types differ, JavaScript uses a complicated and confusing set of rules to determine what to do. In most cases, it just tries to convert one of the values to the other value’s type. However, when <code>null</code> or <code>undefined</code> occurs on either side of the operator, it produces true only if both sides are one of <code>null</code> or <code>undefined</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_qmGDPdETlf" href="#c_qmGDPdETlf" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">null</span> <span class="cm-operator">==</span> <span class="cm-atom">undefined</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">null</span> <span class="cm-operator">==</span> <span class="cm-number">0</span>);
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_hu+ZqjMro3" href="#p_hu+ZqjMro3" tabindex="-1" role="presentation"></a>That behavior is often useful. When you want to test whether a value has a real value instead of <code>null</code> or <code>undefined</code>, you can compare it to <code>null</code> with the <code>==</code> (or <code>!=</code>) operator.</p>
<p><a class="p_ident" id="p_N4OuWeYOwF" href="#p_N4OuWeYOwF" tabindex="-1" role="presentation"></a>But what if you want to test whether something refers to the precise value <code>false</code>? Expressions like <code>0 == false</code> and <code>"" == false</code> are also true because of automatic type conversion. When you do <em>not</em> want any type conversions to happen, there are two additional operators: <code>===</code> and <code>!==</code>. The first tests whether a value is <em>precisely</em> equal to the other, and the second tests whether it is not precisely equal. So <code>"" === false</code> is false as expected.</p>
<p><a class="p_ident" id="p_S/opLpHJcU" href="#p_S/opLpHJcU" tabindex="-1" role="presentation"></a>I recommend using the three-character comparison operators defensively to prevent unexpected type conversions from tripping you up. But when you’re certain the types on both sides will be the same, there is no problem with using the shorter operators.</p>
<h3><a class="i_ident" id="i_3jN0iK4yKW" href="#i_3jN0iK4yKW" tabindex="-1" role="presentation"></a>Short-circuiting of logical operators</h3>
<p><a class="p_ident" id="p_CFbagJsQYK" href="#p_CFbagJsQYK" tabindex="-1" role="presentation"></a>The logical operators <code>&&</code> and <code>||</code> handle values of different types in a peculiar way. They will convert the value on their left side to Boolean type in order to decide what to do, but depending on the operator and the result of that conversion, they will return either the <em>original</em> left-hand value or the right-hand value.</p>
<p><a class="p_ident" id="p_BFq+/JeBH9" href="#p_BFq+/JeBH9" tabindex="-1" role="presentation"></a>The <code>||</code> operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise. This has the expected effect when the values are Boolean and does something analogous for values of other types.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_ENjxHGMklb" href="#c_ENjxHGMklb" tabindex="-1" role="presentation"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-atom">null</span> <span class="cm-operator">|</span><span class="cm-operator">|</span> <span class="cm-string">"user"</span>)
<span class="cm-comment">// → user</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Agnes"</span> <span class="cm-operator">|</span><span class="cm-operator">|</span> <span class="cm-string">"user"</span>)
<span class="cm-comment">// → Agnes</span></pre>
<p><a class="p_ident" id="p_+E3wg/b+ti" href="#p_+E3wg/b+ti" tabindex="-1" role="presentation"></a>We can use this functionality as a way to fall back on a default value. If you have a value that might be empty, you can put <code>||</code> after it with a replacement value. If the initial value can be converted to false, you’ll get the replacement instead. The rules for converting strings and numbers to Boolean values state that <code>0</code>, <code>NaN</code>, and the empty string (<code>""</code>) count as <code>false</code>, while all the other values count as <code>true</code>. So <code>0 || -1</code> produces <code>-1</code>, and <code>"" || "!?"</code> yields <code>"!?"</code>.</p>
<p><a class="p_ident" id="p_LlkwKHpB6u" href="#p_LlkwKHpB6u" tabindex="-1" role="presentation"></a>The <code>&&</code> operator works similarly but the other way around. When the value to its left is something that converts to false, it returns that value, and otherwise it returns the value on its right.</p>
<p><a class="p_ident" id="p_IW4V8ztNjs" href="#p_IW4V8ztNjs" tabindex="-1" role="presentation"></a>Another important property of these two operators is that the part to their right is evaluated only when necessary. In the case of <code>true || X</code>, no matter what <code>X</code> is—even if it’s a piece of program that does something <em>terrible</em>—the result will be true, and <code>X</code> is never evaluated. The same goes for <code>false && X</code>, which is false and will ignore <code>X</code>. This is called <em>short-circuit evaluation</em>.</p>
<p><a class="p_ident" id="p_WW6GFa4Qbm" href="#p_WW6GFa4Qbm" tabindex="-1" role="presentation"></a>The conditional operator works in a similar way. Of the second and third values, only the one that is selected is evaluated.</p>
<h2><a class="h_ident" id="h_ErccPg/l98" href="#h_ErccPg/l98" tabindex="-1" role="presentation"></a>Summary</h2>
<p><a class="p_ident" id="p_K8XmHEfEpW" href="#p_K8XmHEfEpW" tabindex="-1" role="presentation"></a>We looked at four types of JavaScript values in this chapter: numbers, strings, Booleans, and undefined values.</p>
<p><a class="p_ident" id="p_3rwX3Mq/e/" href="#p_3rwX3Mq/e/" tabindex="-1" role="presentation"></a>Such values are created by typing in their name (<code>true</code>, <code>null</code>) or value (<code>13</code>, <code>"abc"</code>). You can combine and transform values with operators. We saw binary operators for arithmetic (<code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, and <code>%</code>), string concatenation (<code>+</code>), comparison (<code>==</code>, <code>!=</code>, <code>===</code>, <code>!==</code>, <code><</code>, <code>></code>, <code><=</code>, <code>>=</code>), and logic (<code>&&</code>, <code>||</code>), as well as several unary operators (<code>-</code> to negate a number, <code>!</code> to negate logically, and <code>typeof</code> to find a value’s type) and a ternary operator (<code>?:</code>) to pick one of two values based on a third value.</p>
<p><a class="p_ident" id="p_WHkzsJyNsJ" href="#p_WHkzsJyNsJ" tabindex="-1" role="presentation"></a>This gives you enough information to use JavaScript as a pocket calculator but not much more. The <a href="02_program_structure.html">next chapter</a> will start tying these expressions together into basic programs.</p><nav><a href="00_intro.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a> <a href="02_program_structure.html" title="next chapter">▶</a></nav>
</article>