- Introduction
- Chapter 1 Values, Types, and Operators
- Chapter 2 Program Structure
- Expressions and statements
- Variables
- Keywords and reserved words
- The environment
- Functions
- The console.log function
- Return values
- prompt and confirm
- Control flow
- Conditional execution
- while and do loops
- Indenting Code
- for loops
- Breaking Out of a Loop
- Updating variables succinctly
- Dispatching on a value with switch
- Capitalization
- Comments
- Summary
- Exercises
- Chapter 3 Functions
- Chapter 4 Data Structures: Objects and Arrays
- Chapter 5 Higher-Order Functions
- Chapter 6 The Secret Life of Objects
- Chapter 7 Project: Electronic Life
- Chapter 8 Bugs and Error Handling
- Chapter 9 Regular Expressions
- Creating a regular expression
- Testing for matches
- Matching a set of characters
- Repeating parts of a pattern
- Grouping subexpressions
- Matches and groups
- The date type
- Word and string boundaries
- Choice patterns
- The mechanics of matching
- Backtracking
- The replace method
- Greed
- Dynamically creating RegExp objects
- The search method
- The lastIndex property
- Parsing an INI file
- International characters
- Summary
- Exercises
- Chapter 10 Modules
- Chapter 11 Project: A Programming Language
- Chapter 12 JavaScript and the Browser
- Chapter 13 The Document Object Model
- Chapter 14 Handling Events
- Chapter 15 Project: A Platform Game
- Chapter 16 Drawing on Canvas
- Chapter 17 HTTP
- Chapter 18 Forms and Form Fields
- Chapter 19 Project: A Paint Program
- Chapter 20 Node.js
- Chapter 21 Project: Skill-Sharing Website
- Eloquent JavaScript
- Exercise Hints
- Program Structure
- Functions
- Data Structures: Objects and Arrays
- Higher-Order Functions
- The Secret Life of Objects
- Project: Electronic Life
- Bugs and Error Handling
- Regular Expressions
- Modules
- Project: A Programming Language
- The Document Object Model
- Handling Events
- Project: A Platform Game
- Drawing on Canvas
- HTTP
- Forms and Form Fields
- Project: A Paint Program
- Node.js
- Project: Skill-Sharing Website
Automatic type conversion
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:
console.log(8 * null) // → 0 console.log("5" - 1) // → 4 console.log("5" + 1) // → 51 console.log("five" * 2) // → NaN console.log(false == 0) // → true
When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it wants, using a set of rules that often aren’t what you want or expect. This is called type coercion. So the null
in the first expression becomes 0
, and the "5"
in the second expression becomes 5
(from string to number). Yet in the third expression, +
tries string concatenation before numeric addition, so the 1
is converted to "1"
(from number to string).
When something that doesn’t map to a number in an obvious way (such as "five"
or undefined
) is converted to a number, the value NaN
is produced. Further arithmetic operations on NaN
keep producing NaN
, so if you find yourself getting one of those in an unexpected place, look for accidental type conversions.
When comparing values of the same type using ==
, the outcome is easy to predict: you should get true when both values are the same, except in the case of NaN
. 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 null
or undefined
occurs on either side of the operator, it produces true only if both sides are one of null
or undefined
.
console.log(null == undefined); // → true console.log(null == 0); // → false
That last piece of behavior is often useful. When you want to test whether a value has a real value instead of null
or undefined
, you can simply compare it to null
with the ==
(or !=
) operator.
But what if you want to test whether something refers to the precise value false
? The rules for converting strings and numbers to Boolean values state that 0
, NaN
, and the empty string ( ""
) count as false
, while all the other values count as true
. Because of this, expressions like 0 == false
and "" == false
are also true. For cases like this, where you do not want any automatic type conversions to happen, there are two extra operators: ===
and !==
. The first tests whether a value is precisely equal to the other, and the second tests whether it is not precisely equal. So "" === false
is false as expected.
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.
Short-circuiting of logical operators
The logical operators &&
and ||
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 return either the original left-hand value or the right-hand value.
The ||
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 conversion works as you’d expect for Boolean values and should do something analogous for values of other types.
console.log(null || "user") // → user console.log("Karl" || "user") // → Karl
This functionality allows the ||
operator to be used as a way to fall back on a default value. If you give it an expression that might produce an empty value on the left, the value on the right will be used as a replacement in that case.
The &&
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.
Another important property of these two operators is that the expression to their right is evaluated only when necessary. In the case of true || X
, no matter what X
is—even if it’s an expression that does something terrible—the result will be true, and X
is never evaluated. The same goes for false && X
, which is false and will ignore X
. This is called short-circuit evaluation.
The conditional operator works in a similar way. The first expression is always evaluated, but the second or third value, the one that is not picked, is not.
This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论