Javascript the good parts

Page 120

A bigger problem is testing a value for objectness. typeof cannot distinguish between null and objects, but you can because null is falsy and all objects are truthy: if (my_value && typeof my_value === 'object') { // my_value is an object or an array! }

Also see the later sections “NaN” and “Phony Arrays.” Implementations disagree on the type of regular expression objects. Some implementations report that: typeof /a/

is 'object', and others say that it is 'function'. It might have been more useful to report 'regexp', but the standard does not allow that.

parseInt parseInt is a function that converts a string into an integer. It stops when it sees a nondigit, so parseInt("16") and parseInt("16 tons") produce the same result. It

would be nice if the function somehow informed us about the extra text, but it doesn’t. If the first character of the string is 0, then the string is evaluated in base 8 instead of base 10. In base 8, 8 and 9 are not digits, so parseInt("08") and parseInt("09") produce 0 as their result. This error causes problems in programs that parse dates and times. Fortunately, parseInt can take a radix parameter, so that parseInt("08", 10) produces 8. I recommend that you always provide the radix parameter.

+ The + operator can add or concatenate. Which one it does depends on the types of the parameters. If either operand is an empty string, it produces the other operand converted to a string. If both operands are numbers, it produces the sum. Otherwise, it converts both operands to strings and concatenates them. This complicated behavior is a common source of bugs. If you intend + to add, make sure that both operands are numbers.

Floating Point Binary floating-point numbers are inept at handling decimal fractions, so 0.1 + 0.2 is not equal to 0.3. This is the most frequently reported bug in JavaScript, and it is an intentional consequence of having adopted the IEEE Standard for Binary FloatingPoint Arithmetic (IEEE 754). This standard is well-suited for many applications, but it violates most of the things you learned about numbers in middle school.

104

|

Appendix A: Awful Parts


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.