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
      2. Comments
      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
      14. Array.map()
      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()
      51. Date.now()
      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
      87. Error.name
      88. Error.toString()
      89. escape()
      90. eval()
      91. EvalError
      92. Function
      93. Function.apply()
      94. Function.arguments[]
      95. Function.bind()
      96. Function.call()
      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()
      175. RegExp.global
      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()
      192. String.search()
      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

Miscellaneous Operators

JavaScript supports a number of other miscellaneous operators, described in the following sections.

The Conditional Operator (?:)

The conditional operator is the only ternary operator (three operands) in JavaScript and is sometimes actually called the ternary operator. This operator is sometimes written ?:, although it does not appear quite that way in code. Because this operator has three operands, the first goes before the ?, the second goes between the ? and the :, and the third goes after the :. It is used like this:

x > 0 ? x : -x     // The absolute value of x

The operands of the conditional operator may be of any type. The first operand is evaluated and interpreted as a boolean. If the value of the first operand is truthy, then the second operand is evaluated, and its value is returned. Otherwise, if the first operand is falsy, then the third operand is evaluated and its value is returned. Only one of the second and third operands is evaluated, never both.

While you can achieve similar results using the if statement (if), the ?: operator often provides a handy shortcut. Here is a typical usage, which checks to be sure that a variable is defined (and has a meaningful, truthy value) and uses it if so or provides a default value if not:

greeting = "hello " + (username ? username : "there");

This is equivalent to, but more compact than, the following if statement:

greeting = "hello ";
if (username)
    greeting += username;
else
    greeting += "there";

The typeof Operator

typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string that specifies the type of the operand. The following table specifies the value of the typeof operator for any JavaScript value:

xtypeof x
undefined"undefined"
null"object"
true or false"boolean"
any number or NaN"number"
any string"string"
any function"function"
any nonfunction native object"object"
any host object

An implementation-defined string, but not “undefined”, “boolean”, “number”, or “string”.

You might use the typeof operator in an expression like this:

(typeof value == "string") ? "'" + value + "'" : value

The typeof operator is also useful when used with the switch statement (switch). Note that you can place parentheses around the operand to typeof, which makes typeof look like the name of a function rather than an operator keyword:

typeof(i)

Note that typeof returns “object” if the operand value is null. If you want to distinguish null from objects, you’ll have to explicitly test for this special-case value. typeof may return a string other than “object” for host objects. In practice, however, most host objects in client-side JavaScript have a type of “object”.

Because typeof evaluates to “object” for all object and array values other than functions, it is useful only to distinguish objects from other, primitive types. In order to distinguish one class of object from another, you must use other techniques, such as the instanceof operator (see The instanceof Operator), the class attribute (see The class Attribute), or the constructor property (see The prototype Attribute and The constructor Property).

Although functions in JavaScript are a kind of object, the typeof operator considers functions to be sufficiently different that they have their own return value. JavaScript makes a subtle distinction between functions and “callable objects.” All functions are callable, but it is possible to have a callable object—that can be invoked just like a function—that is not a true function. The ECMAScript 3 spec says that the typeof operator returns “function” for all native object that are callable. The ECMAScript 5 specification extends this to require that typeof return “function” for all callable objects, whether native objects or host objects. Most browser vendors use native JavaScript function objects for the methods of their host objects. Microsoft, however, has always used non-native callable objects for their client-side methods, and before IE 9 the typeof operator returns “object” for them, even though they behave like functions. In IE9 these client-side methods are now true native function objects. See Callable Objects for more on the distinction between true functions and callable objects.

The delete Operator

delete is an unary operator that attempts to delete the object property or array element specified as its operand.[3] Like the assignment, increment, and decrement operators, delete is typically used for its property deletion side effect, and not for the value it returns. Some examples:

var o = { x: 1, y: 2}; // Start with an object
delete o.x;            // Delete one of its properties
"x" in o               // => false: the property does not exist anymore

var a = [1,2,3];       // Start with an array
delete a[2];           // Delete the last element of the array
2 in a                 // => false: array element 2 doesn't exist anymore
a.lenth                // => 3: note that array length doesn't change, though

Note that a deleted property or array element is not merely set to the undefined value. When a property is deleted, the property ceases to exist. Attempting to read a nonexistent property returns undefined, but you can test for the actual existence of a property with the in operator (The in Operator). Deleting an array element leaves a “hole” in the array and does not change the array’s length. The resulting array is sparse.

delete expects its operand to be an lvalue. If it is not an lvalue, the operator takes no action and returns true. Otherwise, delete attempts to delete the specified lvalue. delete returns true if it successfully deletes the specified lvalue. Not all properties can be deleted, however: some built-in core and client-side properties are immune from deletion, and user-defined variables declared with the var statement cannot be deleted. Functions defined with the function statement and declared function parameters cannot be deleted either.

In ECMAScript 5 strict mode, delete raises a SyntaxError if its operand is an unqualified identifier such as a variable, function, or function parameter: it only works when the operand is a property access expression (Property Access Expressions). Strict mode also specifies that delete raises a TypeError if asked to delete any nonconfigurable property (see Property Attributes). Outside of strict mode, no exception occurs in these cases and delete simply returns false to indicate that the operand could not be deleted.

Here are some example uses of the delete operator:

var o = {x:1, y:2};  // Define a variable; initialize it to an object
delete o.x;          // Delete one of the object properties; returns true
typeof o.x;          // Property does not exist; returns "undefined"
delete o.x;          // Delete a nonexistent property; returns true
delete o;            // Can't delete a declared variable; returns false.
                     // Would raise an exception in strict mode.
delete 1;            // Argument is not an lvalue: returns true
this.x = 1;          // Define a property of the a global object without var
delete x;            // Try to delete it: returns true in non-strict mode
                     // Exception in strict mode. Use 'delete this.x' instead
x;                   // Runtime error: x is not defined

We’ll see the delete operator again in Deleting Properties.

The void Operator

void is a unary operator that appears before its single operand, which may be of any type. This operator is unusual and infrequently used: it evaluates its operand, then discards the value and returns undefined. Since the operand value is discarded, using the void operator makes sense only if the operand has side effects.

The most common use for this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side effects without the browser displaying the value of the evaluated expression. For example, you might use the void operator in an HTML <a> tag as follows:

<a href="javascript:void window.open();">Open New Window</a>

This HTML could be more cleanly written using an onclick event handler rather than a javascript: URL, of course, and the void operator would not be necessary in that case.

The Comma Operator (,)

The comma operator is a binary operator whose operands may be of any type. It evaluates its left operand, evaluates its right operand, and then returns the value of the right operand. Thus, the following line:

i=0, j=1, k=2;

evaluates to 2 and is basically equivalent to:

i = 0; j = 1; k = 2;

The left-hand expression is always evaluated, but its value is discarded, which means that it only makes sense to use the comma operator when the left-hand expression has side effects. The only situation in which the comma operator is commonly used is with a for loop (for) that has multiple loop variables:

// The first comma below is part of the syntax of the var statement
// The second comma is the comma operator: it lets us squeeze 2
// expressions (i++ and j--) into a statement (the for loop) that expects 1.
for(var i=0,j=10; i < j; i++,j--)
    console.log(i+j);


[3] If you are a C++ programmer, note that the delete keyword in JavaScript is nothing like the delete keyword in C++. In JavaScript, memory deallocation is handled automatically by garbage collection, and you never have to worry about explicitly freeing up memory. Thus, there is no need for a C++-style delete to delete entire objects.

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