JavaScriptNotes_Bab1-5_RAW
JavaScriptNotes_Bab1-5_RAW
41
Section 7.8: Splitting a string into an array .............................................................................................................. 41
Section 7.9: Strings are unicode ................................................................................................................................. 42
Section 7.10: Detecting a string .................................................................................................................................. 42
Section 7.11: Substrings with slice ............................................................................................................................... 43
Section 7.12: Character code ...................................................................................................................................... 43
Section 7.13: String Representations of Numbers .................................................................................................... 43
Section 7.14: String Find and Replace Functions ...................................................................................................... 44
Section 7.15: Find the index of a substring inside a string ....................................................................................... 45
Section 7.16: String to Upper Case ............................................................................................................................. 45
Section 7.17: String to Lower Case ............................................................................................................................. 46
Section 7.18: Repeat a String ...................................................................................................................................... 46
Chapter 8: Date ........................................................................................................................................................... 47
Section 8.1: Create a new Date object ....................................................................................................................... 47
Section 8.2: Convert to a string format .................................................................................................................... 49
Section 8.3: Creating a Date from UTC ..................................................................................................................... 50
Section 8.4: Formatting a JavaScript date ............................................................................................................... 53
Section 8.5: Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC ................................. 55
Section 8.6: Get the current time and date ............................................................................................................... 55
Section 8.7: Increment a Date Object ....................................................................................................................... 56
Section 8.8: Convert to JSON ..................................................................................................................................... 57
Chapter 9: Date Comparison ................................................................................................................................ 58
Section 9.1: Comparing Date values .......................................................................................................................... 58
Section 9.2: Date Dierence Calculation .................................................................................................................. 59
Chapter 10: Comparison Operations ................................................................................................................ 60
Section 10.1: Abstract equality / inequality and type conversion ........................................................................... 60
Section 10.2: NaN Property of the Global Object ..................................................................................................... 61
Section 10.3: Short-circuiting in boolean operators ................................................................................................. 63
Section 10.4: Null and Undefined ............................................................................................................................... 65
Section 10.5: Abstract Equality (==) ........................................................................................................................... 65
Section 10.6: Logic Operators with Booleans ........................................................................................................... 66
Section 10.7: Automatic Type Conversions ............................................................................................................... 67
Section 10.8: Logic Operators with Non-boolean values (boolean coercion) ....................................................... 67
Section 10.9: Empty Array ........................................................................................................................................... 68
Section 10.10: Equality comparison operations ........................................................................................................ 68
Section 10.11: Relational operators (<, <=, >, >=) ........................................................................................................ 70
Section 10.12: Inequality .............................................................................................................................................. 71
Section 10.13: List of Comparison Operators ............................................................................................................ 72
Section 10.14: Grouping multiple logic statements ................................................................................................... 72
Section 10.15: Bit fields to optimise comparison of multi state data ...................................................................... 72
Chapter 11: Conditions .............................................................................................................................................. 74
Section 11.1: Ternary operators .................................................................................................................................. 74
Section 11.2: Switch statement .................................................................................................................................... 75
Section 11.3: If / Else If / Else Control ......................................................................................................................... 77
Section 11.4: Strategy ................................................................................................................................................... 78
Section 11.5: Using || and && short circuiting ............................................................................................................. 79
Chapter 12: Arrays ...................................................................................................................................................... 80
Section 12.1: Converting Array-like Objects to Arrays ............................................................................................. 80
Section 12.2: Reducing values .................................................................................................................................... 82
Section 12.3: Mapping values ..................................................................................................................................... 84
Section 12.4: Filtering Object Arrays .......................................................................................................................... 84
Section 12.5: Sorting Arrays ........................................................................................................................................ 86
Section 12.6: Iteration .................................................................................................................................................. 88
Section 12.7: Destructuring an array ......................................................................................................................... 92
Section 12.8: Removing duplicate elements ............................................................................................................. 93
Section 12.9: Array comparison ................................................................................................................................. 93
Section 12.10: Reversing arrays .................................................................................................................................. 94
Section 12.11: Shallow cloning an array ..................................................................................................................... 95
Section 12.12: Concatenating Arrays ......................................................................................................................... 95
Section 12.13: Merge two array as key value pair .................................................................................................... 97
Section 12.14: Array spread / rest .............................................................................................................................. 97
Section 12.15: Filtering values ..................................................................................................................................... 98
Section 12.16: Searching an Array .............................................................................................................................. 99
Section 12.17: Convert a String to an Array ............................................................................................................ 100
Section 12.18: Removing items from an array ........................................................................................................ 100
Section 12.19: Removing all elements ...................................................................................................................... 101
Section 12.20: Finding the minimum or maximum element .................................................................................. 102
Section 12.21: Standard array initialization ............................................................................................................. 103
Section 12.22: Joining array elements in a string .................................................................................................. 104
Section 12.23: Removing/Adding elements using splice() .................................................................................... 105
Section 12.24: The entries() method ........................................................................................................................ 105
Section 12.25: Remove value from array ................................................................................................................ 105
Section 12.26: Flattening Arrays .............................................................................................................................. 106
Section 12.27: Append / Prepend items to Array ................................................................................................... 107
Section 12.28: Object keys and values to array ..................................................................................................... 107
Section 12.29: Logical connective of values ........................................................................................................... 108
Section 12.30: Checking if an object is an Array .................................................................................................... 108
Section 12.31: Insert an item into an array at a specific index .............................................................................. 109
Section 12.32: Sorting multidimensional array ....................................................................................................... 109
Section 12.33: Test all array items for equality ...................................................................................................... 110
Section 12.34: Copy part of an Array ...................................................................................................................... 110
Chapter 13: Objects .................................................................................................................................................. 112
Section 13.1: Shallow cloning ..................................................................................................................................... 112
Section 13.2: Object.freeze ........................................................................................................................................ 112
Section 13.3: Object cloning ...................................................................................................................................... 113
Section 13.4: Object properties iteration ................................................................................................................. 114
Section 13.5: Object.assign ........................................................................................................................................ 115
Section 13.6: Object rest/spread (...) ........................................................................................................................ 116
Section 13.7: Object.defineProperty ......................................................................................................................... 116
Section 13.8: Accesor properties (get and set) ....................................................................................................... 117
Section 13.9: Dynamic / variable property names ................................................................................................ 117
Section 13.10: Arrays are Objects ............................................................................................................................. 118
Section 13.11: Object.seal ........................................................................................................................................... 119
Section 13.12: Convert object's values to array ...................................................................................................... 120
Section 13.13: Retrieving properties from an object ............................................................................................... 120
Section 13.14: Read-Only property ........................................................................................................................... 123
Section 13.15: Non enumerable property ................................................................................................................ 123
Section 13.16: Lock property description ................................................................................................................. 123
Section 13.17: Object.getOwnPropertyDescriptor ................................................................................................... 124
Section 13.18: Descriptors and Named Properties ................................................................................................. 124
Section 13.19: Object.keys ......................................................................................................................................... 126
Section 13.20: Properties with special characters or reserved words .................................................................. 126
Section 13.21: Creating an Iterable object ............................................................................................................... 127
Section 13.22: Iterating over Object entries - Object.entries() .............................................................................. 127
Section 13.23: Object.values() ................................................................................................................................... 128
Chapter 14: Arithmetic (Math) ........................................................................................................................... 129
Section 14.1: Constants .............................................................................................................................................. 129
Section 14.2: Remainder / Modulus (%) .................................................................................................................. 129
Section 14.3: Rounding .............................................................................................................................................. 130
Section 14.4: Trigonometry ....................................................................................................................................... 132
Section 14.5: Bitwise operators ................................................................................................................................ 133
Section 14.6: Incrementing (++) ................................................................................................................................ 135
Section 14.7: Exponentiation (Math.pow() or **) ..................................................................................................... 135
Section 14.8: Random Integers and Floats ............................................................................................................. 136
Section 14.9: Addition (+) .......................................................................................................................................... 137
Section 14.10: Little / Big endian for typed arrays when using bitwise operators .............................................. 137
Section 14.11: Get Random Between Two Numbers ............................................................................................... 138
Section 14.12: Simulating events with dierent probabilities ................................................................................. 139
Section 14.13: Subtraction (-) .................................................................................................................................... 140
Section 14.14: Multiplication (*) ................................................................................................................................. 140
Section 14.15: Getting maximum and minimum ..................................................................................................... 140
Section 14.16: Restrict Number to Min/Max Range ................................................................................................ 141
Section 14.17: Ceiling and Floor ................................................................................................................................ 141
Section 14.18: Getting roots of a number ................................................................................................................ 142
Section 14.19: Random with gaussian distribution ................................................................................................. 142
Section 14.20: Math.atan2 to find direction ............................................................................................................ 143
Section 14.21: Sin & Cos to create a vector given direction & distance ............................................................... 143
Section 14.22: Math.hypot ......................................................................................................................................... 144
Section 14.23: Periodic functions using Math.sin .................................................................................................... 145
Section 14.24: Division (/) ......................................................................................................................................... 146
Section 14.25: Decrementing (--) ............................................................................................................................. 146
Chapter 15: Bitwise operators ............................................................................................................................ 148
Section 15.1: Bitwise operators ................................................................................................................................. 148
Section 15.2: Shift Operators .................................................................................................................................... 150
Chapter 16: Constructor functions ................................................................................................................... 151
Section 16.1: Declaring a constructor function ........................................................................................................ 151
Chapter 17: Declarations and Assignments ................................................................................................ 152
Section 17.1: Modifying constants ............................................................................................................................ 152
Section 17.2: Declaring and initializing constants .................................................................................................. 152
Section 17.3: Declaration ........................................................................................................................................... 152
Section 17.4: Undefined ............................................................................................................................................. 153
Section 17.5: Data Types ........................................................................................................................................... 153
Section 17.6: Mathematic operations and assignment .......................................................................................... 153
Section 17.7: Assignment ........................................................................................................................................... 155
Chapter 18: Loops ..................................................................................................................................................... 156
Section 18.1: Standard "for" loops ............................................................................................................................ 156
Section 18.2: "for ... of" loop ...................................................................................................................................... 157
Section 18.3: "for ... in" loop ....................................................................................................................................... 159
Section 18.4: "while" Loops ....................................................................................................................................... 159
Section 18.5: "continue" a loop ................................................................................................................................. 160
Section 18.6: Break specific nested loops ............................................................................................................... 161
Section 18.7: "do ... while" loop .................................................................................................................................. 161
Section 18.8: Break and continue labels ................................................................................................................. 161
Chapter 19: Functions ............................................................................................................................................. 163
Section 19.1: Function Scoping .................................................................................................................................. 163
Section 19.2: Currying ................................................................................................................................................ 164
Section 19.3: Immediately Invoked Function Expressions ..................................................................................... 165
Section 19.4: Named Functions ................................................................................................................................ 166
Section 19.5: Binding `this` and arguments ............................................................................................................. 169
Section 19.6: Functions with an Unknown Number of Arguments (variadic functions) ..................................... 171
Section 19.7: Anonymous Function .......................................................................................................................... 172
Section 19.8: Default parameters ............................................................................................................................ 174
Section 19.9: Call and apply ...................................................................................................................................... 176
Section 19.10: Partial Application .............................................................................................................................. 177
Section 19.11: Passing arguments by reference or value ....................................................................................... 178
Section 19.12: Function Arguments, "arguments" object, rest and spread parameters .................................... 179
Section 19.13: Function Composition ........................................................................................................................ 179
Section 19.14: Get the name of a function object ................................................................................................... 180
Section 19.15: Recursive Function ............................................................................................................................. 180
Section 19.16: Using the Return Statement ............................................................................................................. 181
Section 19.17: Functions as a variable ..................................................................................................................... 182
Chapter 20: Functional JavaScript .................................................................................................................. 185
Section 20.1: Higher-Order Functions ...................................................................................................................... 185
Section 20.2: Identity Monad ................................................................................................................................... 185
Section 20.3: Pure Functions .................................................................................................................................... 187
Section 20.4: Accepting Functions as Arguments ................................................................................................. 188
Chapter 21: Prototypes, objects ........................................................................................................................ 190
Section 21.1: Creation and initialising Prototype ..................................................................................................... 190
Chapter 22: Classes ................................................................................................................................................. 192
Section 22.1: Class Constructor ................................................................................................................................ 192
Section 22.2: Class Inheritance ................................................................................................................................ 192
Section 22.3: Static Methods .................................................................................................................................... 193
Section 22.4: Getters and Setters ............................................................................................................................ 193
Section 22.5: Private Members ................................................................................................................................ 194
Section 22.6: Methods ............................................................................................................................................... 195
Section 22.7: Dynamic Method Names ................................................................................................................... 195
Section 22.8: Managing Private Data with Classes ............................................................................................... 196
Section 22.9: Class Name binding ........................................................................................................................... 198
Chapter 23: Namespacing .................................................................................................................................... 199
Section 23.1: Namespace by direct assignment .................................................................................................... 199
Section 23.2: Nested Namespaces .......................................................................................................................... 199
Chapter 24: Context (this) .................................................................................................................................... 200
Section 24.1: this with simple objects ....................................................................................................................... 200
Section 24.2: Saving this for use in nested functions / objects ............................................................................ 200
Section 24.3: Binding function context .................................................................................................................... 201
Section 24.4: this in constructor functions .............................................................................................................. 202
Chapter 25: Setters and Getters ...................................................................................................................... 203
Section 25.1: Defining a Setter/Getter Using Object.defineProperty ................................................................... 203
Section 25.2: Defining an Setter/Getter in a Newly Created Object ................................................................... 203
Section 25.3: Defining getters and setters in ES6 class ......................................................................................... 203
Chapter 26: Events ................................................................................................................................................... 205
Section 26.1: Page, DOM and Browser loading ...................................................................................................... 205
Chapter 27: Inheritance ......................................................................................................................................... 206
Section 27.1: Standard function prototype ............................................................................................................. 206
Section 27.2: Dierence between Object.key and Object.prototype.key ............................................................ 206
Section 27.3: Prototypal inheritance ....................................................................................................................... 206
Section 27.4: Pseudo-classical inheritance ............................................................................................................. 207
Section 27.5: Setting an Object's prototype ........................................................................................................... 208
Chapter 28: Method Chaining ............................................................................................................................. 210
Section 28.1: Chainable object design and chaining .............................................................................................. 210
Section 28.2: Method Chaining ................................................................................................................................ 212
Chapter 29: Callbacks ............................................................................................................................................. 213
Section 29.1: Simple Callback Usage Examples ..................................................................................................... 213
Section 29.2: Continuation (synchronous and asynchronous) ............................................................................ 214
Section 29.3: What is a callback? ............................................................................................................................ 215
Section 29.4: Callbacks and `this` ............................................................................................................................ 216
Section 29.5: Callback using Arrow function .......................................................................................................... 217
Section 29.6: Error handling and control-flow branching ..................................................................................... 218
Chapter 30: Intervals and Timeouts ............................................................................................................... 219
Section 30.1: Recursive setTimeout ......................................................................................................................... 219
Section 30.2: Intervals ............................................................................................................................................... 219
Section 30.3: Intervals ............................................................................................................................................... 219
Section 30.4: Removing intervals ............................................................................................................................ 220
Section 30.5: Removing timeouts ............................................................................................................................ 220
Section 30.6: setTimeout, order of operations, clearTimeout .............................................................................. 220
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 Regex.exec() 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: Web Storage ..................................................................................................................................... 229
Section 33.1: Using localStorage .............................................................................................................................. 229
Section 33.2: Simpler way of handling Storage ..................................................................................................... 229
Section 33.3: Storage events .................................................................................................................................... 230
Section 33.4: sessionStorage .................................................................................................................................... 231
Section 33.5: localStorage length ............................................................................................................................ 232
Section 33.6: Error conditions ................................................................................................................................... 232
Section 33.7: Clearing storage ................................................................................................................................. 232
Section 33.8: Remove Storage Item ........................................................................................................................ 232
Chapter 34: Data attributes ............................................................................................................................... 233
Section 34.1: Accessing data attributes ................................................................................................................... 233
Chapter 35: JSON ..................................................................................................................................................... 234
Section 35.1: JSON versus JavaScript literals ......................................................................................................... 234
Section 35.2: Parsing with a reviver function ......................................................................................................... 235
Section 35.3: Serializing a value ............................................................................................................................... 236
Section 35.4: Serializing and restoring class instances ......................................................................................... 237
Section 35.5: Serializing with a replacer function .................................................................................................. 238
Section 35.6: Parsing a simple JSON string ............................................................................................................ 239
Section 35.7: Cyclic object values ............................................................................................................................ 239
Chapter 36: AJAX ...................................................................................................................................................... 240
Section 36.1: Sending and Receiving JSON Data via POST .................................................................................. 240
Section 36.2: Add an AJAX preloader ..................................................................................................................... 240
Section 36.3: Displaying the top JavaScript questions of the month from Stack Overflow's API .................... 241
Section 36.4: Using GET with parameters ............................................................................................................... 242
Section 36.5: Check if a file exists via a HEAD request .......................................................................................... 243
Section 36.6: Using GET and no parameters .......................................................................................................... 243
Section 36.7: Listening to AJAX events at a global level ....................................................................................... 243
Chapter 37: Enumerations ................................................................................................................................... 244
Section 37.1: Enum definition using Object.freeze() ............................................................................................... 244
Section 37.2: Alternate definition ............................................................................................................................. 244
Section 37.3: Printing an enum variable ................................................................................................................. 244
Section 37.4: Implementing Enums Using Symbols ............................................................................................... 245
Section 37.5: Automatic Enumeration Value .......................................................................................................... 245
Chapter 38: Map ........................................................................................................................................................ 247
Section 38.1: Creating a Map .................................................................................................................................... 247
Section 38.2: Clearing a Map ................................................................................................................................... 247
Section 38.3: Removing an element from a Map .................................................................................................. 247
Section 38.4: Checking if a key exists in a Map ...................................................................................................... 248
Section 38.5: Iterating Maps ..................................................................................................................................... 248
Section 38.6: Getting and setting elements ............................................................................................................ 248
Section 38.7: Getting the number of elements of a Map ...................................................................................... 249
Chapter 39: Timestamps ....................................................................................................................................... 250
Section 39.1: High-resolution timestamps ............................................................................................................... 250
Section 39.2: Get Timestamp in Seconds ................................................................................................................ 250
Section 39.3: Low-resolution timestamps ............................................................................................................... 250
Section 39.4: Support for legacy browsers ............................................................................................................. 250
Chapter 40: Unary Operators ........................................................................................................................... 251
Section 40.1: Overview .............................................................................................................................................. 251
Section 40.2: The typeof operator .......................................................................................................................... 251
Section 40.3: The delete operator ........................................................................................................................... 252
Section 40.4: The unary plus operator (+) .............................................................................................................. 253
Section 40.5: The void operator .............................................................................................................................. 254
Section 40.6: The unary negation operator (-) ...................................................................................................... 255
Section 40.7: The bitwise NOT operator (~) ............................................................................................................ 255
Section 40.8: The logical NOT operator (!) ............................................................................................................. 256
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: Set .......................................................................................................................................................... 277
Section 43.1: Creating a Set ...................................................................................................................................... 277
Section 43.2: Adding a value to a Set ..................................................................................................................... 277
Section 43.3: Removing value from a set ............................................................................................................... 277
Section 43.4: Checking if a value exist in a set ....................................................................................................... 278
Section 43.5: Clearing a Set ...................................................................................................................................... 278
Section 43.6: Getting set length ............................................................................................................................... 278
Section 43.7: Converting Sets to arrays .................................................................................................................. 278
Section 43.8: Intersection and dierence in Sets ................................................................................................... 279
Section 43.9: Iterating Sets ....................................................................................................................................... 279
Chapter 44: Modals - Prompts .......................................................................................................................... 280
Section 44.1: About User Prompts ........................................................................................................................... 280
Section 44.2: Persistent Prompt Modal ................................................................................................................... 280
Section 44.3: Confirm to Delete element ................................................................................................................ 281
Section 44.4: Usage of alert() .................................................................................................................................. 281
Section 44.5: Usage of prompt() ............................................................................................................................. 282
Chapter 45: execCommand and contenteditable ................................................................................... 283
Section 45.1: Listening to Changes of contenteditable .......................................................................................... 284
Section 45.2: Getting started .................................................................................................................................... 284
Section 45.3: Copy to clipboard from textarea using execCommand("copy") .................................................. 285
Section 45.4: Formatting .......................................................................................................................................... 285
Chapter 46: History ................................................................................................................................................. 287
Section 46.1: history.pushState() .............................................................................................................................. 287
Section 46.2: history.replaceState() ........................................................................................................................ 287
Section 46.3: Load a specific URL from the history list ......................................................................................... 287
Chapter 47: Navigator Object ........................................................................................................................... 289
Section 47.1: Get some basic browser data and return it as a JSON object ...................................................... 289
Chapter 48: BOM (Browser Object Model) .................................................................................................. 290
Section 48.1: Introduction .......................................................................................................................................... 290
Section 48.2: Window Object Properties ................................................................................................................. 290
Section 48.3: Window Object Methods .................................................................................................................... 291
Chapter 49: The Event Loop ............................................................................................................................... 292
Section 49.1: The event loop in a web browser ...................................................................................................... 292
Section 49.2: Asynchronous operations and the event loop ................................................................................ 293
Chapter 50: Strict mode ....................................................................................................................................... 294
Section 50.1: For entire scripts ................................................................................................................................. 294
Section 50.2: For functions ....................................................................................................................................... 294
Section 50.3: Changes to properties ....................................................................................................................... 294
Section 50.4: Changes to global properties ........................................................................................................... 295
Section 50.5: Duplicate Parameters ........................................................................................................................ 296
Section 50.6: Function scoping in strict mode ........................................................................................................ 296
Section 50.7: Behaviour of a function's arguments list ......................................................................................... 296
Section 50.8: Non-Simple parameter lists .............................................................................................................. 297
Chapter 51: Custom Elements ............................................................................................................................ 299
Section 51.1: Extending Native Elements ................................................................................................................. 299
Section 51.2: Registering New Elements ................................................................................................................. 299
Chapter 52: Data Manipulation ......................................................................................................................... 300
Section 52.1: Format numbers as money ............................................................................................................... 300
Section 52.2: Extract extension from file name ..................................................................................................... 300
Section 52.3: Set object property given its string name ....................................................................................... 301
Chapter 53: Binary Data ....................................................................................................................................... 302
Section 53.1: Getting binary representation of an image file ............................................................................... 302
Section 53.2: Converting between Blobs and ArrayBuers ................................................................................. 302
Section 53.3: Manipulating ArrayBuers with DataViews ..................................................................................... 303
Section 53.4: Creating a TypedArray from a Base64 string ................................................................................. 303
Section 53.5: Using TypedArrays ............................................................................................................................. 304
Section 53.6: Iterating through an arrayBuer ...................................................................................................... 304
Chapter 54: Template Literals .......................................................................................................................... 306
Section 54.1: Basic interpolation and multiline strings ........................................................................................... 306
Section 54.2: Tagged strings ................................................................................................................................... 306
Section 54.3: Raw strings .......................................................................................................................................... 307
Section 54.4: Templating HTML With Template Strings ....................................................................................... 307
Section 54.5: Introduction ......................................................................................................................................... 308
Chapter 55: Fetch ..................................................................................................................................................... 309
Section 55.1: Getting JSON data .............................................................................................................................. 309
Section 55.2: Set Request Headers ......................................................................................................................... 309
Section 55.3: POST Data ........................................................................................................................................... 309
Section 55.4: Send cookies ....................................................................................................................................... 310
Section 55.5: GlobalFetch ......................................................................................................................................... 310
Section 55.6: Using Fetch to Display Questions from the Stack Overflow API ................................................... 310
Chapter 56: Scope .................................................................................................................................................... 311
Section 56.1: Closures ................................................................................................................................................ 311
Section 56.2: Hoisting ................................................................................................................................................ 312
Section 56.3: Dierence between var and let ........................................................................................................ 315
Section 56.4: Apply and Call syntax and invocation ............................................................................................. 317
Section 56.5: Arrow function invocation ................................................................................................................. 318
Section 56.6: Bound invocation ................................................................................................................................ 319
Section 56.7: Method invocation .............................................................................................................................. 319
Section 56.8: Anonymous invocation ...................................................................................................................... 320
Section 56.9: Constructor invocation ...................................................................................................................... 320
Section 56.10: Using let in loops instead of var (click handlers example) ........................................................... 320
Chapter 57: Modules ............................................................................................................................................... 322
Section 57.1: Defining a module ............................................................................................................................... 322
Section 57.2: Default exports ................................................................................................................................... 322
Section 57.3: Importing named members from another module ........................................................................ 323
Section 57.4: Importing an entire module .............................................................................................................. 323
Section 57.5: Importing named members with aliases ......................................................................................... 324
Section 57.6: Importing with side eects ................................................................................................................ 324
Section 57.7: Exporting multiple named members ................................................................................................ 324
Chapter 58: Screen .................................................................................................................................................. 325
Section 58.1: Getting the screen resolution ............................................................................................................. 325
Section 58.2: Getting the “available” area of the screen ...................................................................................... 325
Section 58.3: Page width and height ....................................................................................................................... 325
Section 58.4: Window innerWidth and innerHeight Properties ............................................................................ 325
Section 58.5: Getting color information about the screen .................................................................................... 325
Chapter 59: Variable coercion/conversion ................................................................................................. 326
Section 59.1: Double Negation (!!x) .......................................................................................................................... 326
Section 59.2: Implicit conversion ............................................................................................................................. 326
Section 59.3: Converting to boolean ....................................................................................................................... 326
Section 59.4: Converting a string to a number ...................................................................................................... 327
Section 59.5: Converting a number to a string ...................................................................................................... 328
Section 59.6: Primitive to Primitive conversion table ............................................................................................. 328
Section 59.7: Convert an array to a string ............................................................................................................. 328
Section 59.8: Array to String using array methods ............................................................................................... 329
Section 59.9: Converting a number to a boolean .................................................................................................. 329
Section 59.10: Converting a string to a boolean .................................................................................................... 329
Section 59.11: Integer to Float ................................................................................................................................... 329
Section 59.12: Float to Integer .................................................................................................................................. 330
Section 59.13: Convert string to float ....................................................................................................................... 330
Chapter 60: Destructuring assignment ......................................................................................................... 331
Section 60.1: Destructuring Objects ......................................................................................................................... 331
Section 60.2: Destructuring function arguments ................................................................................................... 332
Section 60.3: Nested Destructuring ......................................................................................................................... 332
Section 60.4: Destructuring Arrays .......................................................................................................................... 333
Section 60.5: Destructuring inside variables .......................................................................................................... 333
Section 60.6: Default Value While Destructuring ................................................................................................... 334
Section 60.7: Renaming Variables While Destructuring ........................................................................................ 334
Chapter 61: WebSockets ....................................................................................................................................... 335
Section 61.1: Working with string messages ........................................................................................................... 335
Section 61.2: Establish a web socket connection ................................................................................................... 335
Section 61.3: Working with binary messages ......................................................................................................... 335
Section 61.4: Making a secure web socket connection ......................................................................................... 336
Chapter 62: Arrow Functions .............................................................................................................................. 337
Section 62.1: Introduction .......................................................................................................................................... 337
Section 62.2: Lexical Scoping & Binding (Value of "this") ..................................................................................... 337
Section 62.3: Arguments Object .............................................................................................................................. 338
Section 62.4: Implicit Return ..................................................................................................................................... 338
Section 62.5: Arrow functions as a constructor ..................................................................................................... 339
Section 62.6: Explicit Return ..................................................................................................................................... 339
Chapter 63: Workers ............................................................................................................................................... 340
Section 63.1: Web Worker ......................................................................................................................................... 340
Section 63.2: A simple service worker ..................................................................................................................... 340
Section 63.3: Register a service worker .................................................................................................................. 341
Section 63.4: Communicating with a Web Worker ................................................................................................ 341
Section 63.5: Terminate a worker ............................................................................................................................ 342
Section 63.6: Populating your cache ....................................................................................................................... 343
Section 63.7: Dedicated Workers and Shared Workers ........................................................................................ 343
Chapter 64: requestAnimationFrame ............................................................................................................ 345
Section 64.1: Use requestAnimationFrame to fade in element ............................................................................ 345
Section 64.2: Keeping Compatibility ....................................................................................................................... 346
Section 64.3: Cancelling an Animation .................................................................................................................... 346
Chapter 65: Creational Design Patterns ....................................................................................................... 348
Section 65.1: Factory Functions ................................................................................................................................ 348
Section 65.2: Factory with Composition .................................................................................................................. 349
Section 65.3: Module and Revealing Module Patterns .......................................................................................... 350
Section 65.4: Prototype Pattern ............................................................................................................................... 352
Section 65.5: Singleton Pattern ................................................................................................................................ 353
Section 65.6: Abstract Factory Pattern ................................................................................................................... 354
Chapter 66: Detecting browser ......................................................................................................................... 355
Section 66.1: Feature Detection Method ................................................................................................................. 355
Section 66.2: User Agent Detection ......................................................................................................................... 355
Section 66.3: Library Method ................................................................................................................................... 356
Chapter 67: Symbols ............................................................................................................................................... 357
Section 67.1: Basics of symbol primitive type ......................................................................................................... 357
Section 67.2: Using Symbol.for() to create global, shared symbols .................................................................... 357
Section 67.3: Converting a symbol into a string .................................................................................................... 357
Chapter 68: Transpiling ......................................................................................................................................... 359
Section 68.1: Introduction to Transpiling ................................................................................................................. 359
Section 68.2: Start using ES6/7 with Babel ............................................................................................................. 360
Chapter 69: Automatic Semicolon Insertion - ASI .................................................................................... 361
Section 69.1: Avoid semicolon insertion on return statements ............................................................................. 361
Section 69.2: Rules of Automatic Semicolon Insertion .......................................................................................... 361
Section 69.3: Statements aected by automatic semicolon insertion ................................................................ 362
Chapter 70: Localization ....................................................................................................................................... 364
Section 70.1: Number formatting ............................................................................................................................. 364
Section 70.2: Currency formatting .......................................................................................................................... 364
Section 70.3: Date and time formatting .................................................................................................................. 364
Chapter 71: Geolocation ........................................................................................................................................ 365
Section 71.1: Get updates when a user's location changes ................................................................................... 365
Section 71.2: Get a user's latitude and longitude ................................................................................................... 365
Section 71.3: More descriptive error codes ............................................................................................................. 365
Chapter 72: IndexedDB .......................................................................................................................................... 367
Section 72.1: Opening a database ........................................................................................................................... 367
Section 72.2: Adding objects .................................................................................................................................... 367
Section 72.3: Retrieving data ................................................................................................................................... 368
Section 72.4: Testing for IndexedDB availability .................................................................................................... 369
Chapter 73: Modularization Techniques ....................................................................................................... 370
Section 73.1: ES6 Modules ......................................................................................................................................... 370
Section 73.2: Universal Module Definition (UMD) .................................................................................................. 370
Section 73.3: Immediately invoked function expressions (IIFE) ............................................................................ 371
Section 73.4: Asynchronous Module Definition (AMD) .......................................................................................... 371
Section 73.5: CommonJS - Node.js .......................................................................................................................... 372
Chapter 74: Proxy .................................................................................................................................................... 374
Section 74.1: Proxying property lookup .................................................................................................................. 374
Section 74.2: Very simple proxy (using the set trap) ............................................................................................ 374
Chapter 75: .postMessage() and MessageEvent ...................................................................................... 376
Section 75.1: Getting Started .................................................................................................................................... 376
Chapter 76: WeakMap ............................................................................................................................................ 379
Section 76.1: Creating a WeakMap object .............................................................................................................. 379
Section 76.2: Getting a value associated to the key .............................................................................................. 379
Section 76.3: Assigning a value to the key ............................................................................................................. 379
Section 76.4: Checking if an element with the key exists ...................................................................................... 379
Section 76.5: Removing an element with the key .................................................................................................. 380
Section 76.6: Weak reference demo ....................................................................................................................... 380
Chapter 77: WeakSet .............................................................................................................................................. 382
Section 77.1: Creating a WeakSet object ................................................................................................................ 382
Section 77.2: Adding a value .................................................................................................................................... 382
Section 77.3: Checking if a value exists ................................................................................................................... 382
Section 77.4: Removing a value ............................................................................................................................... 382
Chapter 78: Escape Sequences ......................................................................................................................... 383
Section 78.1: Entering special characters in strings and regular expressions .................................................... 383
Section 78.2: Escape sequence types ..................................................................................................................... 383
Chapter 79: Behavioral Design Patterns ...................................................................................................... 386
Section 79.1: Observer pattern ................................................................................................................................. 386
Section 79.2: Mediator Pattern ................................................................................................................................ 387
Section 79.3: Command ............................................................................................................................................ 388
Section 79.4: Iterator ................................................................................................................................................. 389
Chapter 80: Server-sent events ........................................................................................................................ 391
Section 80.1: Setting up a basic event stream to the server ................................................................................. 391
Section 80.2: Closing an event stream ................................................................................................................... 391
Section 80.3: Binding event listeners to EventSource ........................................................................................... 391
Chapter 81: Async functions (async/await) ................................................................................................ 393
Section 81.1: Introduction .......................................................................................................................................... 393
Section 81.2: Await and operator precedence ....................................................................................................... 393
Section 81.3: Async functions compared to Promises ........................................................................................... 394
Section 81.4: Looping with async await ................................................................................................................... 395
Section 81.5: Less indentation .................................................................................................................................. 396
Section 81.6: Simultaneous async (parallel) operations ........................................................................................ 397
Chapter 82: Async Iterators ................................................................................................................................ 398
Section 82.1: Basics ................................................................................................................................................... 398
Chapter 83: How to make iterator usable inside async callback function ................................. 399
Section 83.1: Erroneous code, can you spot why this usage of key will lead to bugs? ...................................... 399
Section 83.2: Correct Writing ................................................................................................................................... 399
Chapter 84: Tail Call Optimization .................................................................................................................. 400
Section 84.1: What is Tail Call Optimization (TCO) ................................................................................................ 400
Section 84.2: Recursive loops .................................................................................................................................. 400
Chapter 85: Bitwise Operators - Real World Examples (snippets) ................................................. 401
Section 85.1: Swapping Two Integers with Bitwise XOR (without additional memory allocation) .................... 401
Section 85.2: Faster multiplication or division by powers of 2 ............................................................................. 401
Section 85.3: Number's Parity Detection with Bitwise AND .................................................................................. 401
Chapter 86: Tilde ~ ................................................................................................................................................... 403
Section 86.1: ~ Integer ............................................................................................................................................... 403
Section 86.2: ~~ Operator ......................................................................................................................................... 403
Section 86.3: Converting Non-numeric values to Numbers .................................................................................. 404
Section 86.4: Shorthands .......................................................................................................................................... 404
Section 86.5: ~ Decimal ............................................................................................................................................. 404
Chapter 87: Using JavaScript to get/set CSS custom variables ..................................................... 406
Section 87.1: How to get and set CSS variable property values ........................................................................... 406
Chapter 88: Selection API ..................................................................................................................................... 407
Section 88.1: Get the text of the selection ............................................................................................................... 407
Section 88.2: Deselect everything that is selected ................................................................................................ 407
Section 88.3: Select the contents of an element .................................................................................................... 407
Chapter 89: File API, Blobs and FileReaders ............................................................................................... 408
Section 89.1: Read file as string ............................................................................................................................... 408
Section 89.2: Read file as dataURL ......................................................................................................................... 408
Section 89.3: Slice a file ............................................................................................................................................. 409
Section 89.4: Get the properties of the file ............................................................................................................. 409
Section 89.5: Selecting multiple files and restricting file types ............................................................................. 410
Section 89.6: Client side csv download using Blob ................................................................................................ 410
Chapter 90: Notifications API ............................................................................................................................. 411
Section 90.1: Requesting Permission to send notifications ................................................................................... 411
Section 90.2: Sending Notifications ......................................................................................................................... 411
Section 90.3: Closing a notification ......................................................................................................................... 411
Section 90.4: Notification events ............................................................................................................................. 412
Chapter 91: Vibration API ...................................................................................................................................... 413
Section 91.1: Single vibration ..................................................................................................................................... 413
Section 91.2: Check for support ............................................................................................................................... 413
Section 91.3: Vibration patterns ............................................................................................................................... 413
Chapter 92: Battery Status API ......................................................................................................................... 414
Section 92.1: Battery Events ..................................................................................................................................... 414
Section 92.2: Getting current battery level ............................................................................................................. 414
Section 92.3: Is battery charging? ........................................................................................................................... 414
Section 92.4: Get time left until battery is empty ................................................................................................... 414
Section 92.5: Get time left until battery is fully charged ....................................................................................... 414
Chapter 93: Fluent API ............................................................................................................................................ 415
Section 93.1: Fluent API capturing construction of HTML articles with JS ........................................................... 415
Chapter 94: Web Cryptography API ............................................................................................................... 417
Section 94.1: Creating digests (e.g. SHA-256) ......................................................................................................... 417
Section 94.2: Cryptographically random data ....................................................................................................... 417
Section 94.3: Generating RSA key pair and converting to PEM format .............................................................. 418
Section 94.4: Converting PEM key pair to CryptoKey ........................................................................................... 419
Chapter 95: Security issues ................................................................................................................................. 421
Section 95.1: Reflected Cross-site scripting (XSS) .................................................................................................. 421
Section 95.2: Persistent Cross-site scripting (XSS) ................................................................................................ 422
Section 95.3: Persistent Cross-site scripting from JavaScript string literals ....................................................... 423
Section 95.4: Why scripts from other people can harm your website and its visitors ...................................... 423
Section 95.5: Evaled JSON injection ........................................................................................................................ 424
Chapter 96: Same Origin Policy & Cross-Origin Communication ..................................................... 426
Section 96.1: Safe cross-origin communication with messages ........................................................................... 426
Section 96.2: Ways to circumvent Same-Origin Policy ......................................................................................... 427
Chapter 97: Error Handling ................................................................................................................................. 429
Section 97.1: Error objects ........................................................................................................................................ 429
Section 97.2: Interaction with Promises .................................................................................................................. 429
Section 97.3: Error types ........................................................................................................................................... 430
Section 97.4: Order of operations plus advanced thoughts ................................................................................. 430
Chapter 98: Global error handling in browsers ........................................................................................ 433
Section 98.1: Handling window.onerror to report all errors back to the server-side ......................................... 433
Chapter 99: Debugging .......................................................................................................................................... 435
Section 99.1: Interactive interpreter variables ........................................................................................................ 435
Section 99.2: Breakpoints ......................................................................................................................................... 435
Section 99.3: Using setters and getters to find what changed a property ......................................................... 436
Section 99.4: Using the console ............................................................................................................................... 437
Section 99.5: Automatically pausing execution ..................................................................................................... 438
Section 99.6: Elements inspector ............................................................................................................................. 438
Section 99.7: Break when a function is called ........................................................................................................ 438
Section 99.8: Stepping through code ...................................................................................................................... 439
Chapter 100: Unit Testing JavaScript ............................................................................................................ 440
Section 100.1: Unit Testing Promises with Mocha, Sinon, Chai and Proxyquire ................................................... 440
Section 100.2: Basic Assertion .................................................................................................................................. 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:
https://goalkicker.com/JavaScriptBook
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, Node.js 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 console.log().
In a browser environment, the console.log() function is predominantly used for debugging purposes.
Getting Started
Open up the JavaScript Console in your browser, type the following, and press Enter :
console.log("Hello, World!");
In the example above, the console.log() function prints Hello, World! to the console and returns undefined
(shown above in the console output window). This is because console.log() has no explicit return value.
Logging variables
console.log() 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.
console.log({
'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:
console.log(document.body);
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.
window.alert(message);
Because window is the global object, you can call also use the following shorthand:
alert(message);
So what does window.alert() 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 window.alert().
Unlike using console.log, 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!');
console.log('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, window.alert() 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?");
console.log(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 = window.confirm(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).
window.confirm() 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:
document.body.appendChild(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:
svg.appendChild(text);
document.body.appendChild(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 window.alert():
console.log(number1); // 3
window.alert(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:
window.alert(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"
};
window.alert(john.fullname); // John Doe
window.alert(billy.firstname); // Billy
Rather than making an array ["John Doe", "Billy"] and calling myArray[0], we can just call john.fullname and
billy.fullname.
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
Number.isNaN()
In ECMAScript 6, the Number.isNaN() function has been implemented primarily to avoid the problem of
window.isNaN() of forcefully converting the parameter to a number. Number.isNaN(), 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 Number.isNaN(NaN)).
When the Number.isNaN is called with one argument number, the following steps are taken:
Some examples:
// Numbers
Number.isNaN(1); // false
Number.isNaN(-2e-4); // false
Number.isNaN(Infinity); // false
window.hasOwnProperty('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) {
console.log('is undefined?', param === undefined);
}
foo('a');
foo();
// is undefined? false
// is undefined? true
// Only in browsers
console.log(window.undefined); // undefined
window.hasOwnProperty('undefined'); // true
Version < 5
Before ECMAScript 5 you could actually change the value of the window.undefined property to any other value
potentially breaking everything.
Infinity is a property of the global object (therefore a global variable) that represents mathematical infinity. It is a
reference to Number.POSITIVE_INFINITY
It is greater than any other value, and you can get it by dividing by 0 or by evaluating the expression of a number
that's so big that overflows. This actually means there is no division by 0 errors in JavaScript, there is Infinity!
There is also -Infinity which is mathematical negative infinity, and it's lower than any other value.
- (Infinity); // -Infinity
var a = 0, b = -0;
a === b; // true
1 / a === 1 / b; // false
Number.MAX_VALUE; // 1.7976931348623157e+308
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.EPSILON; // 0.0000000000000002220446049250313
Number.POSITIVE_INFINITY; // Infinity
Number.NEGATIVE_INFINITY; // -Infinity
Number.NaN; // NaN
In many cases the various operators in JavaScript will break with values outside the range of
(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
Note that Number.EPSILON represents the different between one and the smallest Number greater than one, and
thus the smallest possible difference between two different Number values. One reason to use this is due to the
nature of how numbers are stored by JavaScript see Check the equality of two numbers
"b" * 3
"cde" - "e"
[1, 2, 3] * 2
0 / 0 // NaN
Note: In mathematics generally (unlike in JavaScript programming), dividing by zero is not possible.
Math.floor("a")
The square root of a negative number returns NaN, because Math.sqrt does not support imaginary or complex
numbers.
Math.sqrt(-1)
Everything after the // until the end of the line is excluded from execution.
Everything between the opening /* and the closing */ is excluded from execution, even if the opening and closing
are on different lines.
/*
Gets the element from Event coordinates.
Use like:
var clickedEl = someEl.addEventListener("click", elementAt, false);
*/
function elementAt( event ) {
return document.elementFromPoint(event.clientX, event.clientY);
}
/* TODO: write more useful comments! */
Note: the JavaScript interpreter ignores the closing characters of HTML comments (-->) here.
This technique can be observed in legacy code to hide JavaScript from browsers that didn't support it: