You are previewing JavaScript: The Definitive Guide, 6th Edition.

JavaScript: The Definitive Guide, 6th Edition

Cover of JavaScript: The Definitive Guide, 6th Edition by David Flanagan Published by O'Reilly Media, Inc.
  1. JavaScript: The Definitive Guide
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Preface
    1. Conventions Used in This Book
    2. Example Code
    3. Errata and How to Contact Us
    4. Acknowledgments
  5. 1. Introduction to JavaScript
    1. Core JavaScript
    2. Client-Side JavaScript
      1. Example: A JavaScript Loan Calculator
  6. I. Core JavaScript
    1. 2. Lexical Structure
      1. Character Set
      3. Literals
      4. Identifiers and Reserved Words
      5. Optional Semicolons
    2. 3. Types, Values, and Variables
      1. Numbers
      2. Text
      3. Boolean Values
      4. null and undefined
      5. The Global Object
      6. Wrapper Objects
      7. Immutable Primitive Values and Mutable Object References
      8. Type Conversions
      9. Variable Declaration
      10. Variable Scope
    3. 4. Expressions and Operators
      1. Primary Expressions
      2. Object and Array Initializers
      3. Function Definition Expressions
      4. Property Access Expressions
      5. Invocation Expressions
      6. Object Creation Expressions
      7. Operator Overview
      8. Arithmetic Expressions
      9. Relational Expressions
      10. Logical Expressions
      11. Assignment Expressions
      12. Evaluation Expressions
      13. Miscellaneous Operators
    4. 5. Statements
      1. Expression Statements
      2. Compound and Empty Statements
      3. Declaration Statements
      4. Conditionals
      5. Loops
      6. Jumps
      7. Miscellaneous Statements
      8. Summary of JavaScript Statements
    5. 6. Objects
      1. Creating Objects
      2. Querying and Setting Properties
      3. Deleting Properties
      4. Testing Properties
      5. Enumerating Properties
      6. Property Getters and Setters
      7. Property Attributes
      8. Object Attributes
      9. Serializing Objects
      10. Object Methods
    6. 7. Arrays
      1. Creating Arrays
      2. Reading and Writing Array Elements
      3. Sparse Arrays
      4. Array Length
      5. Adding and Deleting Array Elements
      6. Iterating Arrays
      7. Multidimensional Arrays
      8. Array Methods
      9. ECMAScript 5 Array Methods
      10. Array Type
      11. Array-Like Objects
      12. Strings As Arrays
    7. 8. Functions
      1. Defining Functions
      2. Invoking Functions
      3. Function Arguments and Parameters
      4. Functions As Values
      5. Functions As Namespaces
      6. Closures
      7. Function Properties, Methods, and Constructor
      8. Functional Programming
    8. 9. Classes and Modules
      1. Classes and Prototypes
      2. Classes and Constructors
      3. Java-Style Classes in JavaScript
      4. Augmenting Classes
      5. Classes and Types
      6. Object-Oriented Techniques in JavaScript
      7. Subclasses
      8. Classes in ECMAScript 5
      9. Modules
    9. 10. Pattern Matching with Regular Expressions
      1. Defining Regular Expressions
      2. String Methods for Pattern Matching
      3. The RegExp Object
    10. 11. JavaScript Subsets and Extensions
      1. JavaScript Subsets
      2. Constants and Scoped Variables
      3. Destructuring Assignment
      4. Iteration
      5. Shorthand Functions
      6. Multiple Catch Clauses
      7. E4X: ECMAScript for XML
    11. 12. Server-Side JavaScript
      1. Scripting Java with Rhino
      2. Asynchronous I/O with Node
  7. II. Client-Side JavaScript
    1. 13. JavaScript in Web Browsers
      1. Client-Side JavaScript
      2. Embedding JavaScript in HTML
      3. Execution of JavaScript Programs
      4. Compatibility and Interoperability
      5. Accessibility
      6. Security
      7. Client-Side Frameworks
    2. 14. The Window Object
      1. Timers
      2. Browser Location and Navigation
      3. Browsing History
      4. Browser and Screen Information
      5. Dialog Boxes
      6. Error Handling
      7. Document Elements As Window Properties
      8. Multiple Windows and Frames
    3. 15. Scripting Documents
      1. Overview of the DOM
      2. Selecting Document Elements
      3. Document Structure and Traversal
      4. Attributes
      5. Element Content
      6. Creating, Inserting, and Deleting Nodes
      7. Example: Generating a Table of Contents
      8. Document and Element Geometry and Scrolling
      9. HTML Forms
      10. Other Document Features
    4. 16. Scripting CSS
      1. Overview of CSS
      2. Important CSS Properties
      3. Scripting Inline Styles
      4. Querying Computed Styles
      5. Scripting CSS Classes
      6. Scripting Stylesheets
    5. 17. Handling Events
      1. Types of Events
      2. Registering Event Handlers
      3. Event Handler Invocation
      4. Document Load Events
      5. Mouse Events
      6. Mousewheel Events
      7. Drag and Drop Events
      8. Text Events
      9. Keyboard Events
    6. 18. Scripted HTTP
      1. Using XMLHttpRequest
      2. HTTP by <script>: JSONP
      3. Comet with Server-Sent Events
    7. 19. The jQuery Library
      1. jQuery Basics
      2. jQuery Getters and Setters
      3. Altering Document Structure
      4. Handling Events with jQuery
      5. Animated Effects
      6. Ajax with jQuery
      7. Utility Functions
      8. jQuery Selectors and Selection Methods
      9. Extending jQuery with Plug-ins
      10. The jQuery UI Library
    8. 20. Client-Side Storage
      1. localStorage and sessionStorage
      2. Cookies
      3. IE userData Persistence
      4. Application Storage and Offline Webapps
    9. 21. Scripted Media and Graphics
      1. Scripting Images
      2. Scripting Audio and Video
      3. SVG: Scalable Vector Graphics
      4. Graphics in a <canvas>
    10. 22. HTML5 APIs
      1. Geolocation
      2. History Management
      3. Cross-Origin Messaging
      4. Web Workers
      5. Typed Arrays and ArrayBuffers
      6. Blobs
      7. The Filesystem API
      8. Client-Side Databases
      9. Web Sockets
  8. III. Core JavaScript Reference
    1. I. Core JavaScript Reference
      1. arguments[ ]
      2. Arguments
      3. Arguments.callee
      4. Arguments.length
      5. Array
      6. Array.concat()
      7. Array.every()
      8. Array.filter()
      9. Array.forEach()
      10. Array.indexOf()
      11. Array.join()
      12. Array.lastIndexOf()
      13. Array.length
      15. Array.pop()
      16. Array.push()
      17. Array.reduce()
      18. Array.reduceRight()
      19. Array.reverse()
      20. Array.shift()
      21. Array.slice()
      22. Array.some()
      23. Array.sort()
      24. Array.splice()
      25. Array.toLocaleString()
      26. Array.toString()
      27. Array.unshift()
      28. Boolean
      29. Boolean.toString()
      30. Boolean.valueOf()
      31. Date
      32. Date.getDate()
      33. Date.getDay()
      34. Date.getFullYear()
      35. Date.getHours()
      36. Date.getMilliseconds()
      37. Date.getMinutes()
      38. Date.getMonth()
      39. Date.getSeconds()
      40. Date.getTime()
      41. Date.getTimezoneOffset()
      42. Date.getUTCDate()
      43. Date.getUTCDay()
      44. Date.getUTCFullYear()
      45. Date.getUTCHours()
      46. Date.getUTCMilliseconds()
      47. Date.getUTCMinutes()
      48. Date.getUTCMonth()
      49. Date.getUTCSeconds()
      50. Date.getYear()
      52. Date.parse()
      53. Date.setDate()
      54. Date.setFullYear()
      55. Date.setHours()
      56. Date.setMilliseconds()
      57. Date.setMinutes()
      58. Date.setMonth()
      59. Date.setSeconds()
      60. Date.setTime()
      61. Date.setUTCDate()
      62. Date.setUTCFullYear()
      63. Date.setUTCHours()
      64. Date.setUTCMilliseconds()
      65. Date.setUTCMinutes()
      66. Date.setUTCMonth()
      67. Date.setUTCSeconds()
      68. Date.setYear()
      69. Date.toDateString()
      70. Date.toGMTString()
      71. Date.toISOString()
      72. Date.toJSON
      73. Date.toLocaleDateString()
      74. Date.toLocaleString()
      75. Date.toLocaleTimeString()
      76. Date.toString()
      77. Date.toTimeString()
      78. Date.toUTCString()
      79. Date.UTC()
      80. Date.valueOf()
      81. decodeURI()
      82. decodeURIComponent()
      83. encodeURI()
      84. encodeURIComponent()
      85. Error
      86. Error.message
      88. Error.toString()
      89. escape()
      90. eval()
      91. EvalError
      92. Function
      93. Function.apply()
      94. Function.arguments[]
      95. Function.bind()
      97. Function.caller
      98. Function.length
      99. Function.prototype
      100. Function.toString()
      101. Global
      102. Infinity
      103. isFinite()
      104. isNaN()
      105. JSON
      106. JSON.parse()
      107. JSON.stringify()
      108. Math
      109. Math.abs()
      110. Math.acos()
      111. Math.asin()
      112. Math.atan()
      113. Math.atan2()
      114. Math.ceil()
      115. Math.cos()
      116. Math.E
      117. Math.exp()
      118. Math.floor()
      119. Math.LN10
      120. Math.LN2
      121. Math.log()
      122. Math.LOG10E
      123. Math.LOG2E
      124. Math.max()
      125. Math.min()
      126. Math.PI
      127. Math.pow()
      128. Math.random()
      129. Math.round()
      130. Math.sin()
      131. Math.sqrt()
      132. Math.SQRT1_2
      133. Math.SQRT2
      134. Math.tan()
      135. NaN
      136. Number
      137. Number.MAX_VALUE
      138. Number.MIN_VALUE
      139. Number.NaN
      140. Number.NEGATIVE_INFINITY
      141. Number.POSITIVE_INFINITY
      142. Number.toExponential()
      143. Number.toFixed()
      144. Number.toLocaleString()
      145. Number.toPrecision()
      146. Number.toString()
      147. Number.valueOf()
      148. Object
      149. Object.constructor
      150. Object.create()
      151. Object.defineProperties()
      152. Object.defineProperty()
      153. Object.freeze()
      154. Object.getOwnPropertyDescriptor()
      155. Object.getOwnPropertyNames()
      156. Object.getPrototypeOf()
      157. Object.hasOwnProperty()
      158. Object.isExtensible()
      159. Object.isFrozen()
      160. Object.isPrototypeOf()
      161. Object.isSealed()
      162. Object.keys()
      163. Object.preventExtensions()
      164. Object.propertyIsEnumerable()
      165. Object.seal()
      166. Object.toLocaleString()
      167. Object.toString()
      168. Object.valueOf()
      169. parseFloat()
      170. parseInt()
      171. RangeError
      172. ReferenceError
      173. RegExp
      174. RegExp.exec()
      176. RegExp.ignoreCase
      177. RegExp.lastIndex
      178. RegExp.source
      179. RegExp.test()
      180. RegExp.toString()
      181. String
      182. String.charAt()
      183. String.charCodeAt()
      184. String.concat()
      185. String.fromCharCode()
      186. String.indexOf()
      187. String.lastIndexOf()
      188. String.length
      189. String.localeCompare()
      190. String.match()
      191. String.replace()
      193. String.slice()
      194. String.split()
      195. String.substr()
      196. String.substring()
      197. String.toLocaleLowerCase()
      198. String.toLocaleUpperCase()
      199. String.toLowerCase()
      200. String.toString()
      201. String.toUpperCase()
      202. String.trim()
      203. String.valueOf()
      204. SyntaxError
      205. TypeError
      206. undefined
      207. unescape()
      208. URIError
  9. IV. Client-Side JavaScript Reference
    1. II. Client-Side JavaScript Reference
      1. ApplicationCache
      2. ArrayBuffer
      3. ArrayBufferView
      4. Attr
      5. Audio
      6. BeforeUnloadEvent
      7. Blob
      8. BlobBuilder
      9. Button
      10. Canvas
      11. CanvasGradient
      12. CanvasPattern
      13. CanvasRenderingContext2D
      14. ClientRect
      15. CloseEvent
      16. Comment
      17. Console
      18. ConsoleCommandLine
      19. CSS2Properties
      20. CSSRule
      21. CSSStyleDeclaration
      22. CSSStyleSheet
      23. DataTransfer
      24. DataView
      25. Document
      26. DocumentFragment
      27. DocumentType
      28. DOMException
      29. DOMImplementation
      30. DOMSettableTokenList
      31. DOMTokenList
      32. Element
      33. ErrorEvent
      34. Event
      35. EventSource
      36. EventTarget
      37. FieldSet
      38. File
      39. FileError
      40. FileReader
      41. FileReaderSync
      42. Form
      43. FormControl
      44. FormData
      45. FormValidity
      46. Geocoordinates
      47. Geolocation
      48. GeolocationError
      49. Geoposition
      50. HashChangeEvent
      51. History
      52. HTMLCollection
      53. HTMLDocument
      54. HTMLElement
      55. HTMLFormControlsCollection
      56. HTMLOptionsCollection
      57. IFrame
      58. Image
      59. ImageData
      60. Input
      61. jQuery
      62. KeyEvent
      63. Label
      64. Link
      65. Location
      66. MediaElement
      67. MediaError
      68. MessageChannel
      69. MessageEvent
      70. MessagePort
      71. Meter
      72. MouseEvent
      73. Navigator
      74. Node
      75. NodeList
      76. Option
      77. Output
      78. PageTransitionEvent
      79. PopStateEvent
      80. ProcessingInstruction
      81. Progress
      82. ProgressEvent
      83. Screen
      84. Script
      85. Select
      86. Storage
      87. StorageEvent
      88. Style
      89. Table
      90. TableCell
      91. TableRow
      92. TableSection
      93. Text
      94. TextArea
      95. TextMetrics
      96. TimeRanges
      97. TypedArray
      98. URL
      99. Video
      100. WebSocket
      101. Window
      102. Worker
      103. WorkerGlobalScope
      104. WorkerLocation
      105. WorkerNavigator
      106. XMLHttpRequest
      107. XMLHttpRequestUpload
  10. Index
  11. About the Author
  12. Colophon
  13. Copyright
O'Reilly logo

Relational Expressions

This section describes JavaScript’s relational operators. These operators test for a relationship (such as “equals,” “less than,” or “property of”) between two values and return true or false depending on whether that relationship exists. Relational expressions always evaluate to a boolean value, and that value is often used to control the flow of program execution in if, while, and for statements (see Chapter 5). The subsections that follow document the equality and inequality operators, the comparison operators, and JavaScript’s other two relational operators, in and instanceof.

Equality and Inequality Operators

The == and === operators check whether two values are the same, using two different definitions of sameness. Both operators accept operands of any type, and both return true if their operands are the same and false if they are different. The === operator is known as the strict equality operator (or sometimes the identity operator), and it checks whether its two operands are “identical” using a strict definition of sameness. The == operator is known as the equality operator; it checks whether its two operands are “equal” using a more relaxed definition of sameness that allows type conversions.

JavaScript supports =, ==, and === operators. Be sure you understand the differences between these assignment, equality, and strict equality operators, and be careful to use the correct one when coding! Although it is tempting to read all three operators “equals,” it may help to reduce confusion if you read “gets or is assigned” for =, “is equal to” for ==, and “is strictly equal to” for ===.

The != and !== operators test for the exact opposite of the == and === operators. The != inequality operator returns false if two values are equal to each other according to == and returns true otherwise. The !== operator returns false if two values are strictly equal to each other and returns true otherwise. As you’ll see in Logical Expressions, the ! operator computes the Boolean NOT operation. This makes it easy to remember that != and !== stand for “not equal to” and “not strictly equal to.”

As mentioned in Immutable Primitive Values and Mutable Object References, JavaScript objects are compared by reference, not by value. An object is equal to itself, but not to any other object. If two distinct objects have the same number of properties, with the same names and values, they are still not equal. Two arrays that have the same elements in the same order are not equal to each other.

The strict equality operator === evaluates its operands, and then compares the two values as follows, performing no type conversion:

  • If the two values have different types, they are not equal.

  • If both values are null or both values are undefined, they are equal.

  • If both values are the boolean value true or both are the boolean value false, they are equal.

  • If one or both values is NaN, they are not equal. The NaN value is never equal to any other value, including itself! To check whether a value x is NaN, use x !== x. NaN is the only value of x for which this expression will be true.

  • If both values are numbers and have the same value, they are equal. If one value is 0 and the other is -0, they are also equal.

  • If both values are strings and contain exactly the same 16-bit values (see the sidebar in Text) in the same positions, they are equal. If the strings differ in length or content, they are not equal. Two strings may have the same meaning and the same visual appearance, but still be encoded using different sequences of 16-bit values. JavaScript performs no Unicode normalization, and a pair of strings like this are not considered equal to the === or to the == operators. See String.localeCompare() in Part III for another way to compare strings.

  • If both values refer to the same object, array, or function, they are equal. If they refer to different objects they are not equal, even if both objects have identical properties.

The equality operator == is like the strict equality operator, but it is less strict. If the values of the two operands are not the same type, it attempts some type conversions and tries the comparison again:

  • If the two values have the same type, test them for strict equality as described above. If they are strictly equal, they are equal. If they are not strictly equal, they are not equal.

  • If the two values do not have the same type, the == operator may still consider them equal. Use the following rules and type conversions to check for equality:

    • If one value is null and the other is undefined, they are equal.

    • If one value is a number and the other is a string, convert the string to a number and try the comparison again, using the converted value.

    • If either value is true, convert it to 1 and try the comparison again. If either value is false, convert it to 0 and try the comparison again.

    • If one value is an object and the other is a number or string, convert the object to a primitive using the algorithm described in Object to Primitive Conversions and try the comparison again. An object is converted to a primitive value by either its toString() method or its valueOf() method. The built-in classes of core JavaScript attempt valueOf() conversion before toString() conversion, except for the Date class, which performs toString() conversion. Objects that are not part of core JavaScript may convert themselves to primitive values in an implementation-defined way.

    • Any other combinations of values are not equal.

As an example of testing for equality, consider the comparison:

"1" == true

This expression evaluates to true, indicating that these very different-looking values are in fact equal. The boolean value true is first converted to the number 1, and the comparison is done again. Next, the string "1" is converted to the number 1. Since both values are now the same, the comparison returns true.

Comparison Operators

The comparison operators test the relative order (numerical or alphabetics) of their two operands:

Less than (<)

The < operator evaluates to true if its first operand is less than its second operand; otherwise it evaluates to false.

Greater than (>)

The > operator evaluates to true if its first operand is greater than its second operand; otherwise it evaluates to false.

Less than or equal (<=)

The <= operator evaluates to true if its first operand is less than or equal to its second operand; otherwise it evaluates to false.

Greater than or equal (>=)

The >= operator evaluates to true if its first operand is greater than or equal to its second operand; otherwise it evaluates to false.

The operands of these comparison operators may be of any type. Comparison can be performed only on numbers and strings, however, so operands that are not numbers or strings are converted. Comparison and conversion occur as follows:

  • If either operand evaluates to an object, that object is converted to a primitive value as described at the end of Object to Primitive Conversions: if its valueOf() method returns a primitive value, that value is used. Otherwise, the return value of its toString() method is used.

  • If, after any required object-to-primitive conversion, both operands are strings, the two strings are compared, using alphabetical order, where “alphabetical order” is defined by the numerical order of the 16-bit Unicode values that make up the strings.

  • If, after object-to-primitive conversion, at least one operand is not a string, both operands are converted to numbers and compared numerically. 0 and -0 are considered equal. Infinity is larger than any number other than itself, and -Infinity is smaller than any number other than itself. If either operand is (or converts to) NaN, then the comparison operator always returns false.

Remember that JavaScript strings are sequences of 16-bit integer values, and that string comparison is just a numerical comparison of the values in the two strings. The numerical encoding order defined by Unicode may not match the traditional collation order used in any particular language or locale. Note in particular that string comparison is case-sensitive, and all capital ASCII letters are “less than” all lowercase ASCII letters. This rule can cause confusing results if you do not expect it. For example, according to the < operator, the string “Zoo” comes before the string “aardvark”.

For a more robust string-comparison algorithm, see the String.localeCompare() method, which also takes locale-specific definitions of alphabetical order into account. For case-insensitive comparisons, you must first convert the strings to all lowercase or all uppercase using String.toLowerCase() or String.toUpperCase().

Both the + operator and the comparison operators behave differently for numeric and string operands. + favors strings: it performs concatenation if either operand is a string. The comparison operators favor numbers and only perform string comparison if both operands are strings:

1 + 2        // Addition. Result is 3.
"1" + "2"    // Concatenation. Result is "12".
"1" + 2      // Concatenation. 2 is converted to "2". Result is "12".
11 < 3       // Numeric comparison. Result is false.
"11" < "3"   // String comparison. Result is true.
"11" < 3     // Numeric comparison. "11" converted to 11. Result is false.
"one" < 3    // Numeric comparison. "one" converted to NaN. Result is false.

Finally, note that the <= (less than or equal) and >= (greater than or equal) operators do not rely on the equality or strict equality operators for determining whether two values are “equal.” Instead, the less-than-or-equal operator is simply defined as “not greater than,” and the greater-than-or-equal operator is defined as “not less than.” The one exception occurs when either operand is (or converts to) NaN, in which case all four comparison operators return false.

The in Operator

The in operator expects a left-side operand that is or can be converted to a string. It expects a right-side operand that is an object. It evaluates to true if the left-side value is the name of a property of the right-side object. For example:

var point = { x:1, y:1 };  // Define an object
"x" in point               // => true: object has property named "x"
"z" in point               // => false: object has no "z" property.
"toString" in point        // => true: object inherits toString method

var data = [7,8,9];        // An array with elements 0, 1, and 2
"0" in data                // => true: array has an element "0"
1 in data                  // => true: numbers are converted to strings
3 in data                  // => false: no element 3

The instanceof Operator

The instanceof operator expects a left-side operand that is an object and a right-side operand that identifies a class of objects. The operator evaluates to true if the left-side object is an instance of the right-side class and evaluates to false otherwise. Chapter 9 explains that, in JavaScript, classes of objects are defined by the constructor function that initializes them. Thus, the right-side operand of instanceof should be a function. Here are examples:

var d = new Date();  // Create a new object with the Date() constructor
d instanceof Date;   // Evaluates to true; d was created with Date()
d instanceof Object; // Evaluates to true; all objects are instances of Object
d instanceof Number; // Evaluates to false; d is not a Number object
var a = [1, 2, 3];   // Create an array with array literal syntax
a instanceof Array;  // Evaluates to true; a is an array
a instanceof Object; // Evaluates to true; all arrays are objects
a instanceof RegExp; // Evaluates to false; arrays are not regular expressions

Note that all objects are instances of Object. instanceof considers the “superclasses” when deciding whether an object is an instance of a class. If the left-side operand of instanceof is not an object, instanceof returns false. If the right-hand side is not a function, it throws a TypeError.

In order to understand how the instanceof operator works, you must understand the “prototype chain.” This is JavaScript’s inheritance mechanism, and it is described in Inheritance. To evaluate the expression o instanceof f, JavaScript evaluates f.prototype, and then looks for that value in the prototype chain of o. If it finds it, then o is an instance of f (or of a superclass of f) and the operator returns true. If f.prototype is not one of the values in the prototype chain of o, then o is not an instance of f and instanceof returns false.

The best content for your career. Discover unlimited learning on demand for around $1/day.