JavaScript Notes For Professionals
JavaScript Notes For Professionals
JavaScript
Notes for Professionals
®
400+ pages
of professional hints and tricks
Disclaimer
[Link] This is an unocial free book created for educational purposes and is
not aliated with ocial JavaScript® group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with JavaScript ..................................................................................................... 2
Section 1.1: Using [Link]() ..................................................................................................................................... 2
Section 1.2: Using the DOM API .................................................................................................................................... 4
Section 1.3: Using [Link]() .................................................................................................................................. 5
Section 1.4: Using [Link]() ............................................................................................................................. 6
Section 1.5: Using [Link]firm() ............................................................................................................................ 7
Section 1.6: Using the DOM API (with graphical text: Canvas, SVG, or image file) ................................................. 8
Chapter 2: JavaScript Variables ......................................................................................................................... 10
Section 2.1: Defining a Variable ................................................................................................................................. 10
Section 2.2: Using a Variable ..................................................................................................................................... 10
Section 2.3: Types of Variables .................................................................................................................................. 10
Section 2.4: Arrays and Objects ................................................................................................................................ 11
Chapter 3: Built-in Constants ................................................................................................................................ 12
Section 3.1: null ............................................................................................................................................................. 12
Section 3.2: Testing for NaN using isNaN() .............................................................................................................. 12
Section 3.3: NaN .......................................................................................................................................................... 13
Section 3.4: undefined and null .................................................................................................................................. 14
Section 3.5: Infinity and -Infinity ................................................................................................................................. 15
Section 3.6: Number constants .................................................................................................................................. 15
Section 3.7: Operations that return NaN ................................................................................................................... 16
Section 3.8: Math library functions that return NaN ................................................................................................ 16
Chapter 4: Datatypes in JavaScript ................................................................................................................. 17
Section 4.1: typeof ....................................................................................................................................................... 17
Section 4.2: Finding an object's class ........................................................................................................................ 18
Section 4.3: Getting object type by constructor name ............................................................................................ 18
Chapter 5: Arithmetic (Math) ................................................................................................................................ 21
Section 5.1: Constants ................................................................................................................................................. 21
Section 5.2: Remainder / Modulus (%) ..................................................................................................................... 21
Section 5.3: Rounding ................................................................................................................................................. 22
Section 5.4: Trigonometry .......................................................................................................................................... 24
Section 5.5: Bitwise operators .................................................................................................................................... 25
Section 5.6: Incrementing (++) ................................................................................................................................... 27
Section 5.7: Exponentiation ([Link]() or **) ......................................................................................................... 27
Section 5.8: Random Integers and Floats ................................................................................................................. 28
Section 5.9: Addition (+) .............................................................................................................................................. 29
Section 5.10: Little / Big endian for typed arrays when using bitwise operators ................................................. 29
Section 5.11: Get Random Between Two Numbers .................................................................................................. 30
Section 5.12: Simulating events with dierent probabilities .................................................................................... 31
Section 5.13: Subtraction (-) ........................................................................................................................................ 32
Section 5.14: Multiplication (*) ..................................................................................................................................... 32
Section 5.15: Getting maximum and minimum ......................................................................................................... 32
Section 5.16: Restrict Number to Min/Max Range ................................................................................................... 33
Section 5.17: Ceiling and Floor .................................................................................................................................... 33
Section 5.18: Getting roots of a number .................................................................................................................... 34
Section 5.19: Random with gaussian distribution ..................................................................................................... 34
Section 5.20: Math.atan2 to find direction ................................................................................................................ 35
Section 5.21: Sin & Cos to create a vector given direction & distance ................................................................... 35
Section 5.22: [Link] ............................................................................................................................................ 36
Section 5.23: Periodic functions using [Link] ........................................................................................................ 37
Section 5.24: Division (/) ............................................................................................................................................. 38
Section 5.25: Decrementing (--) ................................................................................................................................ 38
Chapter 6: Bitwise operators ................................................................................................................................ 40
Section 6.1: Bitwise operators ..................................................................................................................................... 40
Section 6.2: Shift Operators ........................................................................................................................................ 42
Chapter 7: Strings ....................................................................................................................................................... 43
Section 7.1: Basic Info and String Concatenation ..................................................................................................... 43
Section 7.2: Reverse String ......................................................................................................................................... 44
Section 7.3: Comparing Strings Lexicographically ................................................................................................... 45
Section 7.4: Access character at index in string ....................................................................................................... 46
Section 7.5: Escaping quotes ...................................................................................................................................... 46
Section 7.6: Word Counter .......................................................................................................................................... 47
Section 7.7: Trim whitespace ...................................................................................................................................... 47
Section 7.8: Splitting a string into an array .............................................................................................................. 47
Section 7.9: Strings are unicode ................................................................................................................................. 48
Section 7.10: Detecting a string .................................................................................................................................. 48
Section 7.11: Substrings with slice ............................................................................................................................... 49
Section 7.12: Character code ...................................................................................................................................... 49
Section 7.13: String Representations of Numbers .................................................................................................... 49
Section 7.14: String Find and Replace Functions ...................................................................................................... 50
Section 7.15: Find the index of a substring inside a string ....................................................................................... 51
Section 7.16: String to Upper Case ............................................................................................................................. 51
Section 7.17: String to Lower Case ............................................................................................................................. 52
Section 7.18: Repeat a String ...................................................................................................................................... 52
Chapter 8: Date ........................................................................................................................................................... 53
Section 8.1: Create a new Date object ....................................................................................................................... 53
Section 8.2: Convert to a string format .................................................................................................................... 55
Section 8.3: Creating a Date from UTC ..................................................................................................................... 56
Section 8.4: Formatting a JavaScript date ............................................................................................................... 59
Section 8.5: Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC ................................. 61
Section 8.6: Get the current time and date ............................................................................................................... 61
Section 8.7: Increment a Date Object ....................................................................................................................... 62
Section 8.8: Convert to JSON ..................................................................................................................................... 63
Chapter 9: Date Comparison ................................................................................................................................ 64
Section 9.1: Comparing Date values .......................................................................................................................... 64
Section 9.2: Date Dierence Calculation .................................................................................................................. 65
Chapter 10: Comparison Operations ................................................................................................................ 66
Section 10.1: Abstract equality / inequality and type conversion ........................................................................... 66
Section 10.2: NaN Property of the Global Object ..................................................................................................... 67
Section 10.3: Short-circuiting in boolean operators ................................................................................................. 69
Section 10.4: Null and Undefined ............................................................................................................................... 71
Section 10.5: Abstract Equality (==) ........................................................................................................................... 71
Section 10.6: Logic Operators with Booleans ........................................................................................................... 72
Section 10.7: Automatic Type Conversions ............................................................................................................... 73
Section 10.8: Logic Operators with Non-boolean values (boolean coercion) ....................................................... 73
Section 10.9: Empty Array ........................................................................................................................................... 74
Section 10.10: Equality comparison operations ........................................................................................................ 74
Section 10.11: Relational operators (<, <=, >, >=) ........................................................................................................ 76
Section 10.12: Inequality .............................................................................................................................................. 77
Section 10.13: List of Comparison Operators ............................................................................................................ 78
Section 10.14: Grouping multiple logic statements ................................................................................................... 78
Section 10.15: Bit fields to optimise comparison of multi state data ...................................................................... 78
Chapter 11: Constructor functions ...................................................................................................................... 80
Section 11.1: Declaring a constructor function .......................................................................................................... 80
Chapter 12: Conditions .............................................................................................................................................. 81
Section 12.1: Ternary operators .................................................................................................................................. 81
Section 12.2: Switch statement ................................................................................................................................... 82
Section 12.3: If / Else If / Else Control ........................................................................................................................ 84
Section 12.4: Strategy .................................................................................................................................................. 85
Section 12.5: Using || and && short circuiting ............................................................................................................ 86
Chapter 13: Comments ............................................................................................................................................. 87
Section 13.1: Using Comments .................................................................................................................................... 87
Section 13.2: Using HTML comments in JavaScript (Bad practice) ....................................................................... 87
Chapter 14: Arrays ..................................................................................................................................................... 89
Section 14.1: Converting Array-like Objects to Arrays ............................................................................................. 89
Section 14.2: Reducing values .................................................................................................................................... 91
Section 14.3: Mapping values ..................................................................................................................................... 93
Section 14.4: Filtering Object Arrays .......................................................................................................................... 93
Section 14.5: Sorting Arrays ........................................................................................................................................ 95
Section 14.6: Iteration .................................................................................................................................................. 97
Section 14.7: Destructuring an array ....................................................................................................................... 101
Section 14.8: Removing duplicate elements ........................................................................................................... 102
Section 14.9: Array comparison ............................................................................................................................... 102
Section 14.10: Reversing arrays ................................................................................................................................ 103
Section 14.11: Shallow cloning an array ................................................................................................................... 104
Section 14.12: Concatenating Arrays ....................................................................................................................... 104
Section 14.13: Merge two array as key value pair .................................................................................................. 106
Section 14.14: Array spread / rest ............................................................................................................................ 106
Section 14.15: Filtering values ................................................................................................................................... 107
Section 14.16: Searching an Array ............................................................................................................................ 108
Section 14.17: Convert a String to an Array ............................................................................................................ 109
Section 14.18: Removing items from an array ........................................................................................................ 109
Section 14.19: Removing all elements ...................................................................................................................... 110
Section 14.20: Finding the minimum or maximum element .................................................................................. 111
Section 14.21: Standard array initialization ............................................................................................................. 112
Section 14.22: Joining array elements in a string .................................................................................................. 113
Section 14.23: Removing/Adding elements using splice() .................................................................................... 114
Section 14.24: The entries() method ........................................................................................................................ 114
Section 14.25: Remove value from array ................................................................................................................ 114
Section 14.26: Flattening Arrays ............................................................................................................................... 115
Section 14.27: Append / Prepend items to Array ................................................................................................... 116
Section 14.28: Object keys and values to array ..................................................................................................... 116
Section 14.29: Logical connective of values ........................................................................................................... 117
Section 14.30: Checking if an object is an Array .................................................................................................... 117
Section 14.31: Insert an item into an array at a specific index .............................................................................. 118
Section 14.32: Sorting multidimensional array ....................................................................................................... 118
Section 14.33: Test all array items for equality ...................................................................................................... 119
Section 14.34: Copy part of an Array ...................................................................................................................... 119
Chapter 15: Objects .................................................................................................................................................. 121
Section 15.1: Shallow cloning .................................................................................................................................... 121
Section 15.2: [Link] ........................................................................................................................................ 121
Section 15.3: Object cloning ...................................................................................................................................... 122
Section 15.4: Object properties iteration ................................................................................................................. 123
Section 15.5: [Link] ....................................................................................................................................... 124
Section 15.6: Object rest/spread (...) ........................................................................................................................ 125
Section 15.7: [Link]fineProperty ......................................................................................................................... 125
Section 15.8: Accesor properties (get and set) ....................................................................................................... 126
Section 15.9: Dynamic / variable property names ................................................................................................ 126
Section 15.10: Arrays are Objects ............................................................................................................................. 127
Section 15.11: [Link] ........................................................................................................................................... 128
Section 15.12: Convert object's values to array ...................................................................................................... 129
Section 15.13: Retrieving properties from an object .............................................................................................. 129
Section 15.14: Read-Only property .......................................................................................................................... 132
Section 15.15: Non enumerable property ................................................................................................................ 132
Section 15.16: Lock property description ................................................................................................................. 132
Section 15.17: [Link] ................................................................................................... 133
Section 15.18: Descriptors and Named Properties ................................................................................................. 133
Section 15.19: [Link] ......................................................................................................................................... 135
Section 15.20: Properties with special characters or reserved words ................................................................. 135
Section 15.21: Creating an Iterable object ............................................................................................................... 136
Section 15.22: Iterating over Object entries - [Link]() .............................................................................. 136
Section 15.23: [Link]() ................................................................................................................................... 137
Chapter 16: Declarations and Assignments ................................................................................................ 138
Section 16.1: Modifying constants ............................................................................................................................ 138
Section 16.2: Declaring and initializing constants .................................................................................................. 138
Section 16.3: Declaration ........................................................................................................................................... 138
Section 16.4: Undefined ............................................................................................................................................. 139
Section 16.5: Data Types ........................................................................................................................................... 139
Section 16.6: Mathematic operations and assignment .......................................................................................... 139
Section 16.7: Assignment .......................................................................................................................................... 141
Chapter 17: Loops ..................................................................................................................................................... 142
Section 17.1: Standard "for" loops ............................................................................................................................ 142
Section 17.2: "for ... of" loop ...................................................................................................................................... 143
Section 17.3: "for ... in" loop ....................................................................................................................................... 145
Section 17.4: "while" Loops ....................................................................................................................................... 145
Section 17.5: "continue" a loop ................................................................................................................................. 146
Section 17.6: Break specific nested loops ............................................................................................................... 147
Section 17.7: "do ... while" loop .................................................................................................................................. 147
Section 17.8: Break and continue labels .................................................................................................................. 147
Chapter 18: Functions ............................................................................................................................................. 149
Section 18.1: Function Scoping .................................................................................................................................. 149
Section 18.2: Currying ............................................................................................................................................... 150
Section 18.3: Immediately Invoked Function Expressions ..................................................................................... 151
Section 18.4: Named Functions ................................................................................................................................ 152
Section 18.5: Binding `this` and arguments ............................................................................................................. 155
Section 18.6: Functions with an Unknown Number of Arguments (variadic functions) ..................................... 157
Section 18.7: Anonymous Function .......................................................................................................................... 158
Section 18.8: Default parameters ............................................................................................................................ 160
Section 18.9: Call and apply ..................................................................................................................................... 162
Section 18.10: Partial Application .............................................................................................................................. 163
Section 18.11: Passing arguments by reference or value ....................................................................................... 164
Section 18.12: Function Arguments, "arguments" object, rest and spread parameters .................................... 165
Section 18.13: Function Composition ........................................................................................................................ 165
Section 18.14: Get the name of a function object ................................................................................................... 166
Section 18.15: Recursive Function ............................................................................................................................. 166
Section 18.16: Using the Return Statement ............................................................................................................. 167
Section 18.17: Functions as a variable ..................................................................................................................... 168
Chapter 19: Functional JavaScript ................................................................................................................... 171
Section 19.1: Higher-Order Functions ....................................................................................................................... 171
Section 19.2: Identity Monad .................................................................................................................................... 171
Section 19.3: Pure Functions ..................................................................................................................................... 173
Section 19.4: Accepting Functions as Arguments .................................................................................................. 174
Chapter 20: Prototypes, objects ....................................................................................................................... 176
Section 20.1: Creation and initialising Prototype .................................................................................................... 176
Chapter 21: Classes .................................................................................................................................................. 178
Section 21.1: Class Constructor ................................................................................................................................. 178
Section 21.2: Class Inheritance ................................................................................................................................. 178
Section 21.3: Static Methods ..................................................................................................................................... 179
Section 21.4: Getters and Setters ............................................................................................................................. 179
Section 21.5: Private Members ................................................................................................................................. 180
Section 21.6: Methods ................................................................................................................................................ 181
Section 21.7: Dynamic Method Names .................................................................................................................... 181
Section 21.8: Managing Private Data with Classes ................................................................................................ 182
Section 21.9: Class Name binding ............................................................................................................................ 184
Chapter 22: Namespacing .................................................................................................................................... 185
Section 22.1: Namespace by direct assignment .................................................................................................... 185
Section 22.2: Nested Namespaces .......................................................................................................................... 185
Chapter 23: Callbacks ............................................................................................................................................. 186
Section 23.1: Simple Callback Usage Examples ..................................................................................................... 186
Section 23.2: Continuation (synchronous and asynchronous) ............................................................................. 187
Section 23.3: What is a callback? ............................................................................................................................ 188
Section 23.4: Callbacks and `this` ............................................................................................................................. 189
Section 23.5: Callback using Arrow function .......................................................................................................... 190
Section 23.6: Error handling and control-flow branching ..................................................................................... 191
Chapter 24: Context (this) .................................................................................................................................... 192
Section 24.1: this with simple objects ....................................................................................................................... 192
Section 24.2: Saving this for use in nested functions / objects ............................................................................ 192
Section 24.3: Binding function context .................................................................................................................... 193
Section 24.4: this in constructor functions .............................................................................................................. 194
Chapter 25: Setters and Getters ...................................................................................................................... 195
Section 25.1: Defining a Setter/Getter Using [Link]fineProperty ................................................................... 195
Section 25.2: Defining an Setter/Getter in a Newly Created Object ................................................................... 195
Section 25.3: Defining getters and setters in ES6 class ......................................................................................... 195
Chapter 26: Events ................................................................................................................................................... 197
Section 26.1: Page, DOM and Browser loading ...................................................................................................... 197
Chapter 27: Inheritance ......................................................................................................................................... 198
Section 27.1: Standard function prototype ............................................................................................................. 198
Section 27.2: Dierence between [Link] and [Link] ............................................................ 198
Section 27.3: Prototypal inheritance ....................................................................................................................... 198
Section 27.4: Pseudo-classical inheritance ............................................................................................................. 199
Section 27.5: Setting an Object's prototype ........................................................................................................... 200
Chapter 28: Method Chaining ............................................................................................................................. 202
Section 28.1: Chainable object design and chaining .............................................................................................. 202
Section 28.2: Method Chaining ................................................................................................................................ 204
Chapter 29: Intervals and Timeouts ............................................................................................................... 205
Section 29.1: Recursive setTimeout ......................................................................................................................... 205
Section 29.2: Intervals ............................................................................................................................................... 205
Section 29.3: Intervals ............................................................................................................................................... 205
Section 29.4: Removing intervals ............................................................................................................................ 206
Section 29.5: Removing timeouts ............................................................................................................................ 206
Section 29.6: setTimeout, order of operations, clearTimeout .............................................................................. 206
Chapter 30: Console ................................................................................................................................................ 208
Section 30.1: Measuring time - [Link]() ........................................................................................................ 211
Section 30.2: Formatting console output ................................................................................................................ 212
Section 30.3: Printing to a browser's debugging console ..................................................................................... 213
Section 30.4: Including a stack trace when logging - [Link]() ................................................................. 215
Section 30.5: Tabulating values - [Link]() .................................................................................................. 215
Section 30.6: Counting - [Link]() ................................................................................................................ 217
Section 30.7: Clearing the console - [Link]() .............................................................................................. 219
Section 30.8: Displaying objects and XML interactively - [Link](), [Link]() .................................. 219
Section 30.9: Debugging with assertions - [Link]() ................................................................................. 221
Chapter 31: Regular expressions ....................................................................................................................... 222
Section 31.1: Creating a RegExp Object ................................................................................................................... 222
Section 31.2: RegExp Flags ....................................................................................................................................... 222
Section 31.3: Check if string contains pattern using .test() .................................................................................... 223
Section 31.4: Matching With .exec() ......................................................................................................................... 223
Section 31.5: Using RegExp With Strings ................................................................................................................. 223
Section 31.6: RegExp Groups .................................................................................................................................... 224
Section 31.7: Replacing string match with a callback function ............................................................................. 225
Section 31.8: Using [Link]() with parentheses regex to extract matches of a string ................................ 226
Chapter 32: Cookies ................................................................................................................................................. 228
Section 32.1: Test if cookies are enabled ................................................................................................................ 228
Section 32.2: Adding and Setting Cookies .............................................................................................................. 228
Section 32.3: Reading cookies ................................................................................................................................. 228
Section 32.4: Removing cookies .............................................................................................................................. 228
Chapter 33: Data attributes ................................................................................................................................ 229
Section 33.1: Accessing data attributes ................................................................................................................... 229
Chapter 34: JSON ..................................................................................................................................................... 230
Section 34.1: JSON versus JavaScript literals ......................................................................................................... 230
Section 34.2: Parsing with a reviver function ......................................................................................................... 231
Section 34.3: Serializing a value ............................................................................................................................... 232
Section 34.4: Serializing and restoring class instances ......................................................................................... 233
Section 34.5: Serializing with a replacer function .................................................................................................. 234
Section 34.6: Parsing a simple JSON string ............................................................................................................ 235
Section 34.7: Cyclic object values ............................................................................................................................ 235
Chapter 35: AJAX ...................................................................................................................................................... 236
Section 35.1: Sending and Receiving JSON Data via POST .................................................................................. 236
Section 35.2: Add an AJAX preloader ..................................................................................................................... 236
Section 35.3: Displaying the top JavaScript questions of the month from Stack Overflow's API .................... 237
Section 35.4: Using GET with parameters ............................................................................................................... 238
Section 35.5: Check if a file exists via a HEAD request .......................................................................................... 239
Section 35.6: Using GET and no parameters .......................................................................................................... 239
Section 35.7: Listening to AJAX events at a global level ....................................................................................... 239
Chapter 36: Enumerations ................................................................................................................................... 240
Section 36.1: Enum definition using [Link]() ............................................................................................... 240
Section 36.2: Alternate definition ............................................................................................................................. 240
Section 36.3: Printing an enum variable ................................................................................................................. 240
Section 36.4: Implementing Enums Using Symbols ............................................................................................... 241
Section 36.5: Automatic Enumeration Value .......................................................................................................... 241
Chapter 37: Map ........................................................................................................................................................ 243
Section 37.1: Creating a Map .................................................................................................................................... 243
Section 37.2: Clearing a Map ................................................................................................................................... 243
Section 37.3: Removing an element from a Map ................................................................................................... 243
Section 37.4: Checking if a key exists in a Map ...................................................................................................... 244
Section 37.5: Iterating Maps ..................................................................................................................................... 244
Section 37.6: Getting and setting elements ............................................................................................................ 244
Section 37.7: Getting the number of elements of a Map ...................................................................................... 245
Chapter 38: Timestamps ....................................................................................................................................... 246
Section 38.1: High-resolution timestamps ............................................................................................................... 246
Section 38.2: Get Timestamp in Seconds ................................................................................................................ 246
Section 38.3: Low-resolution timestamps ............................................................................................................... 246
Section 38.4: Support for legacy browsers ............................................................................................................ 246
Chapter 39: Unary Operators ............................................................................................................................ 247
Section 39.1: Overview ............................................................................................................................................... 247
Section 39.2: The typeof operator ........................................................................................................................... 247
Section 39.3: The delete operator ........................................................................................................................... 248
Section 39.4: The unary plus operator (+) .............................................................................................................. 249
Section 39.5: The void operator ............................................................................................................................... 250
Section 39.6: The unary negation operator (-) ...................................................................................................... 251
Section 39.7: The bitwise NOT operator (~) ............................................................................................................ 251
Section 39.8: The logical NOT operator (!) ............................................................................................................. 252
Chapter 40: Error Handling ................................................................................................................................ 254
Section 40.1: Error objects ........................................................................................................................................ 254
Section 40.2: Interaction with Promises .................................................................................................................. 254
Section 40.3: Error types .......................................................................................................................................... 255
Section 40.4: Order of operations plus advanced thoughts ................................................................................. 255
Chapter 41: Generators ......................................................................................................................................... 258
Section 41.1: Generator Functions ............................................................................................................................ 258
Section 41.2: Sending Values to Generator ............................................................................................................. 259
Section 41.3: Delegating to other Generator .......................................................................................................... 259
Section 41.4: Iteration ................................................................................................................................................ 259
Section 41.5: Async flow with generators ................................................................................................................ 260
Section 41.6: Iterator-Observer interface ................................................................................................................ 261
Chapter 42: Promises ............................................................................................................................................. 263
Section 42.1: Introduction .......................................................................................................................................... 263
Section 42.2: Promise chaining ................................................................................................................................ 264
Section 42.3: Waiting for multiple concurrent promises ....................................................................................... 265
Section 42.4: Reduce an array to chained promises ............................................................................................ 266
Section 42.5: Waiting for the first of multiple concurrent promises .................................................................... 267
Section 42.6: "Promisifying" functions with callbacks ........................................................................................... 268
Section 42.7: Error Handling .................................................................................................................................... 268
Section 42.8: Reconciling synchronous and asynchronous operations .............................................................. 272
Section 42.9: Delay function call .............................................................................................................................. 273
Section 42.10: "Promisifying" values ........................................................................................................................ 273
Section 42.11: Using ES2017 async/await ................................................................................................................ 274
Section 42.12: Performing cleanup with finally() .................................................................................................... 274
Section 42.13: forEach with promises ...................................................................................................................... 275
Section 42.14: Asynchronous API request ............................................................................................................... 275
Chapter 43: Async functions (async/await) ............................................................................................... 277
Section 43.1: Introduction .......................................................................................................................................... 277
Section 43.2: Await and operator precedence ....................................................................................................... 277
Section 43.3: Async functions compared to Promises .......................................................................................... 278
Section 43.4: Looping with async await .................................................................................................................. 279
Section 43.5: Less indentation .................................................................................................................................. 280
Section 43.6: Simultaneous async (parallel) operations ....................................................................................... 281
Chapter 44: Set ......................................................................................................................................................... 282
Section 44.1: Creating a Set ...................................................................................................................................... 282
Section 44.2: Adding a value to a Set ..................................................................................................................... 282
Section 44.3: Removing value from a set ............................................................................................................... 282
Section 44.4: Checking if a value exist in a set ....................................................................................................... 283
Section 44.5: Clearing a Set ..................................................................................................................................... 283
Section 44.6: Getting set length ............................................................................................................................... 283
Section 44.7: Converting Sets to arrays .................................................................................................................. 283
Section 44.8: Intersection and dierence in Sets ................................................................................................... 284
Section 44.9: Iterating Sets ....................................................................................................................................... 284
Chapter 45: Modals - Prompts .......................................................................................................................... 285
Section 45.1: About User Prompts ........................................................................................................................... 285
Section 45.2: Persistent Prompt Modal ................................................................................................................... 285
Section 45.3: Confirm to Delete element ................................................................................................................ 286
Section 45.4: Usage of alert() .................................................................................................................................. 286
Section 45.5: Usage of prompt() ............................................................................................................................. 287
Chapter 46: execCommand and contenteditable ................................................................................... 288
Section 46.1: Listening to Changes of contenteditable .......................................................................................... 289
Section 46.2: Getting started .................................................................................................................................... 289
Section 46.3: Copy to clipboard from textarea using execCommand("copy") .................................................. 290
Section 46.4: Formatting .......................................................................................................................................... 290
Chapter 47: History ................................................................................................................................................. 292
Section 47.1: [Link]() .............................................................................................................................. 292
Section 47.2: [Link]() ........................................................................................................................ 292
Section 47.3: Load a specific URL from the history list ......................................................................................... 292
Chapter 48: Navigator Object ........................................................................................................................... 294
Section 48.1: Get some basic browser data and return it as a JSON object ...................................................... 294
Chapter 49: BOM (Browser Object Model) .................................................................................................. 295
Section 49.1: Introduction .......................................................................................................................................... 295
Section 49.2: Window Object Properties ................................................................................................................. 295
Section 49.3: Window Object Methods .................................................................................................................... 296
Chapter 50: The Event Loop ............................................................................................................................... 297
Section 50.1: The event loop in a web browser ...................................................................................................... 297
Section 50.2: Asynchronous operations and the event loop ................................................................................ 298
Chapter 51: Strict mode ......................................................................................................................................... 299
Section 51.1: For entire scripts .................................................................................................................................. 299
Section 51.2: For functions ........................................................................................................................................ 299
Section 51.3: Changes to properties ........................................................................................................................ 299
Section 51.4: Changes to global properties ............................................................................................................ 300
Section 51.5: Duplicate Parameters ......................................................................................................................... 301
Section 51.6: Function scoping in strict mode ......................................................................................................... 301
Section 51.7: Behaviour of a function's arguments list .......................................................................................... 301
Section 51.8: Non-Simple parameter lists ............................................................................................................... 302
Chapter 52: Custom Elements ............................................................................................................................ 304
Section 52.1: Extending Native Elements ................................................................................................................ 304
Section 52.2: Registering New Elements ................................................................................................................ 304
Chapter 53: Data Manipulation ......................................................................................................................... 305
Section 53.1: Format numbers as money ............................................................................................................... 305
Section 53.2: Extract extension from file name ...................................................................................................... 305
Section 53.3: Set object property given its string name ....................................................................................... 306
Chapter 54: Binary Data ...................................................................................................................................... 307
Section 54.1: Getting binary representation of an image file ............................................................................... 307
Section 54.2: Converting between Blobs and ArrayBuers ................................................................................. 307
Section 54.3: Manipulating ArrayBuers with DataViews .................................................................................... 308
Section 54.4: Creating a TypedArray from a Base64 string ................................................................................ 308
Section 54.5: Using TypedArrays ............................................................................................................................ 309
Section 54.6: Iterating through an arrayBuer ...................................................................................................... 309
Chapter 55: Template Literals ........................................................................................................................... 311
Section 55.1: Basic interpolation and multiline strings ........................................................................................... 311
Section 55.2: Tagged strings .................................................................................................................................... 311
Section 55.3: Raw strings .......................................................................................................................................... 312
Section 55.4: Templating HTML With Template Strings ....................................................................................... 312
Section 55.5: Introduction ......................................................................................................................................... 313
Chapter 56: Fetch ..................................................................................................................................................... 314
Section 56.1: Getting JSON data .............................................................................................................................. 314
Section 56.2: Set Request Headers ......................................................................................................................... 314
Section 56.3: POST Data ........................................................................................................................................... 314
Section 56.4: Send cookies ....................................................................................................................................... 315
Section 56.5: GlobalFetch ......................................................................................................................................... 315
Section 56.6: Using Fetch to Display Questions from the Stack Overflow API ................................................... 315
Chapter 57: Scope .................................................................................................................................................... 316
Section 57.1: Closures ................................................................................................................................................ 316
Section 57.2: Hoisting ................................................................................................................................................ 317
Section 57.3: Dierence between var and let ........................................................................................................ 320
Section 57.4: Apply and Call syntax and invocation .............................................................................................. 322
Section 57.5: Arrow function invocation ................................................................................................................. 323
Section 57.6: Bound invocation ................................................................................................................................ 324
Section 57.7: Method invocation .............................................................................................................................. 324
Section 57.8: Anonymous invocation ...................................................................................................................... 325
Section 57.9: Constructor invocation ....................................................................................................................... 325
Section 57.10: Using let in loops instead of var (click handlers example) ........................................................... 325
Chapter 58: Modules ............................................................................................................................................... 327
Section 58.1: Defining a module ............................................................................................................................... 327
Section 58.2: Default exports ................................................................................................................................... 327
Section 58.3: Importing named members from another module ........................................................................ 328
Section 58.4: Importing an entire module .............................................................................................................. 328
Section 58.5: Importing named members with aliases ......................................................................................... 329
Section 58.6: Importing with side eects ................................................................................................................ 329
Section 58.7: Exporting multiple named members ................................................................................................ 329
Chapter 59: Screen .................................................................................................................................................. 330
Section 59.1: Getting the screen resolution ............................................................................................................. 330
Section 59.2: Getting the “available” area of the screen ....................................................................................... 330
Section 59.3: Page width and height ....................................................................................................................... 330
Section 59.4: Window innerWidth and innerHeight Properties ............................................................................ 330
Section 59.5: Getting color information about the screen .................................................................................... 330
Chapter 60: Variable coercion/conversion ................................................................................................. 331
Section 60.1: Double Negation (!!x) .......................................................................................................................... 331
Section 60.2: Implicit conversion ............................................................................................................................. 331
Section 60.3: Converting to boolean ....................................................................................................................... 331
Section 60.4: Converting a string to a number ...................................................................................................... 332
Section 60.5: Converting a number to a string ...................................................................................................... 333
Section 60.6: Primitive to Primitive conversion table ............................................................................................. 333
Section 60.7: Convert an array to a string ............................................................................................................. 333
Section 60.8: Array to String using array methods ............................................................................................... 334
Section 60.9: Converting a number to a boolean .................................................................................................. 334
Section 60.10: Converting a string to a boolean .................................................................................................... 334
Section 60.11: Integer to Float .................................................................................................................................. 334
Section 60.12: Float to Integer .................................................................................................................................. 335
Section 60.13: Convert string to float ...................................................................................................................... 335
Chapter 61: Destructuring assignment .......................................................................................................... 336
Section 61.1: Destructuring Objects .......................................................................................................................... 336
Section 61.2: Destructuring function arguments .................................................................................................... 337
Section 61.3: Nested Destructuring .......................................................................................................................... 337
Section 61.4: Destructuring Arrays ........................................................................................................................... 338
Section 61.5: Destructuring inside variables ........................................................................................................... 338
Section 61.6: Default Value While Destructuring .................................................................................................... 339
Section 61.7: Renaming Variables While Destructuring ......................................................................................... 339
Chapter 62: Web Storage ..................................................................................................................................... 340
Section 62.1: Using localStorage .............................................................................................................................. 340
Section 62.2: Simpler way of handling Storage ..................................................................................................... 340
Section 62.3: Storage events .................................................................................................................................... 341
Section 62.4: sessionStorage ................................................................................................................................... 342
Section 62.5: localStorage length ............................................................................................................................ 343
Section 62.6: Error conditions .................................................................................................................................. 343
Section 62.7: Clearing storage ................................................................................................................................. 343
Section 62.8: Remove Storage Item ........................................................................................................................ 343
Chapter 63: WebSockets ....................................................................................................................................... 344
Section 63.1: Working with string messages ........................................................................................................... 344
Section 63.2: Establish a web socket connection ................................................................................................... 344
Section 63.3: Working with binary messages ......................................................................................................... 344
Section 63.4: Making a secure web socket connection ......................................................................................... 345
Chapter 64: Arrow Functions .............................................................................................................................. 346
Section 64.1: Introduction .......................................................................................................................................... 346
Section 64.2: Lexical Scoping & Binding (Value of "this") ..................................................................................... 346
Section 64.3: Arguments Object .............................................................................................................................. 347
Section 64.4: Implicit Return ..................................................................................................................................... 347
Section 64.5: Arrow functions as a constructor ..................................................................................................... 348
Section 64.6: Explicit Return ..................................................................................................................................... 348
Chapter 65: Workers ............................................................................................................................................... 349
Section 65.1: Web Worker ......................................................................................................................................... 349
Section 65.2: A simple service worker ..................................................................................................................... 349
Section 65.3: Register a service worker .................................................................................................................. 350
Section 65.4: Communicating with a Web Worker ................................................................................................ 350
Section 65.5: Terminate a worker ............................................................................................................................ 351
Section 65.6: Populating your cache ....................................................................................................................... 352
Section 65.7: Dedicated Workers and Shared Workers ........................................................................................ 352
Chapter 66: Creational Design Patterns ....................................................................................................... 354
Section 66.1: Factory Functions ................................................................................................................................ 354
Section 66.2: Factory with Composition .................................................................................................................. 355
Section 66.3: Module and Revealing Module Patterns .......................................................................................... 356
Section 66.4: Prototype Pattern ............................................................................................................................... 358
Section 66.5: Singleton Pattern ................................................................................................................................ 359
Section 66.6: Abstract Factory Pattern ................................................................................................................... 360
Chapter 67: requestAnimationFrame ............................................................................................................ 361
Section 67.1: Use requestAnimationFrame to fade in element ............................................................................. 361
Section 67.2: Keeping Compatibility ........................................................................................................................ 362
Section 67.3: Cancelling an Animation .................................................................................................................... 362
Chapter 68: Global error handling in browsers ........................................................................................ 364
Section 68.1: Handling [Link] to report all errors back to the server-side ......................................... 364
Chapter 69: Tail Call Optimization ................................................................................................................... 366
Section 69.1: What is Tail Call Optimization (TCO) ................................................................................................ 366
Section 69.2: Recursive loops .................................................................................................................................. 366
Chapter 70: Detecting browser ......................................................................................................................... 367
Section 70.1: Feature Detection Method ................................................................................................................. 367
Section 70.2: User Agent Detection ......................................................................................................................... 367
Section 70.3: Library Method ................................................................................................................................... 368
Chapter 71: Symbols ................................................................................................................................................ 369
Section 71.1: Basics of symbol primitive type ......................................................................................................... 369
Section 71.2: Using [Link]() to create global, shared symbols ..................................................................... 369
Section 71.3: Converting a symbol into a string ..................................................................................................... 369
Chapter 72: Transpiling ......................................................................................................................................... 371
Section 72.1: Introduction to Transpiling ................................................................................................................. 371
Section 72.2: Start using ES6/7 with Babel ............................................................................................................. 372
Chapter 73: Unit Testing JavaScript ............................................................................................................... 373
Section 73.1: Unit Testing Promises with Mocha, Sinon, Chai and Proxyquire .................................................... 373
Section 73.2: Basic Assertion .................................................................................................................................... 375
Chapter 74: Debugging ......................................................................................................................................... 377
Section 74.1: Interactive interpreter variables ........................................................................................................ 377
Section 74.2: Breakpoints ......................................................................................................................................... 377
Section 74.3: Using setters and getters to find what changed a property ......................................................... 378
Section 74.4: Using the console ............................................................................................................................... 379
Section 74.5: Automatically pausing execution ...................................................................................................... 380
Section 74.6: Elements inspector ............................................................................................................................. 380
Section 74.7: Break when a function is called ........................................................................................................ 380
Section 74.8: Stepping through code ...................................................................................................................... 381
Chapter 75: Automatic Semicolon Insertion - ASI .................................................................................... 382
Section 75.1: Avoid semicolon insertion on return statements ............................................................................. 382
Section 75.2: Rules of Automatic Semicolon Insertion .......................................................................................... 382
Section 75.3: Statements aected by automatic semicolon insertion ................................................................ 383
Chapter 76: Localization ....................................................................................................................................... 385
Section 76.1: Number formatting ............................................................................................................................. 385
Section 76.2: Currency formatting .......................................................................................................................... 385
Section 76.3: Date and time formatting .................................................................................................................. 385
Chapter 77: Geolocation ....................................................................................................................................... 386
Section 77.1: Get updates when a user's location changes ................................................................................... 386
Section 77.2: Get a user's latitude and longitude ................................................................................................... 386
Section 77.3: More descriptive error codes ............................................................................................................ 386
Chapter 78: IndexedDB .......................................................................................................................................... 388
Section 78.1: Opening a database ........................................................................................................................... 388
Section 78.2: Adding objects .................................................................................................................................... 388
Section 78.3: Retrieving data ................................................................................................................................... 389
Section 78.4: Testing for IndexedDB availability .................................................................................................... 390
Chapter 79: Modularization Techniques ....................................................................................................... 391
Section 79.1: ES6 Modules ......................................................................................................................................... 391
Section 79.2: Universal Module Definition (UMD) .................................................................................................. 391
Section 79.3: Immediately invoked function expressions (IIFE) ........................................................................... 392
Section 79.4: Asynchronous Module Definition (AMD) .......................................................................................... 392
Section 79.5: CommonJS - [Link] ......................................................................................................................... 393
Chapter 80: Proxy .................................................................................................................................................... 395
Section 80.1: Proxying property lookup .................................................................................................................. 395
Section 80.2: Very simple proxy (using the set trap) ............................................................................................ 395
Chapter 81: .postMessage() and MessageEvent ....................................................................................... 397
Section 81.1: Getting Started ..................................................................................................................................... 397
Chapter 82: WeakMap ............................................................................................................................................ 400
Section 82.1: Creating a WeakMap object .............................................................................................................. 400
Section 82.2: Getting a value associated to the key ............................................................................................. 400
Section 82.3: Assigning a value to the key ............................................................................................................. 400
Section 82.4: Checking if an element with the key exists ...................................................................................... 400
Section 82.5: Removing an element with the key .................................................................................................. 401
Section 82.6: Weak reference demo ....................................................................................................................... 401
Chapter 83: WeakSet .............................................................................................................................................. 403
Section 83.1: Creating a WeakSet object ................................................................................................................ 403
Section 83.2: Adding a value .................................................................................................................................... 403
Section 83.3: Checking if a value exists ................................................................................................................... 403
Section 83.4: Removing a value ............................................................................................................................... 403
Chapter 84: Escape Sequences ......................................................................................................................... 404
Section 84.1: Entering special characters in strings and regular expressions .................................................... 404
Section 84.2: Escape sequence types ..................................................................................................................... 404
Chapter 85: Behavioral Design Patterns ...................................................................................................... 407
Section 85.1: Observer pattern ................................................................................................................................. 407
Section 85.2: Mediator Pattern ................................................................................................................................ 408
Section 85.3: Command ............................................................................................................................................ 409
Section 85.4: Iterator ................................................................................................................................................. 410
Chapter 86: Server-sent events ........................................................................................................................ 412
Section 86.1: Setting up a basic event stream to the server ................................................................................. 412
Section 86.2: Closing an event stream .................................................................................................................... 412
Section 86.3: Binding event listeners to EventSource ............................................................................................ 412
Chapter 87: Async Iterators ................................................................................................................................ 414
Section 87.1: Basics .................................................................................................................................................... 414
Chapter 88: How to make iterator usable inside async callback function ................................ 415
Section 88.1: Erroneous code, can you spot why this usage of key will lead to bugs? ...................................... 415
Section 88.2: Correct Writing ................................................................................................................................... 415
Chapter 89: Tilde ~ ................................................................................................................................................... 416
Section 89.1: ~ Integer ............................................................................................................................................... 416
Section 89.2: ~~ Operator ......................................................................................................................................... 416
Section 89.3: Converting Non-numeric values to Numbers .................................................................................. 417
Section 89.4: Shorthands .......................................................................................................................................... 417
Section 89.5: ~ Decimal ............................................................................................................................................. 417
Chapter 90: Bitwise Operators - Real World Examples (snippets) ................................................. 419
Section 90.1: Swapping Two Integers with Bitwise XOR (without additional memory allocation) ................... 419
Section 90.2: Faster multiplication or division by powers of 2 ............................................................................. 419
Section 90.3: Number's Parity Detection with Bitwise AND .................................................................................. 419
Chapter 91: Using JavaScript to get/set CSS custom variables ...................................................... 421
Section 91.1: How to get and set CSS variable property values ........................................................................... 421
Chapter 92: Selection API ..................................................................................................................................... 422
Section 92.1: Get the text of the selection ............................................................................................................... 422
Section 92.2: Deselect everything that is selected ................................................................................................ 422
Section 92.3: Select the contents of an element .................................................................................................... 422
Chapter 93: File API, Blobs and FileReaders ............................................................................................... 423
Section 93.1: Read file as string ................................................................................................................................ 423
Section 93.2: Read file as dataURL ......................................................................................................................... 423
Section 93.3: Slice a file ............................................................................................................................................. 424
Section 93.4: Get the properties of the file ............................................................................................................. 424
Section 93.5: Selecting multiple files and restricting file types ............................................................................. 425
Section 93.6: Client side csv download using Blob ................................................................................................ 425
Chapter 94: Notifications API ............................................................................................................................. 426
Section 94.1: Requesting Permission to send notifications ................................................................................... 426
Section 94.2: Sending Notifications ......................................................................................................................... 426
Section 94.3: Closing a notification .......................................................................................................................... 426
Section 94.4: Notification events ............................................................................................................................. 427
Chapter 95: Vibration API ..................................................................................................................................... 428
Section 95.1: Single vibration .................................................................................................................................... 428
Section 95.2: Check for support ............................................................................................................................... 428
Section 95.3: Vibration patterns .............................................................................................................................. 428
Chapter 96: Battery Status API ......................................................................................................................... 429
Section 96.1: Battery Events ..................................................................................................................................... 429
Section 96.2: Getting current battery level ............................................................................................................. 429
Section 96.3: Is battery charging? ........................................................................................................................... 429
Section 96.4: Get time left until battery is empty ................................................................................................... 429
Section 96.5: Get time left until battery is fully charged ....................................................................................... 429
Chapter 97: Fluent API ............................................................................................................................................ 430
Section 97.1: Fluent API capturing construction of HTML articles with JS ........................................................... 430
Chapter 98: Web Cryptography API ............................................................................................................... 432
Section 98.1: Creating digests (e.g. SHA-256) ......................................................................................................... 432
Section 98.2: Cryptographically random data ....................................................................................................... 432
Section 98.3: Generating RSA key pair and converting to PEM format .............................................................. 433
Section 98.4: Converting PEM key pair to CryptoKey ........................................................................................... 434
Chapter 99: Security issues ................................................................................................................................. 436
Section 99.1: Reflected Cross-site scripting (XSS) .................................................................................................. 436
Section 99.2: Persistent Cross-site scripting (XSS) ................................................................................................ 437
Section 99.3: Persistent Cross-site scripting from JavaScript string literals ....................................................... 438
Section 99.4: Why scripts from other people can harm your website and its visitors ...................................... 438
Section 99.5: Evaled JSON injection ........................................................................................................................ 439
Chapter 100: Same Origin Policy & Cross-Origin Communication ................................................... 441
Section 100.1: Safe cross-origin communication with messages ......................................................................... 441
Section 100.2: Ways to circumvent Same-Origin Policy ....................................................................................... 442
Chapter 101: Evaluating JavaScript ................................................................................................................ 444
Section 101.1: Evaluate a string of JavaScript statements .................................................................................... 444
Section 101.2: Introduction ........................................................................................................................................ 444
Section 101.3: Evaluation and Math .......................................................................................................................... 444
Chapter 102: Linters - Ensuring code quality ............................................................................................. 445
Section 102.1: JSHint .................................................................................................................................................. 445
Section 102.2: ESLint / JSCS ..................................................................................................................................... 446
Section 102.3: JSLint .................................................................................................................................................. 446
Chapter 103: Anti-patterns .................................................................................................................................. 447
Section 103.1: Chaining assignments in var declarations ...................................................................................... 447
Chapter 104: Performance Tips ........................................................................................................................ 448
Section 104.1: Avoid try/catch in performance-critical functions ......................................................................... 448
Section 104.2: Limit DOM Updates ........................................................................................................................... 448
Section 104.3: Benchmarking your code - measuring execution time ................................................................ 449
Section 104.4: Use a memoizer for heavy-computing functions ......................................................................... 451
Section 104.5: Initializing object properties with null .............................................................................................. 453
Section 104.6: Reuse objects rather than recreate ................................................................................................ 454
Section 104.7: Prefer local variables to globals, attributes, and indexed values ................................................ 455
Section 104.8: Be consistent in use of Numbers ..................................................................................................... 456
Chapter 105: Memory eciency ....................................................................................................................... 458
Section 105.1: Drawback of creating true private method .................................................................................... 458
Appendix A: Reserved Keywords ...................................................................................................................... 459
Section A.1: Reserved Keywords .............................................................................................................................. 459
Section A.2: Identifiers & Identifier Names ............................................................................................................. 461
Credits ............................................................................................................................................................................ 463
You may also like ...................................................................................................................................................... 474
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
[Link]
This JavaScript® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official JavaScript® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
All modern web browsers, [Link] as well as almost every other JavaScript environments support writing messages
to a console using a suite of logging methods. The most common of these methods is [Link]().
In a browser environment, the [Link]() function is predominantly used for debugging purposes.
Getting Started
Open up the JavaScript Console in your browser, type the following, and press Enter :
[Link]("Hello, World!");
In the example above, the [Link]() function prints Hello, World! to the console and returns undefined
(shown above in the console output window). This is because [Link]() has no explicit return value.
Logging variables
[Link]() can be used to log variables of any kind; not only strings. Just pass in the variable that you want to
be displayed in the console, for example:
Placeholders
Logging Objects
Below we see the result of logging an object. This is often useful for logging JSON responses from API calls.
[Link]({
'Email': '',
'Groups': {},
'Id': 33,
'IsHiddenInUI': false,
'IsSiteAdmin': false,
'LoginName': 'i:0#.w|virtualdomain\\user2',
'PrincipalType': 1,
You have the ability to log any element which exists within the DOM. In this case we log the body element:
[Link]([Link]);
End Note
For more information on the capabilities of the console, see the Console topic.
Setting the textContent property of an Element is one way to output text on a web page.
<p id="paragraph"></p>
This will select the element that with the id paragraph and set its text content to "Hello, World":
You can also use JavaScript to create a new HTML element programmatically. For example, consider an HTML
document with the following body:
<body>
<h1>Adding an element</h1>
</body>
In our JavaScript, we create a new <p> tag with a textContent property of and add it at the end of the html body:
<body>
<h1>Adding an element</h1>
<p>Hello, World</p>
</body>
Note that in order to manipulate elements in the DOM using JavaScript, the JavaScript code must be run after the
relevant element has been created in the document. This can be achieved by putting the JavaScript <script> tags
after all of your other <body> content. Alternatively, you can also use an event listener to listen to eg. window's
onload event, adding your code to that event listener will delay running your code until after the whole content on
your page has been loaded.
A third way to make sure all your DOM has been loaded, is to wrap the DOM manipulation code with a timeout
function of 0 ms. This way, this JavaScript code is re-queued at the end of the execution queue, which gives the
browser a chance to finish doing some non-JavaScript things that have been waiting to finish before attending to
this new piece of JavaScript.
[Link](message);
Because window is the global object, you can call also use the following shorthand:
alert(message);
So what does [Link]() do? Well, let's take the following example:
alert('hello, world');
Notes
The alert method is technically a property of window object, but since all window properties are
automatically global variables, we can use alert as a global variable instead of as a property of window -
meaning you can directly use alert() instead of [Link]().
Unlike using [Link], alert acts as a modal prompt meaning that the code calling alert will pause until the
prompt is answered. Traditionally this means that no other JavaScript code will execute until the alert is dismissed:
alert('Pause!');
[Link]('Alert was dismissed');
However the specification actually allows other event-triggered code to continue to execute even though a modal
dialog is still being shown. In such implementations, it is possible for other code to run while the modal dialog is
being shown.
More information about usage of the alert method can be found in the modals prompts topic.
The use of alerts is usually discouraged in favour of other methods that do not block users from interacting with the
page - in order to create a better user experience. Nevertheless, it can be useful for debugging.
Starting with Chrome 46.0, [Link]() is blocked inside an <iframe> unless its sandbox attribute has the value
allow-modal.
Syntax
prompt(text, [default]);
Examples
var age = prompt("How old are you?");
[Link](age); // Prints the value inserted by the user
The return value of prompt is always a string, unless the user clicks Cancel , in which that case it returns null.
Safari is an exception in that when the user clicks Cancel, the function returns an empty string. From there, you can
convert the return value to another type, such as an integer.
Notes
While the prompt box is displayed, the user is prevented from accessing other parts of the page, since dialog
boxes are modal windows.
Starting with Chrome 46.0 this method is blocked inside an <iframe> unless its sandbox attribute has the
value allow-modal.
result = [Link](message);
Here, message is the optional string to be displayed in the dialog and result is a boolean value indicating whether
OK or Cancel was selected (true means OK).
[Link]() is typically used to ask for user confirmation before doing a dangerous operation like deleting
something in a Control Panel:
The output of that code would look like this in the browser:
If you need it for later use, you can simply store the result of the user's interaction in a variable:
Notes
Section 1.6: Using the DOM API (with graphical text: Canvas,
SVG, or image file)
Using canvas elements
Then insert the canvas element into the page to take effect:
[Link](canvas);
Using SVG
SVG is for building scalable vector-based graphics and can be used within HTML.
Then build a text element with the desired positioning and font characteristics:
Finally add the text element to our svg container and add the svg container element to the HTML document:
[Link](text);
[Link](svg);
Image file
If you already have an image file containing the desired text and have it placed on a server, you can add the URL of
the image and then add the image to the document as follows:
Variables are what make up most of JavaScript. These variables make up things from numbers to objects, which are
all over JavaScript to make one's life much easier.
This is an example of defining variables. This variable is called a "string" because it has ASCII characters (A-Z, 0-9,
!@#$, etc.)
Here, we defined a number called "number1" which was equal to 5. However, on the second line, we changed the
value to 3. To show the value of a variable, we log it to the console or use [Link]():
[Link](number1); // 3
[Link](number1); // 3
number1 = number1 + 5; // 3 + 5 = 8
number1 = number1 - 6; // 8 - 6 = 2
var number2 = number1 * 10; // 2 (times) 10 = 20
var number3 = number2 / number1; // 20 (divided by) 2 = 10;
We can also add strings which will concatenate them, or put them together. For example:
[Link](myArray[elementNumber]); // Billy
An object is a group of values; unlike arrays, we can do something better than them:
myObject = {};
john = {firstname: "John", lastname: "Doe", fullname: "John Doe"};
billy = {
firstname: "Billy",
lastname: undefined,
fullname: "Billy"
};
[Link]([Link]); // John Doe
[Link]([Link]); // Billy
Rather than making an array ["John Doe", "Billy"] and calling myArray[0], we can just call [Link] and
[Link].
To properly check if a value is null, compare it with the strict equality operator
var a = null;
The global function isNaN() can be used to check if a certain value or expression evaluates to NaN. This function (in
short) first checks if the value is a number, if not tries to convert it (*), and then checks if the resulting value is NaN.
For this reason, this testing method may cause confusion.
(*) The "conversion" method is not that simple, see ECMA-262 18.2.3 for a detailed explanation of the algorithm.
These examples will help you better understand the isNaN() behavior:
isNaN(NaN); // true
isNaN(1); // false: 1 is a number
isNaN(-2e-4); // false: -2e-4 is a number (-0.0002) in scientific notation
isNaN(Infinity); // false: Infinity is a number
isNaN(true); // false: converted to 1, which is a number
isNaN(false); // false: converted to 0, which is a number
isNaN(null); // false: converted to 0, which is a number
isNaN(""); // false: converted to 0, which is a number
isNaN(" "); // false: converted to 0, which is a number
isNaN("45.3"); // false: string representing a number, converted to 45.3
isNaN("1.2e3"); // false: string representing a number, converted to 1.2e3
isNaN("Infinity"); // false: string representing a number, converted to Infinity
isNaN(new Date); // false: Date object, converted to milliseconds since epoch
isNaN("10$"); // true : conversion fails, the dollar sign is not a digit
isNaN("hello"); // true : conversion fails, no digits at all
isNaN(undefined); // true : converted to NaN
isNaN(); // true : converted to NaN (implicitly undefined)
isNaN(function(){}); // true : conversion fails
isNaN({}); // true : conversion fails
isNaN([1, 2]); // true : converted to "1, 2", which can't be converted to a number
This last one is a bit tricky: checking if an Array is NaN. To do this, the Number() constructor first converts the array
Version ≥ 6
[Link]()
In ECMAScript 6, the [Link]() function has been implemented primarily to avoid the problem of
[Link]() of forcefully converting the parameter to a number. [Link](), indeed, doesn't try to
convert the value to a number before testing. This also means that only values of the type number, that are
also NaN, return true (which basically means only [Link](NaN)).
When the [Link] is called with one argument number, the following steps are taken:
Some examples:
// Numbers
[Link](1); // false
[Link](-2e-4); // false
[Link](Infinity); // false
[Link]('NaN'); // true
NaN; // NaN
Don't check for NaN using the equality operator. See isNaN instead.
undefined is the absence of a value in the compiler, because where it should be a value, there hasn't been put one,
like the case of an unassigned variable.
Setting a variable to undefined means the variable effectively does not exist. Some processes, such as JSON
serialization, may strip undefined properties from objects. In contrast, null properties indicate will be preserved so
you can explicitly convey the concept of an "empty" property.
The value of a function argument that is declared but has been omitted from the function call
function foo(param) {
[Link]('is undefined?', param === undefined);
}
foo('a');
foo();
// is undefined? false
// is undefined? true