JavaScript Programming _ Beginner to Professional ADVANCED.pdf
Document Details
Uploaded by EnterprisingAcademicArt
Related
- PCSII Depression/Anxiety/Strong Emotions 2024 Document
- A Concise History of the World: A New World of Connections (1500-1800)
- Human Bio Test PDF
- University of Santo Tomas Pre-Laboratory Discussion of LA No. 1 PDF
- Vertebrate Pest Management PDF
- Lg 5 International Environmental Laws, Treaties, Protocols, and Conventions
Full Transcript
Contents Chapter 19: Functions.............................................................................................................................. 163 Section 19.1: Function Scoping.............................................................................................................
Contents 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: Di☐erence 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 di☐erence 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 ArrayBu☐ers................................................................................. 302 Section 53.3: Manipulating ArrayBu☐ers 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 arrayBu☐er...................................................................................................... 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: Di☐erence 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 e☐ects................................................................................................................ 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 a☐ected 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 e☐ciency....................................................................................................................... 458 Section 105.1: Drawback of creating true private method.................................................................................... 458 Chapter 19: Functions Functions in JavaScript provide organized, reusable code to perform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes the declaration and utilization of functions, arguments, parameters, return statements and scope in JavaScript. Section 19.1: Function Scoping When you define a function, it creates a scope. Everything defined within the function is not accessible by code outside the function. Only code within this scope can see the entities defined inside the scope. function foo() { var a = 'hello'; console.log(a); // => 'hello' } console.log(a); // reference error Nested functions are possible in JavaScript and the same rules apply. function foo() { var a = 'hello'; function bar() { var b = 'world'; console.log(a); // => 'hello' console.log(b); // => 'world' } console.log(a); // => 'hello' console.log(b); // reference error } console.log(a); // reference error console.log(b); // reference error When JavaScript tries to resolve a reference or variable, it starts looking for it in the current scope. If it cannot find that declaration in the current scope, it climbs up one scope to look for it. This process repeats until the declaration has been found. If the JavaScript parser reaches the global scope and still cannot find the reference, a reference error will be thrown. var a = 'hello'; function foo() { var b = 'world'; function bar() { var c = '!!'; console. log(a); // => 'hello' console.log(b); // => 'world' console.log(c); // => '!!' console.log(d); // reference error This climbing behavior can also mean that one reference may "shadow" over a similarly named reference in the outer scope since it gets seen first. var a = 'hello'; function foo() { var a = 'world'; function bar() { console.log(a); // => 'world' } } Version ≥ 6 The way JavaScript resolves scoping also applies to the const keyword. Declaring a variable with the const keyword implies that you are not allowed to reassign the value, but declaring it in a function will create a new scope and with that a new variable. function foo() { const a = true; function bar() { const a = false; // different variable console.log(a); } // false const a = false; a = false; console.log(a); } // SyntaxError // TypeError // true However, functions are not the only blocks that create a scope (if you are using let or const). let and const declarations have a scope of the nearest block statement. See here for a more detailed description. Section 19.2: Currying Currying is the transformation of a function of n arity or arguments into a sequence of n functions taking only one argument. Use cases: When the values of some arguments are available before others, you can use currying to decompose a function into a series of functions that complete the work in stages, as each value arrives. This can be useful: When the value of an argument almost never changes (e.g., a conversion factor), but you need to maintain the flexibility of setting that value (rather than hard-coding it as a constant). When the result of a curried function is useful before the other curried functions have run. To validate the arrival of the functions in a specific sequence. For example, the volume of a rectangular prism can be explained by a function of three factors: length (l), width (w), and height (h): var prism = function(l, w, h) { return l * w * h; A curried version of this function would look like: function prism(l) { return function(w) { return function(h) { return l * w * h; } } } Version ≥ 6 // alternatively, with concise ECMAScript 6+ syntax: var prism = l => w => h => l * w * h; You can call these sequence of functions with prism(2)(3)(5), which should evaluate to 30. Without some extra machinery (like with libraries), currying is of limited syntactical flexibility in JavaScript (ES 5/6) due to the lack of placeholder values; thus, while you can use var a = prism(2)(3) to create a partially applied function, you cannot use prism()(3)(5). Section 19.3: Immediately Invoked Function Expressions Sometimes you don't want to have your function accessible/stored as a variable. You can create an Immediately Invoked Function Expression (IIFE for short). These are essentially self-executing anonymous functions. They have access to the surrounding scope, but the function itself and any internal variables will be inaccessible from outside. An important thing to note about IIFE is that even if you name your function, IIFE are not hoisted like standard functions are and cannot be called by the function name they are declared with. (function() { alert("I've run - but can't be run again because I'm immediately invoked at runtime, leaving behind only the result I generate"); }()); This is another way to write IIFE. Notice that the closing parenthesis before the semicolon was moved and placed right after the closing curly bracket: ( function() { alert("This is IIFE too."); })(); You can easily pass parameters into an IIFE: ( function(message) { alert(message); }("Hello World!")); Additionally, you can return values to the surrounding scope: var example = (function() { return 42; }()); console.log(example); // => 42 If required it is possible to name an IIFE. While less often seen, this pattern has several advantages, such as providing a reference which can be used for a recursion and can make debugging simpler as the name is included in the callstack. ( function namedIIFE() { throw error; // We can now see the error thrown in 'namedIIFE()' }()); While wrapping a function in parenthesis is the most common way to denote to the JavaScript parser to expect an expression, in places where an expression is already expected, the notation can be made more concise: var a = function() { return 42 }(); console.log(a) // => 42 Arrow version of immediately invoked function: Version ≥ 6 (() => console.log("Hello!"))(); // => Hello! Section 19.4: Named Functions Functions can either be named or unnamed (anonymous functions): var namedSum = function sum (a, b) { // named return a + b; } var anonSum = function (a, b) { // anonymous return a + b; } namedSum(1, 3); anonSum(1, 3); 44 But their names are private to their own scope: var sumTwoNumbers = function sum (a, b) { return a + b; } sum(1, 3); Uncaught ReferenceError: sum is not defined Named functions differ from the anonymous functions in multiple scenarios: When you are debugging, the name of the function will appear in the error/stack trace Named functions are hoisted while anonymous functions are not Named functions and anonymous functions behave differently when handling recursion Depending on ECMAScript version, named and anonymous functions may treat the function name property differently Named functions are hoisted When using an anonymous function, the function can only be called after the line of declaration, whereas a named function can be called before declaration. Consider foo(); var foo = function () { // using an anonymous function console.log('bar'); } Uncaught TypeError: foo is not a function foo(); function foo () { // using a named function console.log('bar'); } bar Named Functions in a recursive scenario A recursive function can be defined as: var say = function (times) { if (times > 0) { console.log('Hello!'); say(times - 1); } } //you could call 'say' directly, //but this way just illustrates the example var sayHelloTimes = say; sayHelloTimes(2); Hello! Hello! What if somewhere in your code the original function binding gets redefined? var say = function (times) { if (times > 0) { console.log('Hello!'); say(times - 1); } } var sayHelloTimes = say; say = "oops"; sayHelloTimes(2); Hello! Uncaught TypeError: say is not a function This can be solved using a named function // The outer variable can even have the same name as the function // as they are contained in different scopes var say = function say (times) { if (times > 0) { console.log('Hello!'); // this time, 'say' doesn't use the outer variable // it uses the named function say(times - 1); } } var sayHelloTimes = say; say = "oops"; sayHelloTimes(2); Hello! Hello! And as bonus, the named function can't be set to undefined, even from inside: var say = function say (times) { // this does nothing say = undefined; if (times > 0) { console.log('Hello!'); // this time, 'say' doesn't use the outer variable // it's using the named function say(times - 1); } } var sayHelloTimes = say; say = "oops"; sayHelloTimes(2); Hello! Hello! The name property of functions Before ES6, named functions had their name properties set to their function names, and anonymous functions had their name properties set to the empty string. Version ≤ 5 var foo = function () {} console.log(foo.name); // outputs '' function foo () {} console.log(foo.name); // outputs 'foo' Post ES6, named and unnamed functions both set their name properties: Version ≥ 6 var foo = function () {} console.log(foo.name); // outputs 'foo' function foo () {} console.log(foo.name); // outputs 'foo' var foo = function bar () {} console.log(foo.name); // outputs 'bar' Section 19.5: Binding `this` and arguments Version ≥ 5.1 When you take a reference to a method (a property which is a function) in JavaScript, it usually doesn't remember the object it was originally attached to. If the method needs to refer to that object as this it won't be able to, and calling it will probably cause a crash. You can use the.bind() method on a function to create a wrapper that includes the value of this and any number of leading arguments. var monitor = { threshold: 5, check: function(value) { if (value > this.threshold) { this.display("Value is too high!"); } }, display(message) { alert(message); } }; monitor.check(7); // The value of `this` is implied by the method call syntax. var badCheck = monitor.check; badCheck(15); // The value of `this` is window object and this.threshold is undefined, so value > this.threshold is false var check = monitor.check.bind(monitor); check(15); // This value of `this` was explicitly bound, the function works. var check8 = monitor.check.bind(monitor, 8); check8(); // We also bound the argument to `8` here. It can't be re-specified. When not in strict mode, a function uses the global object (window in the browser) as this, unless the function is called as a method, bound, or called with the method.call syntax. window.x = 12; function example() { return this.x; } console.log(example()); // 12 In strict mode this is undefined by default window.x = 12; function example() { "use strict"; return this.x; } console. log(example()); // Uncaught TypeError: Cannot read property 'x' of undefined(…) Version ≥ 7 Bind Operator The double colon bind operator can be used as a shortened syntax for the concept explained above: var log = console.log.bind(console); // long version const log = ::console.log; // short version foo.bar.call(foo); // long version foo::bar(); // short version foo.bar.call(foo, arg1, arg2, arg3); // long version foo::bar(arg1, arg2, arg3); // short version foo.bar.apply(foo, args); // long version foo::bar(...args); // short version This syntax allows you to write normally, without worrying about binding this everywhere. Binding console functions to variables var log = console.log.bind(console); Usage: log('one', '2', 3, , {5: 5}); Output: one 2 3 Object {5: 5} Why would you do that? One use case can be when you have custom logger and you want to decide on runtime which one to use. var logger = require('appLogger'); var log = logToServer ? logger.log : console.log.bind(console); Section 19.6: Functions with an Unknown Number of Arguments (variadic functions) To create a function which accepts an undetermined number of arguments, there are two methods depending on your environment. Version ≤ 5 Whenever a function is called, it has an Array-like arguments object in its scope, containing all the arguments passed to the function. Indexing into or iterating over this will give access to the arguments, for example function logSomeThings() { for (var i = 0; i < arguments.length; ++i) { console.log(arguments[i]); } } logSomeThings ('hello', 'world'); // logs "hello" // logs "world" Note that you can convert arguments to an actual Array if need-be; see: Converting Array-like Objects to Arrays Version ≥ 6 From ES6, the function can be declared with its last parameter using the rest operator (...). This creates an Array which holds the arguments from that point onwards function personLogsSomeThings(person,...msg) { msg.forEach(arg => { console.log(person, 'says', arg); }); } personLogsSomeThings ('John', 'hello', 'world'); // logs "John says hello" // logs "John says world" Functions can also be called with similar way, the spread syntax const logArguments = (...args) => console.log(args) const list = [1, 2, 3] logArguments('a', 'b', 'c',...list) // output: Array [ "a", "b", "c", 1, 2, 3 ] This syntax can be used to insert arbitrary number of arguments to any position, and can be used with any iterable(apply accepts only array-like objects). const logArguments = (...args) => console.log(args) function* generateNumbers() { yield 6 yield 5 yield 4 } logArguments('a',...generateNumbers(),...'pqr', 'b') // output: Array [ "a", 6, 5, 4, "p", "q", "r", "b" ] Section 19.7: Anonymous Function Defining an Anonymous Function When a function is defined, you often give it a name and then invoke it using that name, like so: foo(); function foo(){ //... } When you define a function this way, the JavaScript runtime stores your function in memory and then creates a reference to that function, using the name you've assigned it. That name is then accessible within the current scope. This can be a very convenient way to create a function, but JavaScript does not require you to assign a name to a function. The following is also perfectly legal: function () { //... } When a function is defined without a name, it's known as an anonymous function. The function is stored in memory, but the runtime doesn't automatically create a reference to it for you. At first glance, it may appear as if such a thing would have no use, but there are several scenarios where anonymous functions are very convenient. Assigning an Anonymous Function to a Variable A very common use of anonymous functions is to assign them to a variable: var foo = function(){ }; foo(); This use of anonymous functions is covered in more detail in Functions as a variable Supplying an Anonymous Function as a Parameter to Another Function Some functions may accept a reference to a function as a parameter. These are sometimes referred to as "dependency injections" or "callbacks", because it allows the function your calling to "call back" to your code, giving you an opportunity to change the way the called function behaves. For example, the Array object's map function allows you to iterate over each element of an array, then build a new array by applying a transform function to each element. var nums = [0,1,2]; var doubledNums = nums.map( function(element){ return element * 2; } ); // [0,2,4] It would be tedious, sloppy and unnecessary to create a named function, which would clutter your scope with a function only needed in this one place and break the natural flow and reading of your code (a colleague would have to leave this code to find your function to understand what's going on). Returning an Anonymous Function From Another Function Sometimes it's useful to return a function as the result of another function. For example: var hash = getHashFunction( 'sha1' ); var hashValue = hash( 'Secret Value' ); function getHashFunction( algorithm ){ if ( algorithm === 'sha1' ) return function( value ){ }; else if ( algorithm === 'md5' ) return function( value ){ }; } Immediately Invoking an Anonymous Function Unlike many other languages, scoping in JavaScript is function-level, not block-level. (See Function Scoping ). In some cases, however, it's necessary to create a new scope. For example, it's common to create a new scope when adding code via a tag, rather than allowing variable names to be defined in the global scope (which runs the risk of other scripts colliding with your variable names). A common method to handle this situation is to define a new anonymous function and then immediately invoke it, safely hiding you variables within the scope of the anonymous function and without making your code accessible to third-parties via a leaked function name. For example: handlerFn1 -> handlerFn2 --> handlerFn5 ~~>.catch() | ^ V| -> handlerFn3 -> handlerFn4 -^ The single catch will get the error on whichever branch it may occur. Section 42.3: Waiting for multiple concurrent promises The Promise.all() static method accepts an iterable (e.g. an Array) of promises and returns a new promise, which resolves when all promises in the iterable have resolved, or rejects if at least one of the promises in the iterable have rejected. // wait "millis" ms, then resolve with "value" function resolve(value, milliseconds) { return new Promise(resolve => setTimeout(() => resolve(value), milliseconds)); } // wait "millis" ms, then reject with "reason" function reject(reason, milliseconds) { return new Promise((_, reject) => setTimeout(() => reject(reason), milliseconds)); } Promise. all([ resolve(1, 5000), resolve(2, 6000), resolve(3, 7000) ]).then(values => console.log(values)); // outputs "[1, 2, 3]" after 7 seconds. Promise. all([ resolve(1, 5000), reject('Error!', 6000), resolve(2, 7000) ]).then(values => console.log(values)) // does not output anything.catch(reason => console.log(reason)); // outputs "Error!" after 6 seconds. Non-promise values in the iterable are "promisified". Promise. all([ resolve(1, 5000), resolve(2, 6000), { hello: 3 } ]).then(values => console.log(values)); // outputs "[1, 2, { hello: 3 }]" after 6 seconds Destructuring assignment can help to retrieve results from multiple promises. Promise. all([ resolve(1, 5000), resolve(2, 6000), resolve(3, 7000) ]).then(([result1, result2, result3]) => { console.log(result1); console.log(result2); console.log(result3); }); Section 42.4: Reduce an array to chained promises This design pattern is useful for generating a sequence of asynchronous actions from a list of elements. There are two variants : the "then" reduction, which builds a chain that continues as long as the chain experiences success. the "catch" reduction, which builds a chain that continues as long as the chain experiences error. The "then" reduction This variant of the pattern builds a.then() chain, and might be used for chaining animations, or making a sequence of dependent HTTP requests. [ 1, 3, 5, 7, 9].reduce((seq, n) => { return seq.then(() => { console.log(n); return new Promise(res => setTimeout(res, 1000)); }); }, Promise.resolve()).then( () => console.log('done'), (e) => console.log(e) ); // will log 1, 3, 5, 7, 9, 'done' in 1s intervals Explanation: 1. We call.reduce() on a source array, and provide Promise.resolve() as an initial value. 2. Every element reduced will add a.then() to the initial value. 3. reduce()'s product will be Promise.resolve().then(...).then(...). 4. We manually append a.then(successHandler, errorHandler) after the reduce, to execute successHandler once all the previous steps have resolved. If any step was to fail, then errorHandler would execute. Note: The "then" reduction is a sequential counterpart of Promise.all(). The "catch" reduction This variant of the pattern builds a.catch() chain and might be used for sequentially probing a set of web servers for some mirrored resource until a working server is found. var working_resource = 5; // one of the values from the source array [ 1, 3, 5, 7, 9].reduce((seq, n) => { return seq.catch(() => { console.log(n); if(n === working_resource) { // 5 is working return new Promise((resolve, reject) => setTimeout(() => resolve(n), 1000)); } else { // all other values are not working return new Promise((resolve, reject) => setTimeout(reject, 1000)); } }); }, Promise.reject()).then( (n) => console.log('success at: ' + n), () => console.log('total failure') ); // will log 1, 3, 5, 'success at 5' at 1s intervals Explanation: 1. We call.reduce() on a source array, and provide Promise.reject() as an initial value. 2. Every element reduced will add a.catch() to the initial value. 3. reduce()'s product will be Promise.reject().catch(...).catch(...). 4. We manually append.then(successHandler, errorHandler) after the reduce, to execute successHandler once any of the previous steps has resolved. If all steps were to fail, then errorHandler would execute. Note: The "catch" reduction is a sequential counterpart of Promise.any() (as implemented in bluebird.js, but not currently in native ECMAScript). Section 42.5: Waiting for the first of multiple concurrent promises The Promise.race() static method accepts an iterable of Promises and returns a new Promise which resolves or rejects as soon as the first of the promises in the iterable has resolved or rejected. // wait "milliseconds" milliseconds, then resolve with "value" function resolve(value, milliseconds) { return new Promise(resolve => setTimeout(() => resolve(value), milliseconds)); } // wait "milliseconds" milliseconds, then reject with "reason" function reject(reason, milliseconds) { return new Promise((_, reject) => setTimeout(() => reject(reason), milliseconds)); } Promise. race([ resolve(1, 5000), resolve(2, 3000), resolve(3, 1000) ]).then(value => console.log(value)); // outputs "3" after 1 second. Promise. race([ reject(new Error('bad things!'), 1000), resolve(2, 2000) ]).then(value => console.log(value)) // does not output anything.catch(error => console.log(error.message)); // outputs "bad things!" after 1 second Section 42.6: "Promisifying" functions with callbacks Given a function that accepts a Node-style callback, fooFn(options, function callback(err, result) {... }); you can promisify it (convert it to a promise-based function) like this: function promiseFooFn(options) { return new Promise((resolve, reject) => fooFn(options, (err, result) => // If there's an error, reject; otherwise resolve err ? reject(err) : resolve(result) ) ); } This function can then be used as follows: promiseFooFn (options).then(result => { // success! }).catch(err => { // error! }); In a more generic way, here's how to promisify any given callback-style function: function promisify(func) { return function(...args) { return new Promise((resolve, reject) => { func(...args, (err, result) => err ? reject(err) : resolve(result)); }); } } This can be used like this: const fs = require('fs'); const promisedStat = promisify(fs.stat.bind(fs)); promisedStat ('/foo/bar').then(stat => console.log('STATE', stat)).catch(err => console.log('ERROR', err)); Section 42.7: Error Handling Errors thrown from promises are handled by the second parameter (reject) passed to then or by the handler passed to catch: throwErrorAsync(). then(null, error => { }); // or throwErrorAsync().catch(error => { }); Chaining If you have a promise chain then an error will cause resolve handlers to be skipped: throwErrorAsync ().then(() => { }).catch(error => { }); The same applies to your then functions. If a resolve handler throws an exception then the next reject handler will be invoked: doSomethingAsync ().then(result => { throwErrorSync(); }).then(() => { }).catch(error => { }); An error handler returns a new promise, allowing you to continue a promise chain. The promise returned by the error handler is resolved with the value returned by the handler: throwErrorAsync ().catch(error => { ; return result; }).then(result => { }); You can let an error cascade down a promise chain by re-throwing the error: throwErrorAsync ().catch(error => { throw error; }).then(() => { }).catch(error => { }); It is possible to throw an exception that is not handled by the promise by wrapping the throw statement inside a setTimeout callback: new Promise((resolve, reject) => { setTimeout(() => { throw new Error(); }); }); This works because promises cannot handle exceptions thrown asynchronously. Unhandled rejections An error will be silently ignored if a promise doesn't have a catch block or reject handler: throwErrorAsync ().then(() => { }); // error silently ignored To prevent this, always use a catch block: throwErrorAsync ().then(() => { }).catch(error => { }); // or throwErrorAsync().then(() => { }, error => { }); Alternatively, subscribe to the unhandledrejection event to catch any unhandled rejected promises: window.addEventListener('unhandledrejection', event => {}); Some promises can handle their rejection later than their creation time. The rejectionhandled event gets fired whenever such a promise is handled: window. addEventListener('unhandledrejection', event => console.log('unhandled')); window.addEventListener('rejectionhandled', event => console.log('handled')); var p = Promise.reject('test'); setTimeout(() => p.catch(console.log), 1000); // Will print 'unhandled', and after one second 'test' and 'handled' The event argument contains information about the rejection. event.reason is the error object and event.promise is the promise object that caused the event. In Nodejs the rejection