[Go to site: main page, start]

0% found this document useful (0 votes)
6 views245 pages

JavaScript Notes For Professionals2

The document is a comprehensive guide on JavaScript, covering topics from basic concepts to advanced techniques. It includes chapters on variables, built-in constants, data types, functions, and various JavaScript operations. The content is structured into sections for easy navigation and understanding, making it a valuable resource for professionals and learners alike.

Uploaded by

Nagdatt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views245 pages

JavaScript Notes For Professionals2

The document is a comprehensive guide on JavaScript, covering topics from basic concepts to advanced techniques. It includes chapters on variables, built-in constants, data types, functions, and various JavaScript operations. The content is structured into sections for easy navigation and understanding, making it a valuable resource for professionals and learners alike.

Uploaded by

Nagdatt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

JavaScript
Notes for Professionals Contents
®
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with JavaScript ..................................................................................................... 2
Section 1.1: Using [Link]() ..................................................................................................................................... 2

Notes for Professionals


Section 1.2: Using the DOM API .................................................................................................................................... 4
Section 1.3: Using [Link]() .................................................................................................................................. 5
Section 1.4: Using [Link]() ............................................................................................................................. 6
Section 1.5: Using [Link]firm() ............................................................................................................................ 7
Section 1.6: Using the DOM API (with graphical text: Canvas, SVG, or image file) ................................................. 8
Chapter 2: JavaScript Variables ......................................................................................................................... 10
Section 2.1: Defining a Variable ................................................................................................................................. 10
Section 2.2: Using a Variable ..................................................................................................................................... 10
Section 2.3: Types of Variables .................................................................................................................................. 10
Section 2.4: Arrays and Objects ................................................................................................................................ 11
Chapter 3: Built-in Constants ................................................................................................................................ 12
Section 3.1: null ............................................................................................................................................................. 12
Section 3.2: Testing for NaN using isNaN() .............................................................................................................. 12
Section 3.3: NaN .......................................................................................................................................................... 13
Section 3.4: undefined and null .................................................................................................................................. 14
Section 3.5: Infinity and -Infinity ................................................................................................................................. 15
Section 3.6: Number constants .................................................................................................................................. 15
Section 3.7: Operations that return NaN ................................................................................................................... 16
Section 3.8: Math library functions that return NaN ................................................................................................ 16
Chapter 4: Comments .............................................................................................................................................. 17
Section 4.1: Using Comments ..................................................................................................................................... 17
Section 4.2: Using HTML comments in JavaScript (Bad practice) ........................................................................ 17
Chapter 5: Console ..................................................................................................................................................... 19
Section 5.1: Measuring time - [Link]() ............................................................................................................ 22
Section 5.2: Formatting console output .................................................................................................................... 23
Section 5.3: Printing to a browser's debugging console ......................................................................................... 24
Section 5.4: Including a stack trace when logging - [Link]() ..................................................................... 26
Section 5.5: Tabulating values - [Link]() ...................................................................................................... 26
Section 5.6: Counting - [Link]() .................................................................................................................... 28
Section 5.7: Clearing the console - [Link]() .................................................................................................. 30
Section 5.8: Displaying objects and XML interactively - [Link](), [Link]() ...................................... 30
Section 5.9: Debugging with assertions - [Link]() ..................................................................................... 32
Chapter 6: Datatypes in JavaScript ................................................................................................................. 33
Section 6.1: typeof ....................................................................................................................................................... 33
Section 6.2: Finding an object's class ........................................................................................................................ 34
Section 6.3: Getting object type by constructor name ............................................................................................ 34
Chapter 7: Strings ....................................................................................................................................................... 37

400+ pages Section 7.1: Basic Info and String Concatenation ..................................................................................................... 37
Section 7.2: Reverse String ......................................................................................................................................... 38
Section 7.3: Comparing Strings Lexicographically ................................................................................................... 39
of professional hints and tricks Section 7.4: Access character at index in string ....................................................................................................... 40
Section 7.5: Escaping quotes ...................................................................................................................................... 40
Section 7.6: Word Counter .......................................................................................................................................... 41
Disclaimer
[Link] This is an unocial free book created for educational purposes and is
not aliated with ocial JavaScript® group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Section 7.7: Trim whitespace ...................................................................................................................................... 41 Section 12.4: Filtering Object Arrays .......................................................................................................................... 84
Section 7.8: Splitting a string into an array .............................................................................................................. 41 Section 12.5: Sorting Arrays ........................................................................................................................................ 86
Section 7.9: Strings are unicode ................................................................................................................................. 42 Section 12.6: Iteration .................................................................................................................................................. 88
Section 7.10: Detecting a string .................................................................................................................................. 42 Section 12.7: Destructuring an array ......................................................................................................................... 92
Section 7.11: Substrings with slice ............................................................................................................................... 43 Section 12.8: Removing duplicate elements ............................................................................................................. 93
Section 7.12: Character code ...................................................................................................................................... 43 Section 12.9: Array comparison ................................................................................................................................. 93
Section 7.13: String Representations of Numbers .................................................................................................... 43 Section 12.10: Reversing arrays .................................................................................................................................. 94
Section 7.14: String Find and Replace Functions ...................................................................................................... 44 Section 12.11: Shallow cloning an array ..................................................................................................................... 95
Section 7.15: Find the index of a substring inside a string ....................................................................................... 45 Section 12.12: Concatenating Arrays ......................................................................................................................... 95
Section 7.16: String to Upper Case ............................................................................................................................. 45 Section 12.13: Merge two array as key value pair .................................................................................................... 97
Section 7.17: String to Lower Case ............................................................................................................................. 46 Section 12.14: Array spread / rest .............................................................................................................................. 97
Section 7.18: Repeat a String ...................................................................................................................................... 46 Section 12.15: Filtering values ..................................................................................................................................... 98
Chapter 8: Date ........................................................................................................................................................... 47 Section 12.16: Searching an Array .............................................................................................................................. 99
Section 8.1: Create a new Date object ....................................................................................................................... 47 Section 12.17: Convert a String to an Array ............................................................................................................ 100
Section 8.2: Convert to a string format .................................................................................................................... 49 Section 12.18: Removing items from an array ........................................................................................................ 100
Section 8.3: Creating a Date from UTC ..................................................................................................................... 50 Section 12.19: Removing all elements ...................................................................................................................... 101
Section 8.4: Formatting a JavaScript date ............................................................................................................... 53 Section 12.20: Finding the minimum or maximum element .................................................................................. 102
Section 8.5: Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC ................................. 55 Section 12.21: Standard array initialization ............................................................................................................. 103
Section 8.6: Get the current time and date ............................................................................................................... 55 Section 12.22: Joining array elements in a string .................................................................................................. 104
Section 8.7: Increment a Date Object ....................................................................................................................... 56 Section 12.23: Removing/Adding elements using splice() .................................................................................... 105
Section 8.8: Convert to JSON ..................................................................................................................................... 57 Section 12.24: The entries() method ........................................................................................................................ 105
Section 12.25: Remove value from array ................................................................................................................ 105
Chapter 9: Date Comparison ................................................................................................................................ 58
Section 12.26: Flattening Arrays .............................................................................................................................. 106
Section 9.1: Comparing Date values .......................................................................................................................... 58
Section 12.27: Append / Prepend items to Array ................................................................................................... 107
Section 9.2: Date Dierence Calculation .................................................................................................................. 59
Section 12.28: Object keys and values to array ..................................................................................................... 107
Chapter 10: Comparison Operations ................................................................................................................ 60
Section 12.29: Logical connective of values ........................................................................................................... 108
Section 10.1: Abstract equality / inequality and type conversion ........................................................................... 60
Section 12.30: Checking if an object is an Array .................................................................................................... 108
Section 10.2: NaN Property of the Global Object ..................................................................................................... 61
Section 12.31: Insert an item into an array at a specific index .............................................................................. 109
Section 10.3: Short-circuiting in boolean operators ................................................................................................. 63
Section 12.32: Sorting multidimensional array ....................................................................................................... 109
Section 10.4: Null and Undefined ............................................................................................................................... 65
Section 12.33: Test all array items for equality ...................................................................................................... 110
Section 10.5: Abstract Equality (==) ........................................................................................................................... 65
Section 12.34: Copy part of an Array ...................................................................................................................... 110
Section 10.6: Logic Operators with Booleans ........................................................................................................... 66
Chapter 13: Objects .................................................................................................................................................. 112
Section 10.7: Automatic Type Conversions ............................................................................................................... 67
Section 13.1: Shallow cloning ..................................................................................................................................... 112
Section 10.8: Logic Operators with Non-boolean values (boolean coercion) ....................................................... 67
Section 13.2: [Link] ........................................................................................................................................ 112
Section 10.9: Empty Array ........................................................................................................................................... 68
Section 13.3: Object cloning ...................................................................................................................................... 113
Section 10.10: Equality comparison operations ........................................................................................................ 68
Section 13.4: Object properties iteration ................................................................................................................. 114
Section 10.11: Relational operators (<, <=, >, >=) ........................................................................................................ 70
Section 13.5: [Link] ........................................................................................................................................ 115
Section 10.12: Inequality .............................................................................................................................................. 71
Section 13.6: Object rest/spread (...) ........................................................................................................................ 116
Section 10.13: List of Comparison Operators ............................................................................................................ 72
Section 13.7: [Link]fineProperty ......................................................................................................................... 116
Section 10.14: Grouping multiple logic statements ................................................................................................... 72
Section 13.8: Accesor properties (get and set) ....................................................................................................... 117
Section 10.15: Bit fields to optimise comparison of multi state data ...................................................................... 72
Section 13.9: Dynamic / variable property names ................................................................................................ 117
Chapter 11: Conditions .............................................................................................................................................. 74
Section 13.10: Arrays are Objects ............................................................................................................................. 118
Section 11.1: Ternary operators .................................................................................................................................. 74
Section 13.11: [Link] ........................................................................................................................................... 119
Section 11.2: Switch statement .................................................................................................................................... 75
Section 13.12: Convert object's values to array ...................................................................................................... 120
Section 11.3: If / Else If / Else Control ......................................................................................................................... 77
Section 13.13: Retrieving properties from an object ............................................................................................... 120
Section 11.4: Strategy ................................................................................................................................................... 78
Section 13.14: Read-Only property ........................................................................................................................... 123
Section 11.5: Using || and && short circuiting ............................................................................................................. 79
Section 13.15: Non enumerable property ................................................................................................................ 123
Chapter 12: Arrays ...................................................................................................................................................... 80 Section 13.16: Lock property description ................................................................................................................. 123
Section 12.1: Converting Array-like Objects to Arrays ............................................................................................. 80 Section 13.17: [Link] ................................................................................................... 124
Section 12.2: Reducing values .................................................................................................................................... 82 Section 13.18: Descriptors and Named Properties ................................................................................................. 124
Section 12.3: Mapping values ..................................................................................................................................... 84 Section 13.19: [Link] ......................................................................................................................................... 126
Section 13.20: Properties with special characters or reserved words .................................................................. 126 Section 18.7: "do ... while" loop .................................................................................................................................. 161
Section 13.21: Creating an Iterable object ............................................................................................................... 127 Section 18.8: Break and continue labels ................................................................................................................. 161
Section 13.22: Iterating over Object entries - [Link]() .............................................................................. 127 Chapter 19: Functions ............................................................................................................................................. 163
Section 13.23: [Link]() ................................................................................................................................... 128 Section 19.1: Function Scoping .................................................................................................................................. 163
Chapter 14: Arithmetic (Math) ........................................................................................................................... 129 Section 19.2: Currying ................................................................................................................................................ 164
Section 14.1: Constants .............................................................................................................................................. 129 Section 19.3: Immediately Invoked Function Expressions ..................................................................................... 165
Section 14.2: Remainder / Modulus (%) .................................................................................................................. 129 Section 19.4: Named Functions ................................................................................................................................ 166
Section 14.3: Rounding .............................................................................................................................................. 130 Section 19.5: Binding `this` and arguments ............................................................................................................. 169
Section 14.4: Trigonometry ....................................................................................................................................... 132 Section 19.6: Functions with an Unknown Number of Arguments (variadic functions) ..................................... 171
Section 14.5: Bitwise operators ................................................................................................................................ 133 Section 19.7: Anonymous Function .......................................................................................................................... 172
Section 14.6: Incrementing (++) ................................................................................................................................ 135 Section 19.8: Default parameters ............................................................................................................................ 174
Section 14.7: Exponentiation ([Link]() or **) ..................................................................................................... 135 Section 19.9: Call and apply ...................................................................................................................................... 176
Section 14.8: Random Integers and Floats ............................................................................................................. 136 Section 19.10: Partial Application .............................................................................................................................. 177
Section 14.9: Addition (+) .......................................................................................................................................... 137 Section 19.11: Passing arguments by reference or value ....................................................................................... 178
Section 14.10: Little / Big endian for typed arrays when using bitwise operators .............................................. 137 Section 19.12: Function Arguments, "arguments" object, rest and spread parameters .................................... 179
Section 14.11: Get Random Between Two Numbers ............................................................................................... 138 Section 19.13: Function Composition ........................................................................................................................ 179
Section 14.12: Simulating events with dierent probabilities ................................................................................. 139 Section 19.14: Get the name of a function object ................................................................................................... 180
Section 14.13: Subtraction (-) .................................................................................................................................... 140 Section 19.15: Recursive Function ............................................................................................................................. 180
Section 14.14: Multiplication (*) ................................................................................................................................. 140 Section 19.16: Using the Return Statement ............................................................................................................. 181
Section 14.15: Getting maximum and minimum ..................................................................................................... 140 Section 19.17: Functions as a variable ..................................................................................................................... 182
Section 14.16: Restrict Number to Min/Max Range ................................................................................................ 141 Chapter 20: Functional JavaScript .................................................................................................................. 185
Section 14.17: Ceiling and Floor ................................................................................................................................ 141 Section 20.1: Higher-Order Functions ...................................................................................................................... 185
Section 14.18: Getting roots of a number ................................................................................................................ 142 Section 20.2: Identity Monad ................................................................................................................................... 185
Section 14.19: Random with gaussian distribution ................................................................................................. 142 Section 20.3: Pure Functions .................................................................................................................................... 187
Section 14.20: Math.atan2 to find direction ............................................................................................................ 143 Section 20.4: Accepting Functions as Arguments ................................................................................................. 188
Section 14.21: Sin & Cos to create a vector given direction & distance ............................................................... 143
Chapter 21: Prototypes, objects ........................................................................................................................ 190
Section 14.22: [Link] ......................................................................................................................................... 144
Section 21.1: Creation and initialising Prototype ..................................................................................................... 190
Section 14.23: Periodic functions using [Link] .................................................................................................... 145
Chapter 22: Classes ................................................................................................................................................. 192
Section 14.24: Division (/) ......................................................................................................................................... 146
Section 22.1: Class Constructor ................................................................................................................................ 192
Section 14.25: Decrementing (--) ............................................................................................................................. 146
Section 22.2: Class Inheritance ................................................................................................................................ 192
Chapter 15: Bitwise operators ............................................................................................................................ 148
Section 22.3: Static Methods .................................................................................................................................... 193
Section 15.1: Bitwise operators ................................................................................................................................. 148
Section 22.4: Getters and Setters ............................................................................................................................ 193
Section 15.2: Shift Operators .................................................................................................................................... 150
Section 22.5: Private Members ................................................................................................................................ 194
Chapter 16: Constructor functions ................................................................................................................... 151 Section 22.6: Methods ............................................................................................................................................... 195
Section 16.1: Declaring a constructor function ........................................................................................................ 151 Section 22.7: Dynamic Method Names ................................................................................................................... 195
Chapter 17: Declarations and Assignments ................................................................................................ 152 Section 22.8: Managing Private Data with Classes ............................................................................................... 196
Section 17.1: Modifying constants ............................................................................................................................ 152 Section 22.9: Class Name binding ........................................................................................................................... 198
Section 17.2: Declaring and initializing constants .................................................................................................. 152 Chapter 23: Namespacing .................................................................................................................................... 199
Section 17.3: Declaration ........................................................................................................................................... 152 Section 23.1: Namespace by direct assignment .................................................................................................... 199
Section 17.4: Undefined ............................................................................................................................................. 153 Section 23.2: Nested Namespaces .......................................................................................................................... 199
Section 17.5: Data Types ........................................................................................................................................... 153
Chapter 24: Context (this) .................................................................................................................................... 200
Section 17.6: Mathematic operations and assignment .......................................................................................... 153
Section 24.1: this with simple objects ....................................................................................................................... 200
Section 17.7: Assignment ........................................................................................................................................... 155
Section 24.2: Saving this for use in nested functions / objects ............................................................................ 200
Chapter 18: Loops ..................................................................................................................................................... 156 Section 24.3: Binding function context .................................................................................................................... 201
Section 18.1: Standard "for" loops ............................................................................................................................ 156 Section 24.4: this in constructor functions .............................................................................................................. 202
Section 18.2: "for ... of" loop ...................................................................................................................................... 157
Chapter 25: Setters and Getters ...................................................................................................................... 203
Section 18.3: "for ... in" loop ....................................................................................................................................... 159
Section 25.1: Defining a Setter/Getter Using [Link]fineProperty ................................................................... 203
Section 18.4: "while" Loops ....................................................................................................................................... 159
Section 25.2: Defining an Setter/Getter in a Newly Created Object ................................................................... 203
Section 18.5: "continue" a loop ................................................................................................................................. 160
Section 25.3: Defining getters and setters in ES6 class ......................................................................................... 203
Section 18.6: Break specific nested loops ............................................................................................................... 161
Chapter 26: Events ................................................................................................................................................... 205 Section 34.1: Accessing data attributes ................................................................................................................... 233
Section 26.1: Page, DOM and Browser loading ...................................................................................................... 205 Chapter 35: JSON ..................................................................................................................................................... 234
Chapter 27: Inheritance ......................................................................................................................................... 206 Section 35.1: JSON versus JavaScript literals ......................................................................................................... 234
Section 27.1: Standard function prototype ............................................................................................................. 206 Section 35.2: Parsing with a reviver function ......................................................................................................... 235
Section 27.2: Dierence between [Link] and [Link] ............................................................ 206 Section 35.3: Serializing a value ............................................................................................................................... 236
Section 27.3: Prototypal inheritance ....................................................................................................................... 206 Section 35.4: Serializing and restoring class instances ......................................................................................... 237
Section 27.4: Pseudo-classical inheritance ............................................................................................................. 207 Section 35.5: Serializing with a replacer function .................................................................................................. 238
Section 27.5: Setting an Object's prototype ........................................................................................................... 208 Section 35.6: Parsing a simple JSON string ............................................................................................................ 239
Section 35.7: Cyclic object values ............................................................................................................................ 239
Chapter 28: Method Chaining ............................................................................................................................. 210
Section 28.1: Chainable object design and chaining .............................................................................................. 210 Chapter 36: AJAX ...................................................................................................................................................... 240
Section 28.2: Method Chaining ................................................................................................................................ 212 Section 36.1: Sending and Receiving JSON Data via POST .................................................................................. 240
Section 36.2: Add an AJAX preloader ..................................................................................................................... 240
Chapter 29: Callbacks ............................................................................................................................................. 213
Section 36.3: Displaying the top JavaScript questions of the month from Stack Overflow's API .................... 241
Section 29.1: Simple Callback Usage Examples ..................................................................................................... 213
Section 36.4: Using GET with parameters ............................................................................................................... 242
Section 29.2: Continuation (synchronous and asynchronous) ............................................................................ 214
Section 36.5: Check if a file exists via a HEAD request .......................................................................................... 243
Section 29.3: What is a callback? ............................................................................................................................ 215
Section 36.6: Using GET and no parameters .......................................................................................................... 243
Section 29.4: Callbacks and `this` ............................................................................................................................ 216
Section 36.7: Listening to AJAX events at a global level ....................................................................................... 243
Section 29.5: Callback using Arrow function .......................................................................................................... 217
Section 29.6: Error handling and control-flow branching ..................................................................................... 218 Chapter 37: Enumerations ................................................................................................................................... 244
Section 37.1: Enum definition using [Link]() ............................................................................................... 244
Chapter 30: Intervals and Timeouts ............................................................................................................... 219
Section 37.2: Alternate definition ............................................................................................................................. 244
Section 30.1: Recursive setTimeout ......................................................................................................................... 219
Section 37.3: Printing an enum variable ................................................................................................................. 244
Section 30.2: Intervals ............................................................................................................................................... 219
Section 37.4: Implementing Enums Using Symbols ............................................................................................... 245
Section 30.3: Intervals ............................................................................................................................................... 219
Section 37.5: Automatic Enumeration Value .......................................................................................................... 245
Section 30.4: Removing intervals ............................................................................................................................ 220
Section 30.5: Removing timeouts ............................................................................................................................ 220 Chapter 38: Map ........................................................................................................................................................ 247
Section 30.6: setTimeout, order of operations, clearTimeout .............................................................................. 220 Section 38.1: Creating a Map .................................................................................................................................... 247
Section 38.2: Clearing a Map ................................................................................................................................... 247
Chapter 31: Regular expressions ....................................................................................................................... 222
Section 38.3: Removing an element from a Map .................................................................................................. 247
Section 31.1: Creating a RegExp Object ................................................................................................................... 222
Section 38.4: Checking if a key exists in a Map ...................................................................................................... 248
Section 31.2: RegExp Flags ....................................................................................................................................... 222
Section 38.5: Iterating Maps ..................................................................................................................................... 248
Section 31.3: Check if string contains pattern using .test() .................................................................................... 223
Section 38.6: Getting and setting elements ............................................................................................................ 248
Section 31.4: Matching With .exec() ......................................................................................................................... 223
Section 38.7: Getting the number of elements of a Map ...................................................................................... 249
Section 31.5: Using RegExp With Strings ................................................................................................................. 223
Section 31.6: RegExp Groups .................................................................................................................................... 224 Chapter 39: Timestamps ....................................................................................................................................... 250
Section 31.7: Replacing string match with a callback function ............................................................................. 225 Section 39.1: High-resolution timestamps ............................................................................................................... 250
Section 31.8: Using [Link]() with parentheses regex to extract matches of a string ................................ 226 Section 39.2: Get Timestamp in Seconds ................................................................................................................ 250
Section 39.3: Low-resolution timestamps ............................................................................................................... 250
Chapter 32: Cookies ................................................................................................................................................. 228
Section 39.4: Support for legacy browsers ............................................................................................................. 250
Section 32.1: Test if cookies are enabled ................................................................................................................ 228
Section 32.2: Adding and Setting Cookies .............................................................................................................. 228 Chapter 40: Unary Operators ........................................................................................................................... 251
Section 32.3: Reading cookies ................................................................................................................................. 228 Section 40.1: Overview .............................................................................................................................................. 251
Section 32.4: Removing cookies .............................................................................................................................. 228 Section 40.2: The typeof operator .......................................................................................................................... 251
Section 40.3: The delete operator ........................................................................................................................... 252
Chapter 33: Web Storage ..................................................................................................................................... 229
Section 40.4: The unary plus operator (+) .............................................................................................................. 253
Section 33.1: Using localStorage .............................................................................................................................. 229
Section 40.5: The void operator .............................................................................................................................. 254
Section 33.2: Simpler way of handling Storage ..................................................................................................... 229
Section 40.6: The unary negation operator (-) ...................................................................................................... 255
Section 33.3: Storage events .................................................................................................................................... 230
Section 40.7: The bitwise NOT operator (~) ............................................................................................................ 255
Section 33.4: sessionStorage .................................................................................................................................... 231
Section 40.8: The logical NOT operator (!) ............................................................................................................. 256
Section 33.5: localStorage length ............................................................................................................................ 232
Section 33.6: Error conditions ................................................................................................................................... 232 Chapter 41: Generators ......................................................................................................................................... 258
Section 33.7: Clearing storage ................................................................................................................................. 232 Section 41.1: Generator Functions ............................................................................................................................ 258
Section 33.8: Remove Storage Item ........................................................................................................................ 232 Section 41.2: Sending Values to Generator ............................................................................................................. 259
Section 41.3: Delegating to other Generator .......................................................................................................... 259
Chapter 34: Data attributes ............................................................................................................................... 233
Section 41.4: Iteration ................................................................................................................................................ 259 Chapter 49: The Event Loop ............................................................................................................................... 292
Section 41.5: Async flow with generators ................................................................................................................ 260 Section 49.1: The event loop in a web browser ...................................................................................................... 292
Section 41.6: Iterator-Observer interface ................................................................................................................ 261 Section 49.2: Asynchronous operations and the event loop ................................................................................ 293
Chapter 42: Promises ............................................................................................................................................. 263 Chapter 50: Strict mode ....................................................................................................................................... 294
Section 42.1: Introduction .......................................................................................................................................... 263 Section 50.1: For entire scripts ................................................................................................................................. 294
Section 42.2: Promise chaining ................................................................................................................................ 264 Section 50.2: For functions ....................................................................................................................................... 294
Section 42.3: Waiting for multiple concurrent promises ....................................................................................... 265 Section 50.3: Changes to properties ....................................................................................................................... 294
Section 42.4: Reduce an array to chained promises ............................................................................................ 266 Section 50.4: Changes to global properties ........................................................................................................... 295
Section 42.5: Waiting for the first of multiple concurrent promises .................................................................... 267 Section 50.5: Duplicate Parameters ........................................................................................................................ 296
Section 42.6: "Promisifying" functions with callbacks ........................................................................................... 268 Section 50.6: Function scoping in strict mode ........................................................................................................ 296
Section 42.7: Error Handling .................................................................................................................................... 268 Section 50.7: Behaviour of a function's arguments list ......................................................................................... 296
Section 42.8: Reconciling synchronous and asynchronous operations .............................................................. 272 Section 50.8: Non-Simple parameter lists .............................................................................................................. 297
Section 42.9: Delay function call .............................................................................................................................. 273
Chapter 51: Custom Elements ............................................................................................................................ 299
Section 42.10: "Promisifying" values ........................................................................................................................ 273
Section 51.1: Extending Native Elements ................................................................................................................. 299
Section 42.11: Using ES2017 async/await ................................................................................................................ 274
Section 51.2: Registering New Elements ................................................................................................................. 299
Section 42.12: Performing cleanup with finally() .................................................................................................... 274
Chapter 52: Data Manipulation ......................................................................................................................... 300
Section 42.13: forEach with promises ...................................................................................................................... 275
Section 52.1: Format numbers as money ............................................................................................................... 300
Section 42.14: Asynchronous API request ............................................................................................................... 275
Section 52.2: Extract extension from file name ..................................................................................................... 300
Chapter 43: Set .......................................................................................................................................................... 277
Section 52.3: Set object property given its string name ....................................................................................... 301
Section 43.1: Creating a Set ...................................................................................................................................... 277
Chapter 53: Binary Data ....................................................................................................................................... 302
Section 43.2: Adding a value to a Set ..................................................................................................................... 277
Section 53.1: Getting binary representation of an image file ............................................................................... 302
Section 43.3: Removing value from a set ............................................................................................................... 277
Section 53.2: Converting between Blobs and ArrayBuers ................................................................................. 302
Section 43.4: Checking if a value exist in a set ....................................................................................................... 278
Section 53.3: Manipulating ArrayBuers with DataViews ..................................................................................... 303
Section 43.5: Clearing a Set ...................................................................................................................................... 278
Section 53.4: Creating a TypedArray from a Base64 string ................................................................................. 303
Section 43.6: Getting set length ............................................................................................................................... 278
Section 53.5: Using TypedArrays ............................................................................................................................. 304
Section 43.7: Converting Sets to arrays .................................................................................................................. 278
Section 53.6: Iterating through an arrayBuer ...................................................................................................... 304
Section 43.8: Intersection and dierence in Sets ................................................................................................... 279
Section 43.9: Iterating Sets ....................................................................................................................................... 279 Chapter 54: Template Literals .......................................................................................................................... 306
Section 54.1: Basic interpolation and multiline strings ........................................................................................... 306
Chapter 44: Modals - Prompts .......................................................................................................................... 280
Section 54.2: Tagged strings ................................................................................................................................... 306
Section 44.1: About User Prompts ........................................................................................................................... 280
Section 54.3: Raw strings .......................................................................................................................................... 307
Section 44.2: Persistent Prompt Modal ................................................................................................................... 280
Section 54.4: Templating HTML With Template Strings ....................................................................................... 307
Section 44.3: Confirm to Delete element ................................................................................................................ 281
Section 54.5: Introduction ......................................................................................................................................... 308
Section 44.4: Usage of alert() .................................................................................................................................. 281
Section 44.5: Usage of prompt() ............................................................................................................................. 282 Chapter 55: Fetch ..................................................................................................................................................... 309
Section 55.1: Getting JSON data .............................................................................................................................. 309
Chapter 45: execCommand and contenteditable ................................................................................... 283
Section 55.2: Set Request Headers ......................................................................................................................... 309
Section 45.1: Listening to Changes of contenteditable .......................................................................................... 284
Section 55.3: POST Data ........................................................................................................................................... 309
Section 45.2: Getting started .................................................................................................................................... 284
Section 55.4: Send cookies ....................................................................................................................................... 310
Section 45.3: Copy to clipboard from textarea using execCommand("copy") .................................................. 285
Section 55.5: GlobalFetch ......................................................................................................................................... 310
Section 45.4: Formatting .......................................................................................................................................... 285
Section 55.6: Using Fetch to Display Questions from the Stack Overflow API ................................................... 310
Chapter 46: History ................................................................................................................................................. 287
Chapter 56: Scope .................................................................................................................................................... 311
Section 46.1: [Link]() .............................................................................................................................. 287
Section 56.1: Closures ................................................................................................................................................ 311
Section 46.2: [Link]() ........................................................................................................................ 287
Section 56.2: Hoisting ................................................................................................................................................ 312
Section 46.3: Load a specific URL from the history list ......................................................................................... 287
Section 56.3: Dierence between var and let ........................................................................................................ 315
Chapter 47: Navigator Object ........................................................................................................................... 289
Section 56.4: Apply and Call syntax and invocation ............................................................................................. 317
Section 47.1: Get some basic browser data and return it as a JSON object ...................................................... 289
Section 56.5: Arrow function invocation ................................................................................................................. 318
Chapter 48: BOM (Browser Object Model) .................................................................................................. 290 Section 56.6: Bound invocation ................................................................................................................................ 319
Section 48.1: Introduction .......................................................................................................................................... 290 Section 56.7: Method invocation .............................................................................................................................. 319
Section 48.2: Window Object Properties ................................................................................................................. 290 Section 56.8: Anonymous invocation ...................................................................................................................... 320
Section 48.3: Window Object Methods .................................................................................................................... 291 Section 56.9: Constructor invocation ...................................................................................................................... 320
Section 56.10: Using let in loops instead of var (click handlers example) ........................................................... 320 Chapter 63: Workers ............................................................................................................................................... 340
Chapter 57: Modules ............................................................................................................................................... 322 Section 63.1: Web Worker ......................................................................................................................................... 340
Section 57.1: Defining a module ............................................................................................................................... 322 Section 63.2: A simple service worker ..................................................................................................................... 340
Section 57.2: Default exports ................................................................................................................................... 322 Section 63.3: Register a service worker .................................................................................................................. 341
Section 57.3: Importing named members from another module ........................................................................ 323 Section 63.4: Communicating with a Web Worker ................................................................................................ 341
Section 57.4: Importing an entire module .............................................................................................................. 323 Section 63.5: Terminate a worker ............................................................................................................................ 342
Section 57.5: Importing named members with aliases ......................................................................................... 324 Section 63.6: Populating your cache ....................................................................................................................... 343
Section 57.6: Importing with side eects ................................................................................................................ 324 Section 63.7: Dedicated Workers and Shared Workers ........................................................................................ 343
Section 57.7: Exporting multiple named members ................................................................................................ 324 Chapter 64: requestAnimationFrame ............................................................................................................ 345
Chapter 58: Screen .................................................................................................................................................. 325 Section 64.1: Use requestAnimationFrame to fade in element ............................................................................ 345
Section 58.1: Getting the screen resolution ............................................................................................................. 325 Section 64.2: Keeping Compatibility ....................................................................................................................... 346
Section 58.2: Getting the “available” area of the screen ...................................................................................... 325 Section 64.3: Cancelling an Animation .................................................................................................................... 346
Section 58.3: Page width and height ....................................................................................................................... 325 Chapter 65: Creational Design Patterns ....................................................................................................... 348
Section 58.4: Window innerWidth and innerHeight Properties ............................................................................ 325 Section 65.1: Factory Functions ................................................................................................................................ 348
Section 58.5: Getting color information about the screen .................................................................................... 325 Section 65.2: Factory with Composition .................................................................................................................. 349
Chapter 59: Variable coercion/conversion ................................................................................................. 326 Section 65.3: Module and Revealing Module Patterns .......................................................................................... 350
Section 59.1: Double Negation (!!x) .......................................................................................................................... 326 Section 65.4: Prototype Pattern ............................................................................................................................... 352
Section 59.2: Implicit conversion ............................................................................................................................. 326 Section 65.5: Singleton Pattern ................................................................................................................................ 353
Section 59.3: Converting to boolean ....................................................................................................................... 326 Section 65.6: Abstract Factory Pattern ................................................................................................................... 354
Section 59.4: Converting a string to a number ...................................................................................................... 327 Chapter 66: Detecting browser ......................................................................................................................... 355
Section 59.5: Converting a number to a string ...................................................................................................... 328 Section 66.1: Feature Detection Method ................................................................................................................. 355
Section 59.6: Primitive to Primitive conversion table ............................................................................................. 328 Section 66.2: User Agent Detection ......................................................................................................................... 355
Section 59.7: Convert an array to a string ............................................................................................................. 328 Section 66.3: Library Method ................................................................................................................................... 356
Section 59.8: Array to String using array methods ............................................................................................... 329
Chapter 67: Symbols ............................................................................................................................................... 357
Section 59.9: Converting a number to a boolean .................................................................................................. 329
Section 67.1: Basics of symbol primitive type ......................................................................................................... 357
Section 59.10: Converting a string to a boolean .................................................................................................... 329
Section 67.2: Using [Link]() to create global, shared symbols .................................................................... 357
Section 59.11: Integer to Float ................................................................................................................................... 329
Section 67.3: Converting a symbol into a string .................................................................................................... 357
Section 59.12: Float to Integer .................................................................................................................................. 330
Chapter 68: Transpiling ......................................................................................................................................... 359
Section 59.13: Convert string to float ....................................................................................................................... 330
Section 68.1: Introduction to Transpiling ................................................................................................................. 359
Chapter 60: Destructuring assignment ......................................................................................................... 331
Section 68.2: Start using ES6/7 with Babel ............................................................................................................. 360
Section 60.1: Destructuring Objects ......................................................................................................................... 331
Chapter 69: Automatic Semicolon Insertion - ASI .................................................................................... 361
Section 60.2: Destructuring function arguments ................................................................................................... 332
Section 69.1: Avoid semicolon insertion on return statements ............................................................................. 361
Section 60.3: Nested Destructuring ......................................................................................................................... 332
Section 69.2: Rules of Automatic Semicolon Insertion .......................................................................................... 361
Section 60.4: Destructuring Arrays .......................................................................................................................... 333
Section 69.3: Statements aected by automatic semicolon insertion ................................................................ 362
Section 60.5: Destructuring inside variables .......................................................................................................... 333
Section 60.6: Default Value While Destructuring ................................................................................................... 334 Chapter 70: Localization ....................................................................................................................................... 364
Section 60.7: Renaming Variables While Destructuring ........................................................................................ 334 Section 70.1: Number formatting ............................................................................................................................. 364
Section 70.2: Currency formatting .......................................................................................................................... 364
Chapter 61: WebSockets ....................................................................................................................................... 335
Section 70.3: Date and time formatting .................................................................................................................. 364
Section 61.1: Working with string messages ........................................................................................................... 335
Section 61.2: Establish a web socket connection ................................................................................................... 335 Chapter 71: Geolocation ........................................................................................................................................ 365
Section 61.3: Working with binary messages ......................................................................................................... 335 Section 71.1: Get updates when a user's location changes ................................................................................... 365
Section 61.4: Making a secure web socket connection ......................................................................................... 336 Section 71.2: Get a user's latitude and longitude ................................................................................................... 365
Section 71.3: More descriptive error codes ............................................................................................................. 365
Chapter 62: Arrow Functions .............................................................................................................................. 337
Section 62.1: Introduction .......................................................................................................................................... 337 Chapter 72: IndexedDB .......................................................................................................................................... 367
Section 62.2: Lexical Scoping & Binding (Value of "this") ..................................................................................... 337 Section 72.1: Opening a database ........................................................................................................................... 367
Section 62.3: Arguments Object .............................................................................................................................. 338 Section 72.2: Adding objects .................................................................................................................................... 367
Section 62.4: Implicit Return ..................................................................................................................................... 338 Section 72.3: Retrieving data ................................................................................................................................... 368
Section 62.5: Arrow functions as a constructor ..................................................................................................... 339 Section 72.4: Testing for IndexedDB availability .................................................................................................... 369
Section 62.6: Explicit Return ..................................................................................................................................... 339 Chapter 73: Modularization Techniques ....................................................................................................... 370
Section 73.1: ES6 Modules ......................................................................................................................................... 370
Section 73.2: Universal Module Definition (UMD) .................................................................................................. 370 Chapter 85: Bitwise Operators - Real World Examples (snippets) ................................................. 401
Section 73.3: Immediately invoked function expressions (IIFE) ............................................................................ 371 Section 85.1: Swapping Two Integers with Bitwise XOR (without additional memory allocation) .................... 401
Section 73.4: Asynchronous Module Definition (AMD) .......................................................................................... 371 Section 85.2: Faster multiplication or division by powers of 2 ............................................................................. 401
Section 73.5: CommonJS - [Link] .......................................................................................................................... 372 Section 85.3: Number's Parity Detection with Bitwise AND .................................................................................. 401
Chapter 74: Proxy .................................................................................................................................................... 374 Chapter 86: Tilde ~ ................................................................................................................................................... 403
Section 74.1: Proxying property lookup .................................................................................................................. 374 Section 86.1: ~ Integer ............................................................................................................................................... 403
Section 74.2: Very simple proxy (using the set trap) ............................................................................................ 374 Section 86.2: ~~ Operator ......................................................................................................................................... 403
Chapter 75: .postMessage() and MessageEvent ...................................................................................... 376 Section 86.3: Converting Non-numeric values to Numbers .................................................................................. 404
Section 75.1: Getting Started .................................................................................................................................... 376 Section 86.4: Shorthands .......................................................................................................................................... 404
Chapter 76: WeakMap ............................................................................................................................................ 379 Section 86.5: ~ Decimal ............................................................................................................................................. 404
Section 76.1: Creating a WeakMap object .............................................................................................................. 379 Chapter 87: Using JavaScript to get/set CSS custom variables ..................................................... 406
Section 76.2: Getting a value associated to the key .............................................................................................. 379 Section 87.1: How to get and set CSS variable property values ........................................................................... 406
Section 76.3: Assigning a value to the key ............................................................................................................. 379 Chapter 88: Selection API ..................................................................................................................................... 407
Section 76.4: Checking if an element with the key exists ...................................................................................... 379 Section 88.1: Get the text of the selection ............................................................................................................... 407
Section 76.5: Removing an element with the key .................................................................................................. 380 Section 88.2: Deselect everything that is selected ................................................................................................ 407
Section 76.6: Weak reference demo ....................................................................................................................... 380 Section 88.3: Select the contents of an element .................................................................................................... 407
Chapter 77: WeakSet .............................................................................................................................................. 382 Chapter 89: File API, Blobs and FileReaders ............................................................................................... 408
Section 77.1: Creating a WeakSet object ................................................................................................................ 382 Section 89.1: Read file as string ............................................................................................................................... 408
Section 77.2: Adding a value .................................................................................................................................... 382 Section 89.2: Read file as dataURL ......................................................................................................................... 408
Section 77.3: Checking if a value exists ................................................................................................................... 382 Section 89.3: Slice a file ............................................................................................................................................. 409
Section 77.4: Removing a value ............................................................................................................................... 382 Section 89.4: Get the properties of the file ............................................................................................................. 409
Chapter 78: Escape Sequences ......................................................................................................................... 383 Section 89.5: Selecting multiple files and restricting file types ............................................................................. 410
Section 78.1: Entering special characters in strings and regular expressions .................................................... 383 Section 89.6: Client side csv download using Blob ................................................................................................ 410
Section 78.2: Escape sequence types ..................................................................................................................... 383 Chapter 90: Notifications API ............................................................................................................................. 411
Chapter 79: Behavioral Design Patterns ...................................................................................................... 386 Section 90.1: Requesting Permission to send notifications ................................................................................... 411
Section 79.1: Observer pattern ................................................................................................................................. 386 Section 90.2: Sending Notifications ......................................................................................................................... 411
Section 79.2: Mediator Pattern ................................................................................................................................ 387 Section 90.3: Closing a notification ......................................................................................................................... 411
Section 79.3: Command ............................................................................................................................................ 388 Section 90.4: Notification events ............................................................................................................................. 412
Section 79.4: Iterator ................................................................................................................................................. 389 Chapter 91: Vibration API ...................................................................................................................................... 413
Chapter 80: Server-sent events ........................................................................................................................ 391 Section 91.1: Single vibration ..................................................................................................................................... 413
Section 80.1: Setting up a basic event stream to the server ................................................................................. 391 Section 91.2: Check for support ............................................................................................................................... 413
Section 80.2: Closing an event stream ................................................................................................................... 391 Section 91.3: Vibration patterns ............................................................................................................................... 413
Section 80.3: Binding event listeners to EventSource ........................................................................................... 391 Chapter 92: Battery Status API ......................................................................................................................... 414
Chapter 81: Async functions (async/await) ................................................................................................ 393 Section 92.1: Battery Events ..................................................................................................................................... 414
Section 81.1: Introduction .......................................................................................................................................... 393 Section 92.2: Getting current battery level ............................................................................................................. 414
Section 81.2: Await and operator precedence ....................................................................................................... 393 Section 92.3: Is battery charging? ........................................................................................................................... 414
Section 81.3: Async functions compared to Promises ........................................................................................... 394 Section 92.4: Get time left until battery is empty ................................................................................................... 414
Section 81.4: Looping with async await ................................................................................................................... 395 Section 92.5: Get time left until battery is fully charged ....................................................................................... 414
Section 81.5: Less indentation .................................................................................................................................. 396 Chapter 93: Fluent API ............................................................................................................................................ 415
Section 81.6: Simultaneous async (parallel) operations ........................................................................................ 397 Section 93.1: Fluent API capturing construction of HTML articles with JS ........................................................... 415
Chapter 82: Async Iterators ................................................................................................................................ 398 Chapter 94: Web Cryptography API ............................................................................................................... 417
Section 82.1: Basics ................................................................................................................................................... 398 Section 94.1: Creating digests (e.g. SHA-256) ......................................................................................................... 417
Chapter 83: How to make iterator usable inside async callback function ................................. 399 Section 94.2: Cryptographically random data ....................................................................................................... 417
Section 83.1: Erroneous code, can you spot why this usage of key will lead to bugs? ...................................... 399 Section 94.3: Generating RSA key pair and converting to PEM format .............................................................. 418
Section 83.2: Correct Writing ................................................................................................................................... 399 Section 94.4: Converting PEM key pair to CryptoKey ........................................................................................... 419
Chapter 84: Tail Call Optimization .................................................................................................................. 400 Chapter 95: Security issues ................................................................................................................................. 421
Section 84.1: What is Tail Call Optimization (TCO) ................................................................................................ 400 Section 95.1: Reflected Cross-site scripting (XSS) .................................................................................................. 421
Section 84.2: Recursive loops .................................................................................................................................. 400 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 Credits ............................................................................................................................................................................ 463
Section 95.5: Evaled JSON injection ........................................................................................................................ 424
You may also like ...................................................................................................................................................... 474
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 [Link] 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
Appendix A: Reserved Keywords ...................................................................................................................... 459
Section A.1: Reserved Keywords .............................................................................................................................. 459
Section A.2: Identifiers & Identifier Names ............................................................................................................. 461
About Chapter 1: Getting started with JavaScript
Version Release Date
1 1997-06-01
2 1998-06-01
3 1998-12-01
E4X 2004-06-01
5 2009-12-01
5.1 2011-06-01
Please feel free to share this PDF with anyone for free, 6 2015-06-01
latest version of this book can be downloaded from: 7 2016-06-14
[Link] 8 2017-06-27

This JavaScript® Notes for Professionals book is compiled from Stack Overflow
Section 1.1: Using [Link]()
Documentation, the content is written by the beautiful people at Stack Overflow. Introduction
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright All modern web browsers, [Link] as well as almost every other JavaScript environments support writing messages
of their respective owners unless otherwise specified to a console using a suite of logging methods. The most common of these methods is [Link]().

This is an unofficial free book created for educational purposes and is not In a browser environment, the [Link]() function is predominantly used for debugging purposes.
affiliated with official JavaScript® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners Getting Started

The information presented in this book is not guaranteed to be correct nor Open up the JavaScript Console in your browser, type the following, and press Enter :
accurate, use at your own risk
[Link]("Hello, World!");
Please send feedback and corrections to web@[Link]
This will log the following to the console:

In the example above, the [Link]() function prints Hello, World! to the console and returns undefined
(shown above in the console output window). This is because [Link]() has no explicit return value.

Logging variables

[Link]() can be used to log variables of any kind; not only strings. Just pass in the variable that you want to
be displayed in the console, for example:

var foo = "bar";


[Link](foo);

This will log the following to the console:

[Link] – JavaScript® Notes for Professionals 1 [Link] – JavaScript® Notes for Professionals 2
'Title': 'user2'
});

This will log the following to the console:

If you want to log two or more values, simply separate them with commas. Spaces will be automatically added
between each argument during concatenation:

var thisVar = 'first value';


var thatVar = 'second value';
[Link]("thisVar:", thisVar, "and thatVar:", thatVar);

This will log the following to the console: Logging HTML elements

You have the ability to log any element which exists within the DOM. In this case we log the body element:

[Link]([Link]);

This will log the following to the console:

Placeholders

You can use [Link]() in combination with placeholders:

var greet = "Hello", who = "World";


[Link]("%s, %s!", greet, who);

This will log the following to the console:

End Note

For more information on the capabilities of the console, see the Console topic.

Section 1.2: Using the DOM API


Logging Objects
DOM stands for Document Object Model. It is an object-oriented representation of structured documents like XML
Below we see the result of logging an object. This is often useful for logging JSON responses from API calls. and HTML.

Setting the textContent property of an Element is one way to output text on a web page.
[Link]({
'Email': '',
For example, consider the following HTML tag:
'Groups': {},
'Id': 33,
'IsHiddenInUI': false, <p id="paragraph"></p>
'IsSiteAdmin': false,
'LoginName': 'i:0#.w|virtualdomain\\user2', To change its textContent property, we can run the following JavaScript:
'PrincipalType': 1,

[Link] – JavaScript® Notes for Professionals 3 [Link] – JavaScript® Notes for Professionals 4
[Link]("paragraph").textContent = "Hello, World"; In Chrome, that would produce a pop-up like this:

This will select the element that with the id paragraph and set its text content to "Hello, World":

<p id="paragraph">Hello, World</p>

(See also this demo)

You can also use JavaScript to create a new HTML element programmatically. For example, consider an HTML
document with the following body:

<body>
<h1>Adding an element</h1>
</body>
Notes
In our JavaScript, we create a new <p> tag with a textContent property of and add it at the end of the html body:
The alert method is technically a property of window object, but since all window properties are
var element = [Link]('p');
automatically global variables, we can use alert as a global variable instead of as a property of window -
[Link] = "Hello, World";
[Link](element); //add the newly created element to the DOM meaning you can directly use alert() instead of [Link]().

That will change your HTML body to the following: Unlike using [Link], alert acts as a modal prompt meaning that the code calling alert will pause until the
prompt is answered. Traditionally this means that no other JavaScript code will execute until the alert is dismissed:
<body>
<h1>Adding an element</h1>
alert('Pause!');
<p>Hello, World</p>
[Link]('Alert was dismissed');
</body>

Note that in order to manipulate elements in the DOM using JavaScript, the JavaScript code must be run after the However the specification actually allows other event-triggered code to continue to execute even though a modal
relevant element has been created in the document. This can be achieved by putting the JavaScript <script> tags dialog is still being shown. In such implementations, it is possible for other code to run while the modal dialog is
after all of your other <body> content. Alternatively, you can also use an event listener to listen to eg. window's being shown.
onload event, adding your code to that event listener will delay running your code until after the whole content on
More information about usage of the alert method can be found in the modals prompts topic.
your page has been loaded.
The use of alerts is usually discouraged in favour of other methods that do not block users from interacting with the
A third way to make sure all your DOM has been loaded, is to wrap the DOM manipulation code with a timeout
page - in order to create a better user experience. Nevertheless, it can be useful for debugging.
function of 0 ms. This way, this JavaScript code is re-queued at the end of the execution queue, which gives the
browser a chance to finish doing some non-JavaScript things that have been waiting to finish before attending to Starting with Chrome 46.0, [Link]() is blocked inside an <iframe> unless its sandbox attribute has the value
this new piece of JavaScript. allow-modal.

Section 1.3: Using [Link]() Section 1.4: Using [Link]()


The alert method displays a visual alert box on screen. The alert method parameter is displayed to the user in An easy way to get an input from a user is by using the prompt() method.
plain text:
Syntax
[Link](message); prompt(text, [default]);

Because window is the global object, you can call also use the following shorthand: text: The text displayed in the prompt box.
default: A default value for the input field (optional).
alert(message);
Examples
So what does [Link]() do? Well, let's take the following example: var age = prompt("How old are you?");
[Link](age); // Prints the value inserted by the user
alert('hello, world');

[Link] – JavaScript® Notes for Professionals 5 [Link] – JavaScript® Notes for Professionals 6
var deleteConfirm = [Link]("Are you sure you want to delete this?");

Notes

The argument is optional and not required by the specification.


Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface
until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box
(or modal window). And regardless, there are very good reasons to avoid using dialog boxes for
confirmation.
Starting with Chrome 46.0 this method is blocked inside an <iframe> unless its sandbox attribute has the
value allow-modal.
If the user clicks the OK button, the input value is returned. Otherwise, the method returns null. It is commonly accepted to call the confirm method with the window notation removed as the window object
is always implicit. However, it is recommended to explicitly define the window object as expected behavior
The return value of prompt is always a string, unless the user clicks Cancel , in which that case it returns null. may change due to implementation at a lower scope level with similarly named methods.
Safari is an exception in that when the user clicks Cancel, the function returns an empty string. From there, you can
convert the return value to another type, such as an integer. Section 1.6: Using the DOM API (with graphical text: Canvas,
Notes
SVG, or image file)
While the prompt box is displayed, the user is prevented from accessing other parts of the page, since dialog Using canvas elements
boxes are modal windows.
HTML provides the canvas element for building raster-based images.
Starting with Chrome 46.0 this method is blocked inside an <iframe> unless its sandbox attribute has the
value allow-modal. First build a canvas for holding image pixel information.

Section 1.5: Using [Link]firm() var canvas = [Link]('canvas');


[Link] = 500;
The [Link]() method displays a modal dialog with an optional message and two buttons, OK and Cancel. [Link] = 250;

Now, let's take the following example: Then select a context for the canvas, in this case two-dimensional:

result = [Link](message); var ctx = [Link]('2d');

Here, message is the optional string to be displayed in the dialog and result is a boolean value indicating whether Then set properties related to the text:
OK or Cancel was selected (true means OK).
[Link] = '30px Cursive';
[Link]() is typically used to ask for user confirmation before doing a dangerous operation like deleting [Link]("Hello world!", 50, 50);
something in a Control Panel:
Then insert the canvas element into the page to take effect:
if([Link]("Are you sure you want to delete this?")) {
deleteItem(itemId); [Link](canvas);
}
Using SVG
The output of that code would look like this in the browser:
SVG is for building scalable vector-based graphics and can be used within HTML.

First create an SVG element container with dimensions:

var svg = [Link]('[Link] 'svg');


[Link] = 500;
[Link] = 50;

Then build a text element with the desired positioning and font characteristics:
If you need it for later use, you can simply store the result of the user's interaction in a variable:
var text = [Link]('[Link] 'text');
[Link]('x', '0');

[Link] – JavaScript® Notes for Professionals 7 [Link] – JavaScript® Notes for Professionals 8
[Link]('y', '50');
[Link] = 'Times New Roman';
[Link] = '50';
Chapter 2: JavaScript Variables
variable_name {Required} The name of the variable: used when calling it.
Then add the actual text to display to the textelement: = [Optional] Assignment (defining the variable)
value {Required when using Assignment} The value of a variable [default: undefined]
[Link] = 'Hello world!';

Variables are what make up most of JavaScript. These variables make up things from numbers to objects, which are
Finally add the text element to our svg container and add the svg container element to the HTML document:
all over JavaScript to make one's life much easier.

[Link](text);
[Link](svg); Section 2.1: Defining a Variable
Image file var myVariable = "This is a variable!";

If you already have an image file containing the desired text and have it placed on a server, you can add the URL of This is an example of defining variables. This variable is called a "string" because it has ASCII characters (A-Z, 0-9,
the image and then add the image to the document as follows: !@#$, etc.)

var img = new Image(); Section 2.2: Using a Variable


[Link] = '[Link]
[Link](img);
var number1 = 5;
number1 = 3;

Here, we defined a number called "number1" which was equal to 5. However, on the second line, we changed the
value to 3. To show the value of a variable, we log it to the console or use [Link]():

[Link](number1); // 3
[Link](number1); // 3

To add, subtract, multiply, divide, etc., we do like so:

number1 = number1 + 5; // 3 + 5 = 8
number1 = number1 - 6; // 8 - 6 = 2
var number2 = number1 * 10; // 2 (times) 10 = 20
var number3 = number2 / number1; // 20 (divided by) 2 = 10;

We can also add strings which will concatenate them, or put them together. For example:

var myString = "I am a " + "string!"; // "I am a string!"

Section 2.3: Types of Variables


var myInteger = 12; // 32-bit number (from -2,147,483,648 to 2,147,483,647)
var myLong = 9310141419482; // 64-bit number (from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807)
var myFloat = 5.5; // 32-bit floating-point number (decimal)
var myDouble = 9310141419482.22; // 64-bit floating-point number

var myBoolean = true; // 1-bit true/false (0 or 1)


var myBoolean2 = false;

var myNotANumber = NaN;


var NaN_Example = 0/0; // NaN: Division by Zero is not possible

var notDefined; // undefined: we didn't define it to anything yet


[Link](aRandomVariable); // undefined

[Link] – JavaScript® Notes for Professionals 9 [Link] – JavaScript® Notes for Professionals 10
var myNull = null; // null
// etc... Chapter 3: Built-in Constants
Section 2.4: Arrays and Objects Section 3.1: null
var myArray = []; // empty array null is used for representing the intentional absence of an object value and is a primitive value. Unlike undefined,
it is not a property of the global object.
An array is a set of variables. For example:
It is equal to undefined but not identical to it.
var favoriteFruits = ["apple", "orange", "strawberry"];
var carsInParkingLot = ["Toyota", "Ferrari", "Lexus"]; null == undefined; // true
var employees = ["Billy", "Bob", "Joe"]; null === undefined; // false
var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31];
var randomVariables = [2, "any type works", undefined, null, true, 2.51]; CAREFUL: The typeof null is 'object'.

myArray = ["zero", "one", "two"];


typeof null; // 'object';
[Link](myArray[0]); // 0 is the first element of an array
// in this case, the value would be "zero"
myArray = ["John Doe", "Billy"]; To properly check if a value is null, compare it with the strict equality operator
elementNumber = 1;
var a = null;
[Link](myArray[elementNumber]); // Billy
a === null; // true
An object is a group of values; unlike arrays, we can do something better than them:

myObject = {};
Section 3.2: Testing for NaN using isNaN()
john = {firstname: "John", lastname: "Doe", fullname: "John Doe"}; [Link]()
billy = {
firstname: "Billy", The global function isNaN() can be used to check if a certain value or expression evaluates to NaN. This function (in
lastname: undefined,
short) first checks if the value is a number, if not tries to convert it (*), and then checks if the resulting value is NaN.
fullname: "Billy"
}; For this reason, this testing method may cause confusion.
[Link]([Link]); // John Doe
[Link]([Link]); // Billy (*) The "conversion" method is not that simple, see ECMA-262 18.2.3 for a detailed explanation of the algorithm.

Rather than making an array ["John Doe", "Billy"] and calling myArray[0], we can just call [Link] and These examples will help you better understand the isNaN() behavior:
[Link].
isNaN(NaN); // true
isNaN(1); // false: 1 is a number
isNaN(-2e-4); // false: -2e-4 is a number (-0.0002) in scientific notation
isNaN(Infinity); // false: Infinity is a number
isNaN(true); // false: converted to 1, which is a number
isNaN(false); // false: converted to 0, which is a number
isNaN(null); // false: converted to 0, which is a number
isNaN(""); // false: converted to 0, which is a number
isNaN(" "); // false: converted to 0, which is a number
isNaN("45.3"); // false: string representing a number, converted to 45.3
isNaN("1.2e3"); // false: string representing a number, converted to 1.2e3
isNaN("Infinity"); // false: string representing a number, converted to Infinity
isNaN(new Date); // false: Date object, converted to milliseconds since epoch
isNaN("10$"); // true : conversion fails, the dollar sign is not a digit
isNaN("hello"); // true : conversion fails, no digits at all
isNaN(undefined); // true : converted to NaN
isNaN(); // true : converted to NaN (implicitly undefined)
isNaN(function(){}); // true : conversion fails
isNaN({}); // true : conversion fails
isNaN([1, 2]); // true : converted to "1, 2", which can't be converted to a number

This last one is a bit tricky: checking if an Array is NaN. To do this, the Number() constructor first converts the array

[Link] – JavaScript® Notes for Professionals 11 [Link] – JavaScript® Notes for Professionals 12
to a string, then to a number; this is the reason why isNaN([]) and isNaN([34]) both return false, but isNaN([1, It is a property of the global object, and a reference to [Link]
2]) and isNaN([true]) both return true: because they get converted to "", "34", "1,2" and "true" respectively. In
general, an array is considered NaN by isNaN() unless it only holds one element whose string representation [Link]('NaN'); // true
NaN; // NaN
can be converted to a valid number.

Version ≥ 6 Perhaps confusingly, NaN is still considered a number.


[Link]()
typeof NaN; // 'number'
In ECMAScript 6, the [Link]() function has been implemented primarily to avoid the problem of
[Link]() of forcefully converting the parameter to a number. [Link](), indeed, doesn't try to
Don't check for NaN using the equality operator. See isNaN instead.
convert the value to a number before testing. This also means that only values of the type number, that are
also NaN, return true (which basically means only [Link](NaN)). NaN == NaN // false
NaN === NaN // false
From ECMA-262 [Link]:

Section 3.4: undefined and null


When the [Link] is called with one argument number, the following steps are taken:
At first glance it may appear that null and undefined are basically the same, however there are subtle but
1. If Type(number) is not Number, return false. important differences.
2. If number is NaN, return true.
3. Otherwise, return false. undefined is the absence of a value in the compiler, because where it should be a value, there hasn't been put one,
like the case of an unassigned variable.

Some examples: undefined is a global value that represents the absence of an assigned value.
typeof undefined === 'undefined'
// The one and only
null is an object that indicates that a variable has been explicitly assigned "no value".
[Link](NaN); // true
typeof null === 'object'
// Numbers
[Link](1); // false Setting a variable to undefined means the variable effectively does not exist. Some processes, such as JSON
[Link](-2e-4); // false serialization, may strip undefined properties from objects. In contrast, null properties indicate will be preserved so
[Link](Infinity); // false you can explicitly convey the concept of an "empty" property.

// Values not of type number


The following evaluate to undefined:
[Link](true); // false
[Link](false); // false
A variable when it is declared but not assigned a value (i.e. defined)
[Link](null); // false
[Link](""); // false let foo;
[Link](" "); // false [Link]('is undefined?', foo === undefined);
[Link]("45.3"); // false // is undefined? true
[Link]("1.2e3"); // false Accessing the value of a property that doesn't exist
[Link]("Infinity"); // false
[Link](new Date); // false let foo = { a: 'a' };
[Link]("10$"); // false [Link]('is undefined?', foo.b === undefined);
[Link]("hello"); // false // is undefined? true
[Link](undefined); // false The return value of a function that doesn't return a value
[Link](); // false
function foo() { return; }
[Link](function(){}); // false
[Link]('is undefined?', foo() === undefined);
[Link]({}); // false
// is undefined? true
[Link]([]); // false
[Link]([1]); // false The value of a function argument that is declared but has been omitted from the function call
[Link]([1, 2]); // false function foo(param) {
[Link]([true]); // false [Link]('is undefined?', param === undefined);
}

Section 3.3: NaN foo('a');


foo();
// is undefined? false
NaN stands for "Not a Number." When a mathematical function or operation in JavaScript cannot return a specific
// is undefined? true
number, it returns the value NaN instead.

[Link] – JavaScript® Notes for Professionals 13 [Link] – JavaScript® Notes for Professionals 14
undefined is also a property of the global window object. Number.MIN_VALUE; // 5e-324
Number.MIN_SAFE_INTEGER; // -9007199254740991
// Only in browsers
[Link]; // 0.0000000000000002220446049250313
[Link]([Link]); // undefined
[Link]('undefined'); // true
Number.POSITIVE_INFINITY; // Infinity
Version < 5
Number.NEGATIVE_INFINITY; // -Infinity

Before ECMAScript 5 you could actually change the value of the [Link] property to any other value [Link]; // NaN
potentially breaking everything.
In many cases the various operators in JavaScript will break with values outside the range of
(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
Section 3.5: Infinity and -Infinity
Note that [Link] represents the different between one and the smallest Number greater than one, and
1 / 0; // Infinity thus the smallest possible difference between two different Number values. One reason to use this is due to the
// Wait! WHAAAT?
nature of how numbers are stored by JavaScript see Check the equality of two numbers

Infinity is a property of the global object (therefore a global variable) that represents mathematical infinity. It is a
reference to Number.POSITIVE_INFINITY
Section 3.7: Operations that return NaN
Mathematical operations on values other than numbers return NaN.
It is greater than any other value, and you can get it by dividing by 0 or by evaluating the expression of a number
that's so big that overflows. This actually means there is no division by 0 errors in JavaScript, there is Infinity!
"b" * 3
"cde" - "e"
There is also -Infinity which is mathematical negative infinity, and it's lower than any other value.
[1, 2, 3] * 2

To get -Infinity you negate Infinity, or get a reference to it in Number.NEGATIVE_INFINITY.


An exception: Single-number arrays.
- (Infinity); // -Infinity
[2] * [3] // Returns 6

Now let's have some fun with examples:


Also, remember that the + operator concatenates strings.
Infinity > 123192310293; // true
-Infinity < -123192310293; // true "a" + "b" // Returns "ab"
1 / 0; // Infinity
[Link](123123123, 9123192391023); // Infinity Dividing zero by zero returns NaN.
Number.MAX_VALUE * 2; // Infinity
23 / Infinity; // 0 0 / 0 // NaN
-Infinity; // -Infinity
-Infinity === Number.NEGATIVE_INFINITY; // true
-0; // -0 , yes there is a negative 0 in the language Note: In mathematics generally (unlike in JavaScript programming), dividing by zero is not possible.
0 === -0; // true
1 / -0; // -Infinity
1 / 0 === 1 / -0; // false
Section 3.8: Math library functions that return NaN
Infinity + Infinity; // Infinity
Generally, Math functions that are given non-numeric arguments will return NaN.
var a = 0, b = -0;
[Link]("a")
a === b; // true
1 / a === 1 / b; // false The square root of a negative number returns NaN, because [Link] does not support imaginary or complex
numbers.
// Try your own!

[Link](-1)
Section 3.6: Number constants
The Number constructor has some built in constants that can be useful

Number.MAX_VALUE; // 1.7976931348623157e+308
Number.MAX_SAFE_INTEGER; // 9007199254740991

[Link] – JavaScript® Notes for Professionals 15 [Link] – JavaScript® Notes for Professionals 16
Chapter 4: Comments </script>

An HTML closing comment can also be used in JavaScript (independent of an opening comment) at the beginning of
Section 4.1: Using Comments a line (optionally preceded by whitespace) in which case it too causes the rest of the line to be ignored:

To add annotations, hints, or exclude some code from being executed JavaScript provides two ways of commenting --> Unreachable JS code
code lines
These facts have also been exploited to allow a page to call itself first as HTML and secondly as JavaScript. For
Single line Comment // example:

Everything after the // until the end of the line is excluded from execution. <!--
[Link]('reached JS "file"');
function elementAt( event ) { /*
// Gets the element from Event coordinates -->
return [Link]([Link], [Link]); <!DOCTYPE html>
} <script>
// TODO: write more cool stuff! var w1 = new Worker('#1');
[Link] = function (e) {
Multi-line Comment /**/
[Link]([Link]); // 'reached JS "file"
};
Everything between the opening /* and the closing */ is excluded from execution, even if the opening and closing
</script>
are on different lines. <!--
*/
/* -->
Gets the element from Event coordinates.
Use like: When run a HTML, all the multiline text between the <!-- and --> comments are ignored, so the JavaScript
var clickedEl = [Link]("click", elementAt, false);
contained therein is ignored when run as HTML.
*/
function elementAt( event ) {
return [Link]([Link], [Link]); As JavaScript, however, while the lines beginning with <!-- and --> are ignored, their effect is not to escape over
} multiple lines, so the lines following them (e.g., [Link](...) will not be ignored when run as JavaScript,
/* TODO: write more useful comments! */ at least until they reach a JavaScript comment, marked by /* and */. Such JavaScript comments are used in the
above example to ignore the remaining HTML text (until the --> which is also ignored as JavaScript).
Section 4.2: Using HTML comments in JavaScript (Bad
practice)
HTML comments (optionally preceded by whitespace) will cause code (on the same line) to be ignored by the
browser also, though this is considered bad practice.

One-line comments with the HTML comment opening sequence (<!--):

Note: the JavaScript interpreter ignores the closing characters of HTML comments (-->) here.

<!-- A single-line comment.


<!-- --> Identical to using `//` since
<!-- --> the closing `-->` is ignored.

This technique can be observed in legacy code to hide JavaScript from browsers that didn't support it:

<script type="text/javascript" language="JavaScript">


<!--
/* Arbitrary JavaScript code.
Old browsers would treat
it as HTML code. */
// -->

[Link] – JavaScript® Notes for Professionals 17 [Link] – JavaScript® Notes for Professionals 18
Chapter 5: Console Opening the “Console” panel in Firefox’s Developer Tools:

Windows / Linux: any of the following options.


The information displayed by a debugging/web console is made available through the multiple methods of the
console Javascript object that can be consulted through [Link](console). Besides the [Link] Ctrl + Shift + K
property, the methods displayed are generally the following (taken from Chromium's output): Ctrl + Shift + I , then click on the “Web Console” tab or press ESC to toggle the console
on and off
assert
F12 , then click on the “Web Console” tab or press ESC to toggle the console on and off
clear
count Mac OS: Cmd + Opt + K
debug
dir
dirxml Edge and Internet Explorer
error
group Opening the “Console” panel in the F12 Developer Tools:
groupCollapsed
F12 , then click on the “Console” tab
groupEnd
info
log Safari
markTimeline
profile Opening the “Console” panel in Safari’s Web Inspector you must first enable the develop menu in Safari's
profileEnd Preferences
table
time
timeEnd
timeStamp
timeline
timelineEnd
trace
warn

Opening the Console

In most current browsers, the JavaScript Console has been integrated as a tab within Developer Tools. The shortcut
keys listed below will open Developer Tools, it might be necessary to switch to the right tab after that.

Chrome

Opening the “Console” panel of Chrome’s DevTools:

Windows / Linux: any of the following options.

Ctrl + Shift + J
Ctrl + Shift + I , then click on the “Web Console” tab or press ESC to toggle the console
on and off
F12 , then click on the “Console” tab or press ESC to toggle the console on and off

Mac OS: Cmd + Opt + J

Firefox

[Link] – JavaScript® Notes for Professionals 19 [Link] – JavaScript® Notes for Professionals 20
of your references and prevent exceptions.

if (![Link])
{
console = {log: function() {}};
}

Note this second example will stop all console logs even if the developer window has been opened.

Using this second example will preclude use of other functions such as [Link](obj) unless that is specifically
added.

A browser's debugging console or web console is generally used by developers to identify errors, understand flow
of execution, log data and for many other purpose at runtime. This information is accessed through the console
object.

Section 5.1: Measuring time - [Link]()


[Link]() can be used to measure how long a task in your code takes to run.

Calling [Link]([label]) starts a new timer. When [Link]([label]) is called, the elapsed time, in
milliseconds, since the original .time() call is calculated and logged. Because of this behavior, you can call
.timeEnd() multiple times with the same label to log the elapsed time since the original .time() call was made.

Example 1:

[Link]('response in');

alert('Click to continue');
[Link]('response in');

alert('One more time');


[Link]('response in');
Then you can either pick "Develop->Show Error Console" from the menus or press ⌘ + Option + C
will output:

Opera response in: 774.967ms


response in: 1402.199ms
Opening the “Console” in opera:
Example 2:
Ctrl + Shift + I ,then click on the “Console” tab
var elms = [Link]('*'); //select all elements on the page

Compatibility [Link]('Loop time');

When using or emulating Internet Explorer 8 or earlier versions (e.g. through Compatibility View / Enterprise Mode) for (var i = 0; i < 5000; i++) {
the console will only be defined when the Developer Tools are active, so [Link]() statements can cause an for (var j = 0, length = [Link]; j < length; j++) {
exception and prevent code from executing. To mitigate this, you can check to see if the console is available before // nothing to do ...
}
you log:
}

if (typeof [Link] !== 'undefined') [Link]('Loop time');


{
[Link]("Hello World");
will output:
}

Loop time: 40.716ms


Or at the start of your script you can identify if the console is available and if not, define a null function to catch all

[Link] – JavaScript® Notes for Professionals 21 [Link] – JavaScript® Notes for Professionals 22
Section 5.2: Formatting console output Using groups to indent output

Many of the console's print methods can also handle C-like string formatting, using % tokens: Output can be indented and enclosed in a collapsible group in the debugging console with the following methods:

[Link](): creates a collapsed group of entries that can be expanded through the
[Link]('%s has %d points', 'Sam', 100);
disclosure button in order to reveal all the entries performed after this method is invoked;
Displays Sam has 100 points. [Link](): creates an expanded group of entries that can be collapsed in order to hide the entries
after this method is invoked.
The full list of format specifiers in JavaScript is:
The indentation can be removed for posterior entries by using the following method:
Specifier Output
%s Formats the value as a string [Link](): exits the current group, allowing newer entries to be printed in the parent group after
%i or %d Formats the value as an integer this method is invoked.

%f Formats the value as a floating point value


Groups can be cascaded to allow multiple indented output or collapsible layers within each other:
%o Formats the value as an expandable DOM element
%O Formats the value as an expandable JavaScript object
%c Applies CSS style rules to the output string as specified by the second parameter

Advanced styling

When the CSS format specifier (%c) is placed at the left side of the string, the print method will accept a second
parameter with CSS rules which allow fine-grained control over the formatting of that string:

[Link]('%cHello world!', 'color: blue; font-size: xx-large');

Displays:

It is possible to use multiple %c format specifiers:

= Collapsed group expanded =>


any substring to the right of a %c has a corresponding parameter in the print method;
this parameter may be an empty string, if there is no need to apply CSS rules to that same substring;
if two %c format specifiers are found, the 1st (encased in %c) and 2nd substring will have their rules defined in Section 5.3: Printing to a browser's debugging console
the 2nd and 3rd parameter of the print method respectively.
A browser's debugging console can be used in order to print simple messages. This debugging or web console can
if three %c format specifiers are found, then the 1st, 2nd and 3rd substrings will have their rules defined in
be directly opened in the browser ( F12 key in most browsers – see Remarks below for further information) and
the 2nd , 3rd and 4th parameter respectively, and so on...
the log method of the console JavaScript object can be invoked by typing the following:
[Link]("%cHello %cWorld%c!!", // string to be printed
"color: blue;", // applies color formatting to the 1st substring [Link]('My message');
"font-size: xx-large;", // applies font formatting to the 2nd substring
"/* no CSS rule*/" // does not apply any rule to the remaining substring Then, by pressing Enter , this will display My message in the debugging console.
);
[Link]() can be called with any number of arguments and variables available in the current scope. Multiple
Displays: arguments will be printed in one line with a small space between them.

var obj = { test: 1 };


[Link](['string'], 1, obj, window);

The log method will display the following in the debugging console:

[Link] – JavaScript® Notes for Professionals 23 [Link] – JavaScript® Notes for Professionals 24
['string'] 1 Object { test: 1 } Window { /* truncated */ } }
function first() {
[Link]();
Beside plain strings, [Link]() can handle other types, like arrays, objects, dates, functions, etc.: }
sec();
[Link]([0, 3, 32, 'a string']);
[Link]({ key1: 'value', key2: 'another value'});
Displays:

Displays: first
sec
Array [0, 3, 32, 'a string'] (anonymous function)
Object { key1: 'value', key2: 'another value'}

Nested objects may be collapsed:

[Link]({ key1: 'val', key2: ['one', 'two'], key3: { a: 1, b: 2 } });

Displays:

Object { key1: 'val', key2: Array[2], key3: Object }


The above image shows all the functions, with the exception of timeStamp, in Chrome version 56.
Certain types such as Date objects and functions may be displayed differently:
These methods behave similarly to the log method and in different debugging consoles may render in different
[Link](new Date(0)); colors or formats.
[Link](function test(a, b) { return c; });
In certain debuggers, the individual objects information can be further expanded by clicking the printed text or a
Displays: small triangle (►) which refers to the respective object properties. These collapsing object properties can be open or
closed on log. See the [Link] for additional information on this
Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)
function test(a, b) { return c; }
Section 5.4: Including a stack trace when logging -
Other print methods
[Link]()
function foo() {
In addition to the log method, modern browsers also support similar methods:
[Link]('My log statement');
}
[Link] – small informative icon (ⓘ) appears on the left side of the printed string(s) or object(s).
foo();
[Link] – small warning icon (!) appears on the left side. In some browsers, the background of the log
is yellow.
Will display this in the console:
[Link] – small times icon (⊗) appears on the left side. In some browsers, the background of the log is
red. My log statement VM696:1
foo @ VM696:1
[Link] – outputs the current time and a specified string, but is non-standard: (anonymous function) @ (program):1

[Link]('msg'); Note: Where available it's also useful to know that the same stack trace is accessible as a property of the Error
object. This can be useful for post-processing and gathering automated feedback.
Displays:
var e = new Error('foo');
[Link]([Link]);
00:00:00.001 msg

[Link] – outputs the current stack trace or displays the same output as the log method if invoked in Section 5.5: Tabulating values - [Link]()
the global scope.
In most environments, [Link]() can be used to display objects and arrays in a tabular format.
function sec() {
first();
For example:

[Link] – JavaScript® Notes for Professionals 25 [Link] – JavaScript® Notes for Professionals 26
[Link](['Hello', 'world']);

displays like:

(index) value
0 "Hello"
1 "world"
[Link]({foo: 'bar', bar: 'baz'});

displays like:

(index) value
"foo" "bar"
"bar" "baz"
var personArr = [
{
"personId": 123,
"name": "Jhon",
"city": "Melbourne",
"phoneNo": "1234567890"
},
{
"personId": 124,
"name": "Amelia", Section 5.6: Counting - [Link]()
"city": "Sydney",
"phoneNo": "1234567890"
[Link]([obj]) places a counter on the object's value provided as argument. Each time this method is
},
{
invoked, the counter is increased (with the exception of the empty string ''). A label together with a number is
"personId": 125, displayed in the debugging console according to the following format:
"name": "Emily",
"city": "Perth", [label]: X
"phoneNo": "1234567890"
},
label represents the value of the object passed as argument and X represents the counter's value.
{
"personId": 126,
"name": "Abraham",
An object's value is always considered, even if variables are provided as arguments:
"city": "Perth",
"phoneNo": "1234567890" var o1 = 1, o2 = '2', o3 = "";
} [Link](o1);
]; [Link](o2);
[Link](personArr, ['name', 'personId']); [Link](o3);

[Link](1);
displays like:
[Link]('2');
[Link]('');

Displays:

1: 1
2: 1
: 1
1: 2
2: 2
: 1

Strings with numbers are converted to Number objects:

[Link](42.3);

[Link] – JavaScript® Notes for Professionals 27 [Link] – JavaScript® Notes for Professionals 28
[Link](Number('42.3')); [object Object]: 2
[Link]('42.3'); [object Object]: 3
[object Object]: 4
[object Object]: 5
Displays:
null: 1

42.3: 1 Empty string or absence of argument


42.3: 2
42.3: 3 If no argument is provided while sequentially inputting the count method in the debugging console, an empty
string is assumed as parameter, i.e.:
Functions point always to the global Function object:
> [Link]();
[Link]([Link]); : 1
[Link](function(){}); > [Link]('');
[Link](Object); : 2
var fn1 = function myfn(){}; > [Link]("");
[Link](fn1); : 3
[Link](Number);

Displays:
Section 5.7: Clearing the console - [Link]()
You can clear the console window using the [Link]() method. This removes all previously printed
[object Function]: 1
messages in the console and may print a message like "Console was cleared" in some environments.
[object Function]: 2
[object Function]: 3
[object Function]: 4 Section 5.8: Displaying objects and XML interactively -
[object Function]: 5 [Link](), [Link]()
Certain objects get specific counters associated to the type of object they refer to: [Link](object) displays an interactive list of the properties of the specified JavaScript object. The output is
presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.
[Link](undefined);
[Link]([Link]); var myObject = {
var obj; "foo":{
[Link](obj); "bar":"data"
[Link](Number(undefined)); }
[Link](NaN); };
[Link](NaN+3);
[Link](1/0); [Link](myObject);
[Link](String(1/0));
[Link](window);
[Link](document); displays:
[Link](console);
[Link](console.__proto__);
[Link]([Link]);
[Link](console.__proto__.[Link]);
[Link]([Link](console));
[Link](null);

Displays:

undefined: 1
undefined: 2
undefined: 3
NaN: 1
NaN: 2
NaN: 3
Infinity: 1
Infinity: 2
[object Window]: 1 [Link](object) prints an XML representation of the descendant elements of object if possible, or the
[object HTMLDocument]: 1 JavaScript representation if not. Calling [Link]() on HTML and XML elements is equivalent to calling
[object Object]: 1 [Link]().

[Link] – JavaScript® Notes for Professionals 29 [Link] – JavaScript® Notes for Professionals 30
Example 1:

[Link](document)

displays:

Section 5.9: Debugging with assertions - [Link]()


Example 2:
Writes an error message to the console if the assertion is false. Otherwise, if the assertion is true, this does
[Link](document) nothing.

displays: [Link]('one' === 1);

Multiple arguments can be provided after the assertion–these can be strings or other objects–that will only be
printed if the assertion is false:

Example 3:

var myObject = {
"foo":{
"bar":"data"
} [Link] does not throw an AssertionError (except in [Link]), meaning that this method is incompatible
};
with most testing frameworks and that code execution will not break on a failed assertion.
[Link](myObject);

displays:

[Link] – JavaScript® Notes for Professionals 31 [Link] – JavaScript® Notes for Professionals 32
Chapter 6: Datatypes in JavaScript Section 6.2: Finding an object's class
To find whether an object was constructed by a certain constructor or one inheriting from it, you can use the
Section 6.1: typeof instanceof command:

typeof is the 'official' function that one uses to get the type in JavaScript, however in certain cases it might yield //We want this function to take the sum of the numbers passed to it
some unexpected results ... //It can be called as sum(1, 2, 3) or sum([1, 2, 3]) and should give 6
function sum(...arguments) {
1. Strings if ([Link] === 1) {
const [firstArg] = arguments
typeof "String" or if (firstArg instanceof Array) { //firstArg is something like [1, 2, 3]
return sum(...firstArg) //calls sum(1, 2, 3)
typeof Date(2011,01,01)
}
}
return [Link]((a, b) => a + b)
"string"
}

[Link](sum(1, 2, 3)) //6


2. Numbers
[Link](sum([1, 2, 3])) //6
[Link](sum(4)) //4
typeof 42

Note that primitive values are not considered instances of any class:
"number"
[Link](2 instanceof Number) //false
[Link]('abc' instanceof String) //false
3. Bool [Link](true instanceof Boolean) //false
[Link](Symbol() instanceof Symbol) //false
typeof true (valid values true and false)
Every value in JavaScript besides null and undefined also has a constructor property storing the function that was
used to construct it. This even works with primitives.
"boolean"

//Whereas instanceof also catches instances of subclasses,


4. Object //using [Link] does not
[Link]([] instanceof Object, [] instanceof Array) //true true
[Link]([].constructor === Object, [].constructor === Array) //false true
typeof {} or
typeof [] or
function isNumber(value) {
typeof null or //[Link] and [Link] throw an error when accessed
typeof /aaa/ or if (value === null || value === undefined) return false
typeof Error() return [Link] === Number
}
[Link](isNumber(null), isNumber(undefined)) //false false
"object" [Link](isNumber('abc'), isNumber([]), isNumber(() => 1)) //false false false
[Link](isNumber(0), isNumber(Number('10.1')), isNumber(NaN)) //true true true

5. Function
Section 6.3: Getting object type by constructor name
typeof function(){}
When one with typeof operator one gets type object it falls into somewhat wast category...

"function" In practice you might need to narrow it down to what sort of 'object' it actually is and one way to do it is to use
object constructor name to get what flavour of object it actually is: [Link](yourObject)

6. Undefined 1. String

var var1; typeof var1 [Link]("String")

"undefined" "[object String]"

[Link] – JavaScript® Notes for Professionals 33 [Link] – JavaScript® Notes for Professionals 34
2. Number "[object Null]"

[Link](42)
10. Undefined

"[object Number]" [Link](undefined);

3. Bool "[object Undefined]"

[Link](true)
11. Error

"[object Boolean]" [Link](Error());

4. Object "[object Error]"

[Link](Object()) or
[Link]({})

"[object Object]"

5. Function

[Link](function(){})

"[object Function]"

6. Date

[Link](new Date(2015,10,21))

"[object Date]"

7. Regex

[Link](new RegExp()) or
[Link](/foo/);

"[object RegExp]"

8. Array

[Link]([]);

"[object Array]"

9. Null

[Link](null);

[Link] – JavaScript® Notes for Professionals 35 [Link] – JavaScript® Notes for Professionals 36
Chapter 7: Strings
Version ≥ 6

Strings can be created using template literals (backticks) `hello`.

Section 7.1: Basic Info and String Concatenation var greeting = `Hello`;

Strings in JavaScript can be enclosed in Single quotes 'hello', Double quotes "Hello" and (from ES2015, ES6) in
With template literals, you can do string interpolation using ${variable} inside template literals:
Template Literals (backticks) `hello`.

var place = `World`;


var hello = "Hello";
var greet = `Hello ${place}!`
var world = 'world';
var helloW = `Hello World`; // ES2015 / ES6
[Link](greet); // "Hello World!"

Strings can be created from other types using the String() function.
You can use [Link] to get backslashes to be in the string without modification.

var intString = String(32); // "32"


`a\\b` // = a\b
var booleanString = String(true); // "true"
[Link]`a\\b` // = a\\b
var nullString = String(null); // "null"

Or, toString() can be used to convert Numbers, Booleans or Objects to Strings. Section 7.2: Reverse String
var intString = (5232).toString(); // "5232" The most "popular" way of reversing a string in JavaScript is the following code fragment, which is quite common:
var booleanString = (false).toString(); // "false"
var objString = ({}).toString(); // "[object Object]" function reverseString(str) {
return [Link]('').reverse().join('');
Strings also can be created by using [Link] method. }

reverseString('string'); // "gnirts"
[Link](104,101,108,108,111) //"hello"

However, this will work only so long as the string being reversed does not contain surrogate pairs. Astral symbols,
Creating a String object using new keyword is allowed, but is not recommended as it behaves like Objects unlike
i.e. characters outside of the basic multilingual plane, may be represented by two code units, and will lead this
primitive strings.
naive technique to produce wrong results. Moreover, characters with combining marks (e.g. diaeresis) will appear
var objectString = new String("Yes, I am a String object");
on the logical "next" character instead of the original one it was combined with.
typeof objectString;//"object"
typeof [Link]();//"string" '?????.'.split('').reverse().join(''); //fails

Concatenating Strings
While the method will work fine for most languages, a truly accurate, encoding respecting algorithm for string
String concatenation can be done with the + concatenation operator, or with the built-in concat() method on the reversal is slightly more involved. One such implementation is a tiny library called Esrever, which uses regular
String object prototype. expressions for matching combining marks and surrogate pairs in order to perform the reversing perfectly.

var foo = "Foo"; Explanation


var bar = "Bar"; Section Explanation Result
[Link](foo + bar); // => "FooBar" str The input string "string"
[Link](foo + " " + bar); // => "Foo Bar"
Splits string str into an array. The
[Link](
deliminator )
parameter "" means to split between each ["s","t","r","i","n","g"]
[Link](bar) // => "FooBar"
character.
"a".concat("b", " ", "d") // => "ab d"
Returns the array from the split string with
[Link]() ["g","n","i","r","t","s"]
its elements in reverse order.
Strings can be concatenated with non-string variables but will type-convert the non-string variables into strings.
Joins the elements in the array together into
[Link]( deliminator a string. The "" parameter means an empty
var string = "string"; "gnirts"
) deliminator (i.e., the elements of the array
var number = 32; are put right next to each other).
var boolean = true;

[Link](string + number + boolean); // "string32true" Using spread operator

String Templates Version ≥ 6

[Link] – JavaScript® Notes for Professionals 37 [Link] – JavaScript® Notes for Professionals 38
function reverseString(str) { });
return [...String(str)].reverse().join(''); [Link](arr); // [ "apples", "bananas", "cranberries" ]
}

[Link](reverseString('stackoverflow')); // "wolfrevokcats"
Section 7.4: Access character at index in string
[Link](reverseString(1337)); // "7331"
[Link](reverseString([1, 2, 3])); // "3,2,1" Use charAt() to get a character at the specified index in the string.

var string = "Hello, World!";


Custom reverse() function
[Link]( [Link](4) ); // "o"

function reverse(string) {
var strRev = ""; Alternatively, because strings can be treated like arrays, use the index via bracket notation.
for (var i = [Link] - 1; i >= 0; i--) {
strRev += string[i]; var string = "Hello, World!";
} [Link]( string[4] ); // "o"
return strRev;
} To get the character code of the character at a specified index, use charCodeAt().

reverse("zebra"); // "arbez"
var string = "Hello, World!";
[Link]( [Link](4) ); // 111
Section 7.3: Comparing Strings Lexicographically
Note that these methods are all getter methods (return a value). Strings in JavaScript are immutable. In other
To compare strings alphabetically, use localeCompare(). This returns a negative value if the reference string is words, none of them can be used to set a character at a position in the string.
lexicographically (alphabetically) before the compared string (the parameter), a positive value if it comes
afterwards, and a value of 0 if they are equal. Section 7.5: Escaping quotes
var a = "hello"; If your string is enclosed (i.e.) in single quotes you need to escape the inner literal quote with backslash \
var b = "world";

var text = 'L\'albero means tree in Italian';


[Link]([Link](b)); // -1
[Link]( text ); \\ "L'albero means tree in Italian"

The > and < operators can also be used to compare strings lexicographically, but they cannot return a value of zero
Same goes for double quotes:
(this can be tested with the == equality operator). As a result, a form of the localeCompare() function can be
written like so: var text = "I feel \"high\"";

function strcmp(a, b) {
Special attention must be given to escaping quotes if you're storing HTML representations within a String, since
if(a === b) {
return 0;
HTML strings make large use of quotations i.e. in attributes:
}
var content = "<p class=\"special\">Hello World!</p>"; // valid String
if (a > b) { var hello = '<p class="special">I\'d like to say "Hi"</p>'; // valid String
return 1;
} Quotes in HTML strings can also be represented using &apos; (or &#39;) as a single quote and &quot; ( or &#34;) as
double quotes.
return -1;
}
var hi = "<p class='special'>I'd like to say &quot;Hi&quot;</p>"; // valid String
[Link](strcmp("hello", "world")); // -1 var hello = '<p class="special">I&apos;d like to say "Hi"</p>'; // valid String
[Link](strcmp("hello", "hello")); // 0
[Link](strcmp("world", "hello")); // 1 Note: The use of &apos; and &quot; will not overwrite double quotes that browsers can automatically place on
attribute quotes. For example <p class=special> being made to <p class="special">, using &quot; can lead to
This is especially useful when using a sorting function that compares based on the sign of the return value (such as <p class=""special""> where \" will be <p class="special">.
sort).
Version ≥ 6

var arr = ["bananas", "cranberries", "apples"];


[Link](function(a, b) {
If a string has ' and " you may want to consider using template literals (also known as template strings in previous ES6
return [Link](b); editions), which do not require you to escape ' and ". These use backticks (`) instead of single or double quotes.

[Link] – JavaScript® Notes for Professionals 39 [Link] – JavaScript® Notes for Professionals 40
var x = `"Escaping " and ' can become very annoying`; Section 7.9: Strings are unicode
Section 7.6: Word Counter All JavaScript strings are unicode!

Say you have a <textarea> and you want to retrieve info about the number of: var s = "some ∆≈ƒ unicode ¡™£¢¢¢";
[Link](5); // 8710
Characters (total)
Characters (no spaces) There are no raw byte or binary strings in JavaScript. To effectively handle binary data, use Typed Arrays.
Words
Lines Section 7.10: Detecting a string
function wordCount( val ){ To detect whether a parameter is a primitive string, use typeof:
var wom = [Link](/\S+/g);
return { var aString = "my string";
charactersNoSpaces : [Link](/\s+/g, '').length, var anInt = 5;
characters : [Link], var anObj = {};
words : wom ? [Link] : 0, typeof aString === "string"; // true
lines : [Link](/\r*\n/).length typeof anInt === "string"; // false
}; typeof anObj === "string"; // false
}

If you ever have a String object, via new String("somestr"), then the above will not work. In this instance, we can
// Use like: use instanceof:
wordCount( someMultilineText ).words; // (Number of words)
var aStringObj = new String("my string");
jsFiddle example aStringObj instanceof String; // true

Section 7.7: Trim whitespace To cover both instances, we can write a simple helper function:

To trim whitespace from the edges of a string, use [Link]: var isString = function(value) {
return typeof value === "string" || value instanceof String;
};
" some whitespaced string ".trim(); // "some whitespaced string"
var aString = "Primitive String";
Many JavaScript engines, but not Internet Explorer, have implemented non-standard trimLeft and trimRight var aStringObj = new String("String Object");
methods. There is a proposal, currently at Stage 1 of the process, for standardised trimStart and trimEnd isString(aString); // true
isString(aStringObj); // true
methods, aliased to trimLeft and trimRight for compatibility.
isString({}); // false
isString(5); // false
// Stage 1 proposal
" this is me ".trimStart(); // "this is me "
" this is me ".trimEnd(); // " this is me" Or we can make use of toString function of Object. This can be useful if we have to check for other types as well
say in a switch statement, as this method supports other datatypes as well just like typeof.
// Non-standard methods, but currently implemented by most engines
" this is me ".trimLeft(); // "this is me " var pString = "Primitive String";
" this is me ".trimRight(); // " this is me" var oString = new String("Object Form of String");
[Link](pString);//"[object String]"

Section 7.8: Splitting a string into an array [Link](oString);//"[object String]"

A more robust solution is to not detect a string at all, rather only check for what functionality is required. For
Use .split to go from strings to an array of the split substrings:
example:
var s = "one, two, three, four, five"
[Link](", "); // ["one", "two", "three", "four", "five"] var aString = "Primitive String";
// Generic check for a substring method
if([Link]) {
Use the array method .join to go back to a string:
}
[Link](", ").join("--"); // "one--two--three--four--five" // Explicit check for the String substring prototype method

[Link] – JavaScript® Notes for Professionals 41 [Link] – JavaScript® Notes for Professionals 42
if([Link] === [Link]) { // base 16 String representation
[Link](0, ); var b16 = 'c';
}
// base 10 Number

Section 7.11: Substrings with slice var b10 = parseInt(b16, 16); // 12

Use .slice() to extract substrings given two indices: To convert an arbitrary number (i.e. non-integer) from its String representation into a Number, the operation must be
split into two parts; the integer part and the fraction part.
var s = "0123456789abcdefg";
Version ≥ 6
[Link](0, 5); // "01234"
[Link](5, 6); // "5" let b16 = '3.243f3e0370cdc';
// Split into integer and fraction parts
let [i16, f16] = [Link]('.');
Given one index, it will take from that index to the end of the string:
// Calculate base 10 integer part
[Link](10); // "abcdefg" let i10 = parseInt(i16, 16); // 3

Section 7.12: Character code // Calculate the base 10 fraction part


let f10 = parseInt(f16, 16) / [Link](16, [Link]); // 0.14158999999999988

The method charCodeAt retrieves the Unicode character code of a single character: // Put the base 10 parts together to find the Number
let b10 = i10 + f10; // 3.14159
var charCode = "µ".charCodeAt(); // The character code of the letter µ is 181
Note 1: Be careful as small errors may be in the result due to differences in what is possible to be represented in
To get the character code of a character in a string, the 0-based position of the character is passed as a parameter different bases. It may be desirable to perform some kind of rounding afterwards.
to charCodeAt: Note 2: Very long representations of numbers may also result in errors due to the accuracy and maximum values
of Numbers of the environment the conversions are happening in.
var charCode = "ABCDE".charCodeAt(3); // The character code of "D" is 68
Version ≥ 6
Section 7.14: String Find and Replace Functions
Some Unicode symbols don't fit in a single character, and instead require two UTF-16 surrogate pairs to encode.
To search for a string inside a string, there are several functions:
This is the case of character codes beyond 216 - 1 or 63553. These extended character codes or code point values
can be retrieved with codePointAt: indexOf( searchString ) and lastIndexOf( searchString )

// The Grinning Face Emoji has code point 128512 or 0x1F600 indexOf() will return the index of the first occurrence of searchString in the string. If searchString is not found,
var codePoint = "????".codePointAt(); then -1 is returned.

Section 7.13: String Representations of Numbers var string = "Hello, World!";


[Link]( [Link]("o") ); // 4
[Link]( [Link]("foo") ); // -1
JavaScript has native conversion from Number to its String representation for any base from 2 to 36.

The most common representation after decimal (base 10) is hexadecimal (base 16), but the contents of this section Similarly, lastIndexOf() will return the index of the last occurrence of searchstring or -1 if not found.
work for all bases in the range.
var string = "Hello, World!";
In order to convert a Number from decimal (base 10) to its hexadecimal (base 16) String representation the toString [Link]( [Link]("o") ); // 8
[Link]( [Link]("foo") ); // -1
method can be used with radix 16.

// base 10 Number includes( searchString, start )


var b10 = 12;
includes() will return a boolean that tells whether searchString exists in the string, starting from index start
// base 16 String representation (defaults to 0). This is better than indexOf() if you simply need to test for existence of a substring.
var b16 = [Link](16); // "c"
var string = "Hello, World!";
If the number represented is an integer, the inverse operation for this can be done with parseInt and the radix 16 [Link]( [Link]("Hello") ); // true
again [Link]( [Link]("foo") ); // false

[Link] – JavaScript® Notes for Professionals 43 [Link] – JavaScript® Notes for Professionals 44
replace( regexp|substring, replacement|replaceFunction )
Section 7.17: String to Lower Case
replace() will return a string that has all occurrences of substrings matching the RegExp regexp or string
[Link]()
substring with a string replacement or the returned value of replaceFunction.

[Link]('QWERTY'.toLowerCase()); // 'qwerty'
Note that this does not modify the string in place, but returns the string with replacements.

var string = "Hello, World!"; Section 7.18: Repeat a String


string = [Link]( "Hello", "Bye" );
[Link]( string ); // "Bye, World!" Version ≥ 6

string = [Link]( /W.{3}d/g, "Universe" ); This can be done using the .repeat() method:
[Link]( string ); // "Bye, Universe!"
"abc".repeat(3); // Returns "abcabcabc"
replaceFunction can be used for conditional replacements for regular expression objects (i.e., with use with "abc".repeat(0); // Returns ""
"abc".repeat(-1); // Throws a RangeError
regexp). The parameters are in the following order:
Version < 6

Parameter Meaning
In the general case, this should be done using a correct polyfill for the ES6 [Link]() method.
match the substring that matches the entire regular expressiong
Otherwise, the idiom new Array(n + 1).join(myString) can repeat n times the string myString:
g1, g2, g3, ... the matching groups in the regular expression
offset the offset of the match in the entire string var myString = "abc";
string the entire string var n = 3;

Note that all parameters are optional. new Array(n + 1).join(myString); // Returns "abcabcabc"

var string = "heLlo, woRlD!";


string = [Link]( /([a-zA-Z])([a-zA-Z]+)/g, function(match, g1, g2) {
return [Link]() + [Link]();
});
[Link]( string ); // "Hello, World!"

Section 7.15: Find the index of a substring inside a string


The .indexOf method returns the index of a substring inside another string (if exists, or -1 if otherwise)

'Hellow World'.indexOf('Wor'); // 7

.indexOf also accepts an additional numeric argument that indicates on what index should the function start
looking

"harr dee harr dee harr".indexOf("dee", 10); // 14

You should note that .indexOf is case sensitive

'Hellow World'.indexOf('WOR'); // -1

Section 7.16: String to Upper Case

[Link]():

[Link]('qwerty'.toUpperCase()); // 'QWERTY'

[Link] – JavaScript® Notes for Professionals 45 [Link] – JavaScript® Notes for Professionals 46
Chapter 8: Date to show the date and time in UTC (the Z in the formatted string denotes UTC).

// Creates a Date object with the current date and time from the
Parameter Details // user's browser
value The number of milliseconds since 1 January 1970 00:00:00.000 UTC (Unix epoch) var now = new Date();
[Link]() === 'Mon Apr 11 2016 16:10:41 GMT-0500 (Central Daylight Time)'
dateAsString A date formatted as a string (see examples for more information)
// true
The year value of the date. Note that month must also be provided, or the value will be interpreted // well, at the time of this writing, anyway
year as a number of milliseconds. Also note that values between 0 and 99 have special meaning. See the
examples. // Creates a Date object at the Unix Epoch (i.e., '1970-01-01T00:00:00.000Z')
The month, in the range 0-11. Note that using values outside the specified range for this and the var epoch = new Date(0);
month following parameters will not result in an error, but rather cause the resulting date to "roll over" to [Link]() === '1970-01-01T00:00:00.000Z' // true
the next value. See the examples.
// Creates a Date object with the date and time 2,012 milliseconds
day Optional: The date, in the range 1-31.
// after the Unix Epoch (i.e., '1970-01-01T00:00:02.012Z').
hour Optional: The hour, in the range 0-23. var ms = new Date(2012);
minute Optional: The minute, in the range 0-59. [Link]() === '1970-01-01T00:00:02.012Z' // true

second Optional: The second, in the range 0-59. // Creates a Date object with the first day of February of the year 2012
millisecond Optional: The millisecond, in the range 0-999. // in the local timezone.
var Date(2012, 1);
[Link]() === 'Wed Feb 01 2012 00:00:00 GMT-0600 (Central Standard Time)'
Section 8.1: Create a new Date object // true

To create a new Date object use the Date() constructor: // Creates a Date object with the first day of the year 2012 in the local
// timezone.
with no arguments // (Months are zero-based)
var zero = new Date(2012, 0);
[Link]() === 'Sun Jan 01 2012 00:00:00 GMT-0600 (Central Standard Time)'
Date() creates a Date instance containing the current time (up to milliseconds) and date. // true

// Creates a Date object with the first day of the year 2012, in UTC.
with one integer argument var utc = new Date([Link](2012, 0));
[Link]() === 'Sat Dec 31 2011 18:00:00 GMT-0600 (Central Standard Time)'
// true
Date(m) creates a Date instance containing the time and date corresponding to the Epoch time (1 January, [Link]() === '2012-01-01T00:00:00.000Z'
1970 UTC) plus m milliseconds. Example: new Date(749019369738) gives the date Sun, 26 Sep 1993 04:56:09 // true

GMT.
// Parses a string into a Date object (ISO 8601 format added in ECMAScript 5.1)
// Implementations should assumed UTC because of ISO 8601 format and Z designation
var iso = new Date('2012-01-01T00:00:00.000Z');
with a string argument [Link]() === '2012-01-01T00:00:00.000Z' // true

// Parses a string into a Date object (RFC in JavaScript 1.0)


Date(dateString) returns the Date object that results after parsing dateString with [Link]. var local = new Date('Sun, 01 Jan 2012 00:00:00 -0600');
[Link]() === 'Sun Jan 01 2012 00:00:00 GMT-0600 (Central Standard Time)'
// true
with two or more integer arguments
// Parses a string in no particular format, most of the time. Note that parsing
// logic in these cases is very implementation-dependent, and therefore can vary
Date(i1, i2, i3, i4, i5, i6) reads the arguments as year, month, day, hours, minutes, seconds, // across browsers and versions.
milliseconds and instantiates the corresponding Dateobject. Note that the month is 0-indexed in JavaScript, var anything = new Date('11/12/2012');
[Link]() === 'Mon Nov 12 2012 00:00:00 GMT-0600 (Central Standard Time)'
so 0 means January and 11 means December. Example: new Date(2017, 5, 1) gives June 1st, 2017.
// true, in Chrome 49 64-bit on Windows 10 in the en-US locale. Other versions in
// other locales may get a different result.

// Rolls values outside of a specified range to the next value.


Exploring dates var rollover = new Date(2012, 12, 32, 25, 62, 62, 1023);
[Link]() === 'Sat Feb 02 2013 02:03:03 GMT-0600 (Central Standard Time)'
// true; note that the month rolled over to Feb; first the month rolled over to
Note that these examples were generated on a browser in the Central Time Zone of the US, during Daylight Time,
// Jan based on the month 12 (11 being December), then again because of the day 32
as evidenced by the code. Where comparison with UTC was instructive, [Link]() was used
// (January having 31 days).

[Link] – JavaScript® Notes for Professionals 47 [Link] – JavaScript® Notes for Professionals 48
// Special dates for years in the range 0-99 Convert to GMT String
var special1 = new Date(12, 0);
var date1 = new Date();
[Link]() === 'Mon Jan 01 1912 00:00:00 GMT-0600 (Central Standard Time)`
[Link]();
// true

// If you actually wanted to set the year to the year 12 CE, you'd need to use the
// setFullYear() method: Returns: "Thu, 14 Apr 2016 23:49:08 GMT"
[Link](12);
[Link]() === 'Sun Jan 01 12 00:00:00 GMT-0600 (Central Standard Time)`
// true This function has been marked as deprecated so some browsers may not support it in the future. It is suggested to
use toUTCString() instead.

Section 8.2: Convert to a string format


Convert to Locale Date String
Convert to String
var date1 = new Date();
var date1 = new Date();
[Link]();
[Link]();

Returns: "4/14/2016"
Returns: "Fri Apr 15 2016 07:48:48 GMT-0400 (Eastern Daylight Time)"

This function returns a locale sensitive date string based upon the user's location by default.

Convert to Time String


[Link]([locales [, options]])
var date1 = new Date();
[Link]();
can be used to provide specific locales but is browser implementation specific. For example,

[Link](["zh", "en-US"]);
Returns: "07:48:48 GMT-0400 (Eastern Daylight Time)"

would attempt to print the string in the Chinese locale using United States English as a fallback. The options
parameter can be used to provide specific formatting. For example:
Convert to Date String
var date1 = new Date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
[Link](); [Link]([], options);

would result in
Returns: "Thu Apr 14 2016"

"Thursday, April 14, 2016".

Convert to UTC String


See the MDN for more details.
var date1 = new Date();
[Link]();
Section 8.3: Creating a Date from UTC
Returns: "Fri, 15 Apr 2016 11:48:48 GMT" By default, a Date object is created as local time. This is not always desirable, for example when communicating a
date between a server and a client that do not reside in the same timezone. In this scenario, one doesn't want to
worry about timezones at all until the date needs to be displayed in local time, if that is even required at all.

Convert to ISO String The problem


var date1 = new Date();
[Link](); In this problem we want to communicate a specific date (day, month, year) with someone in a different timezone.
The first implementation naively uses local times, which results in wrong results. The second implementation uses
UTC dates to avoid timezones where they are not needed.
Returns: "2016-04-14T23:49:08.596Z"
Naive approach with WRONG results

[Link] – JavaScript® Notes for Professionals 49 [Link] – JavaScript® Notes for Professionals 50
function formatDate(dayOfWeek, day, month, year) { [Link]("Foo was born on: " + formatDate([Link](), [Link](),
var daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; [Link](), [Link]()));
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return daysOfWeek[dayOfWeek] + " " + months[month] + " " + day + " " + year;
} Sample output:

//Foo lives in a country with timezone GMT + 1 Foo was born on: Sat Jan 1 2000
var birthday = new Date(2000,0,1);
[Link]("Foo was born on: " + formatDate([Link](), [Link](),
[Link](), [Link]()));
Creating a Date from UTC
sendToBar([Link]());
If one wants to create a Date object based on UTC or GMT, the [Link](...) method can be used. It uses the
same arguments as the longest Date constructor. This method will return a number representing the time that has
Sample output: passed since January 1, 1970, 00:00:00 UTC.

Foo was born on: Sat Jan 1 2000 [Link]([Link](2000,0,31,12));

//Meanwhile somewhere else... Sample output:

//Bar lives in a country with timezone GMT - 1 949320000000


var birthday = new Date(receiveFromFoo());
[Link]("Foo was born on: " + formatDate([Link](), [Link](),
[Link](), [Link]()));
var utcDate = new Date([Link](2000,0,31,12));
[Link](utcDate);

Sample output:
Sample output:
Foo was born on: Fri Dec 31 1999
Mon Jan 31 2000 13:00:00 GMT+0100 (West-Europa (standaardtijd))

And thus, Bar would always believe Foo was born on the last day of 1999.
Unsurprisingly, the difference between UTC time and local time is, in fact, the timezone offset converted to
Correct approach
milliseconds.
function formatDate(dayOfWeek, day, month, year) {
var daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var utcDate = new Date([Link](2000,0,31,12));
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var localDate = new Date(2000,0,31,12);
return daysOfWeek[dayOfWeek] + " " + months[month] + " " + day + " " + year;
}
[Link](localDate - utcDate === [Link]() * 60 * 1000);

//Foo lives in a country with timezone GMT + 1


var birthday = new Date([Link](2000,0,1));
[Link]("Foo was born on: " + formatDate([Link](), [Link](), Sample output: true
[Link](), [Link]()));

sendToBar([Link]()); Changing a Date object

All Date object modifiers, such as setDate(...) and setFullYear(...) have an equivalent takes an argument in
Sample output: UTC time rather than in local time.

Foo was born on: Sat Jan 1 2000 var date = new Date();
[Link](2000,0,31);
[Link](12,0,0,0);
[Link](date);
//Meanwhile somewhere else...

//Bar lives in a country with timezone GMT - 1


var birthday = new Date(receiveFromFoo()); Sample output:

[Link] – JavaScript® Notes for Professionals 51 [Link] – JavaScript® Notes for Professionals 52
Mon Jan 31 2000 13:00:00 GMT+0100 (West-Europa (standaardtijd)) zone
hour12 :possible values are true and false; the default is locale dependent
formatMatcher : possible values are "basic" and "best fit"; the default is "best fit"
The other UTC-specific modifiers are .setUTCMonth(), .setUTCDate() (for the day of the month), weekday : possible values are "narrow", "short" & "long"
.setUTCMinutes(), .setUTCSeconds() and .setUTCMilliseconds(). era : possible values are "narrow", "short" & "long"
year : possible values are "numeric" & "2-digit"
Avoiding ambiguity with getTime() and setTime()
month : possible values are "numeric", "2-digit", "narrow", "short" & "long"
Where the methods above are required to differentiate between ambiguity in dates, it is usually easier to day : possible values are "numeric" & "2-digit"
communicate a date as the amount of time that has passed since January 1, 1970, 00:00:00 UTC. This single number hour : possible values are "numeric" & "2-digit"
represents a single point in time, and can be converted to local time whenever necessary. minute : possible values are "numeric" & "2-digit"
second : possible values are "numeric" & "2-digit"
var date = new Date([Link](2000,0,31,12)); timeZoneName : possible values are "short" & "long"
var timestamp = [Link]();
//Alternatively
var timestamp2 = [Link](2000,0,31,12); How to use
[Link](timestamp === timestamp2);
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
Sample output: true year : 'numeric'
});

//And when constructing a date from it elsewhere...


Output if executed on January 24 ʰ, 2036 :
var otherDate = new Date(timestamp);

//Represented as a universal date '24 Jan 2036'


[Link]([Link]());
//Represented as a local date
Going custom
[Link](otherDate);

If [Link]() isn't flexible enough to fulfill whatever need you may have, you might
want to consider creating a custom Date object that looks like this:
Sample output:

var DateObject = (function() {


var monthNames = [
Mon, 31 Jan 2000 12:00:00 GMT
Mon Jan 31 2000 13:00:00 GMT+0100 (West-Europa (standaardtijd)) "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
/code>
"November", "December"
];
Section 8.4: Formatting a JavaScript date var date = function(str) {
[Link](str);
Formatting a JavaScript date in modern browsers };
[Link] = {
In modern browsers (*), [Link]() allows you to define the formatting of a Date in a set : function(str) {
var dateDef = str ? new Date(str) : new Date();
convenient manner.
[Link] = [Link]();
[Link] = ([Link] < 10) ? ("0" + [Link]) : "" + [Link];
It requires the following format : [Link] = [Link]() + 1;
[Link] = ([Link] < 10) ? ("0" + [Link]) : "" + [Link];
[Link]([locales [, options]]) [Link] = monthNames[[Link] - 1];
[Link] = [Link]();
The locales parameter should be a string with a BCP 47 language tag, or an array of such strings. },
get : function(properties, separator) {
var separator = separator ? separator : '-'
The options parameter should be an object with some or all of the following properties:
ret = [];
for(var i in properties) {
localeMatcher : possible values are "lookup" and "best fit"; the default is "best fit" [Link](this[properties[i]]);
timeZone : the only value implementations must recognize is "UTC"; the default is the runtime's default time }
return [Link](separator);

[Link] – JavaScript® Notes for Professionals 53 [Link] – JavaScript® Notes for Professionals 54
} Get the current month
};
var month = (new Date()).getMonth();
return date;
[Link](month);
})();
// Sample output: 0

If you included that code and executed new DateObject() on January 20 ʰ, 2019, it would produce an object with
Please note that 0 = January. This is because months range from 0 to 11, so it is often desirable to add +1 to the
the following properties:
index.

day: 20
Get the current day
dayPadded: "20"
month: 1 var day = (new Date()).getDate();
monthPadded: "01" [Link](day);
monthName: "January" // Sample output: 31
year: 2019 Get the current hour
var hours = (new Date()).getHours();
To get a formatted string, you could do something like this: [Link](hours);
// Sample output: 10
new DateObject().get(['dayPadded', 'monthPadded', 'year']);
Get the current minutes
var minutes = (new Date()).getMinutes();
That would produce the following output:
[Link](minutes);
// Sample output: 39
20-01-2016 Get the current seconds
var seconds = (new Date()).getSeconds();
[Link](second);
(*) According to the MDN, "modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari
// Sample output: 48
nightly build
Get the current milliseconds

Section 8.5: Get the number of milliseconds elapsed since 1 To get the milliseconds (ranging from 0 to 999) of an instance of a Date object, use its getMilliseconds method.
January 1970 00:00:00 UTC
var milliseconds = (new Date()).getMilliseconds();
The static method [Link] returns the number of milliseconds that have elapsed since 1 January 1970 00:00:00 [Link](milliseconds);
UTC. To get the number of milliseconds that have elapsed since that time using an instance of a Date object, use its // Output: milliseconds right now
getTime method. Convert the current time and date to a human-readable string
var now = new Date();
// get milliseconds using static method now of Date // convert date to a string in UTC timezone format:
[Link]([Link]()); [Link]([Link]());
// Output: Wed, 21 Jun 2017 09:13:01 GMT
// get milliseconds using method getTime of Date instance
[Link]((new Date()).getTime());
The static method [Link]() returns the number of milliseconds that have elapsed since 1 January 1970 00:00:00
UTC. To get the number of milliseconds that have elapsed since that time using an instance of a Date object, use its
Section 8.6: Get the current time and date getTime method.

Use new Date() to generate a new Date object containing the current date and time. // get milliseconds using static method now of Date
[Link]([Link]());
Note that Date() called without arguments is equivalent to new Date([Link]()).
// get milliseconds using method getTime of Date instance
Once you have a date object, you can apply any of the several available methods to extract its properties (e.g. [Link]((new Date()).getTime());
getFullYear() to get the 4-digits year).

Below are some common date methods. Section 8.7: Increment a Date Object
Get the current year To increment date objects in JavaScript, we can usually do this:

var year = (new Date()).getFullYear();


var checkoutDate = new Date(); // Thu Jul 21 2016 10:05:13 GMT-0400 (EDT)
[Link](year);
// Sample output: 2016
[Link]( [Link]() + 1 );

[Link] – JavaScript® Notes for Professionals 55 [Link] – JavaScript® Notes for Professionals 56
[Link](checkoutDate); // Fri Jul 22 2016 10:05:13 GMT-0400 (EDT)
Chapter 9: Date Comparison
It is possible to use setDate to change the date to a day in the following month by using a value larger than the
number of days in the current month - Section 9.1: Comparing Date values
var checkoutDate = new Date(); // Thu Jul 21 2016 10:05:13 GMT-0400 (EDT) To check the equality of Date values:
[Link]( [Link]() + 12 );
[Link](checkoutDate); // Tue Aug 02 2016 10:05:13 GMT-0400 (EDT) var date1 = new Date();
var date2 = new Date([Link]() + 10);
The same applies to other methods such as getHours(), getMonth(),etc. [Link]([Link]() === [Link]());

Adding Work Days


Sample output: false
If you wish to add work days (in this case I am assuming Monday - Friday) you can use the setDate function
although you need a little extra logic to account for the weekends (obviously this will not take account of national
Note that you must use valueOf() or getTime() to compare the values of Date objects because the equality
holidays) -
operator will compare if two object references are the same. For example:
function addWorkDays(startDate, days) {
// Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday) var date1 = new Date();
var dow = [Link](); var date2 = new Date();
var daysToAdd = days; [Link](date1 === date2);
// If the current day is Sunday add one day
if (dow == 0)
daysToAdd++; Sample output: false
// If the start date plus the additional days falls on or after the closest Saturday calculate
weekends
if (dow + daysToAdd >= 6) { Whereas if the variables point to the same object:
//Subtract days in current working week from work days
var remainingWorkDays = daysToAdd - (5 - dow); var date1 = new Date();
//Add current working week's weekend var date2 = date1;
daysToAdd += 2; [Link](date1 === date2);
if (remainingWorkDays > 5) {
//Add two days for each working week by calculating how many weeks are included
daysToAdd += 2 * [Link](remainingWorkDays / 5);
//Exclude final weekend if remainingWorkDays resolves to an exact number of weeks
Sample output: true
if (remainingWorkDays % 5 == 0)
daysToAdd -= 2;
} However, the other comparison operators will work as usual and you can use < and > to compare that one date is
} earlier or later than the other. For example:
[Link]([Link]() + daysToAdd);
return startDate; var date1 = new Date();
} var date2 = new Date([Link]() + 10);
[Link](date1 < date2);

Section 8.8: Convert to JSON


Sample output: true
var date1 = new Date();
[Link]();
It works even if the operator includes equality:

Returns: "2016-04-14T23:49:08.596Z" var date1 = new Date();


var date2 = new Date([Link]());
[Link](date1 <= date2);

Sample output: true

[Link] – JavaScript® Notes for Professionals 57 [Link] – JavaScript® Notes for Professionals 58
Section 9.2: Date Dierence Calculation Chapter 10: Comparison Operations
To compare the difference of two dates, we can do the comparison based on the timestamp.
Section 10.1: Abstract equality / inequality and type
var date1 = new Date(); conversion
var date2 = new Date([Link]() + 5000);
The Problem
var dateDiff = [Link]() - [Link]();
var dateDiffInYears = dateDiff/1000/60/60/24/365; //convert milliseconds into years
The abstract equality and inequality operators (== and !=) convert their operands if the operand types do not
[Link]("Date difference in years : " + dateDiffInYears); match. This type coercion is a common source of confusion about the results of these operators, in particular, these
operators aren't always transitive as one would expect.

"" == 0; // true A
0 == "0"; // true A
"" == "0"; // false B
false == 0; // true
false == "0"; // true

"" != 0; // false A
0 != "0"; // false A
"" != "0"; // true B
false != 0; // false
false != "0"; // false

The results start to make sense if you consider how JavaScript converts empty strings to numbers.

Number(""); // 0
Number("0"); // 0
Number(false); // 0

The Solution

In the statement false B, both the operands are strings ("" and "0"), hence there will be no type conversion and
since "" and "0" are not the same value, "" == "0" is false as expected.

One way to eliminate unexpected behavior here is making sure that you always compare operands of the same
type. For example, if you want the results of numerical comparison use explicit conversion:

var test = (a,b) => Number(a) == Number(b);


test("", 0); // true;
test("0", 0); // true
test("", "0"); // true;
test("abc", "abc"); // false as operands are not numbers

Or, if you want string comparison:

var test = (a,b) => String(a) == String(b);


test("", 0); // false;
test("0", 0); // true
test("", "0"); // false;

Side-note: Number("0") and new Number("0") isn't the same thing! While the former performs a type conversion,
the latter will create a new object. Objects are compared by reference and not by value which explains the results
below.

Number("0") == Number("0"); // true;

[Link] – JavaScript® Notes for Professionals 59 [Link] – JavaScript® Notes for Professionals 60
new Number("0") == new Number("0"); // false [Link]({}); // false
Version < 6
Finally, you have the option to use strict equality and inequality operators which will not perform any implicit type
conversions. You can check if a value is NaN by comparing it with itself:

"" === 0; // false value !== value; // true for NaN, false for any other value
0 === "0"; // false
"" === "0"; // false You can use the following polyfill for [Link]():

Further reference to this topic can be found here: [Link] = [Link] || function(value) {
return value !== value;
Which equals operator (== vs ===) should be used in JavaScript comparisons?. }

Abstract Equality (==) By contrast, the global function isNaN() returns true not only for NaN, but also for any value or expression that
cannot be coerced into a number:
Section 10.2: NaN Property of the Global Object
isNaN(NaN); // true
NaN ("Not a Number") is a special value defined by the IEEE Standard for Floating-Point Arithmetic, which is used when isNaN(0 / 0); // true
isNaN('str' - 12); // true
a non-numeric value is provided but a number is expected (1 * "two"), or when a calculation doesn't have a valid
number result ([Link](-1)). isNaN(24); // false
isNaN('24'); // false
Any equality or relational comparisons with NaN returns false, even comparing it with itself. Because, NaN is isNaN(Infinity); // false
supposed to denote the result of a nonsensical computation, and as such, it isn’t equal to the result of any other
nonsensical computations. isNaN('str'); // true
isNaN(undefined); // true
isNaN({}); // true
(1 * "two") === NaN //false

NaN === 0; // false ECMAScript defines a “sameness” algorithm called SameValue which, since ECMAScript 6, can be invoked with
NaN === NaN; // false [Link]. Unlike the == and === comparison, using [Link]() will treat NaN as identical with itself (and -0 as not
[Link] === NaN; // false identical with +0):

NaN < 0; // false


[Link](NaN, NaN) // true
NaN > 0; // false
[Link](+0, 0) // false
NaN > 0; // false
NaN >= NaN; // false
NaN === NaN // false
NaN >= 'two'; // false
+0 === 0 // true
Version < 6
Non-equal comparisons will always return true:
You can use the following polyfill for [Link]() (from MDN):
NaN !== 0; // true
NaN !== NaN; // true
if (![Link]) {
Checking if a value is NaN [Link] = function(x, y) {
Version ≥ 6 // SameValue algorithm
if (x === y) { // Steps 1-5, 7-10
You can test a value or expression for NaN by using the function [Link](): // Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
[Link](NaN); // true } else {
[Link](0 / 0); // true // Step 6.a: NaN == NaN
[Link]('str' - 12); // true return x !== x && y !== y;
}
[Link](24); // false };
[Link]('24'); // false }
[Link](1 / 0); // false Points to note
[Link](Infinity); // false
NaN itself is a number, meaning that it does not equal to the string "NaN", and most importantly (though perhaps
[Link]('str'); // false
unintuitively):
[Link](undefined); // false

[Link] – JavaScript® Notes for Professionals 61 [Link] – JavaScript® Notes for Professionals 62
typeof(NaN) === "number"; //true F() || T(); // true

Section 10.3: Short-circuiting in boolean operators Output:

The and-operator (&&) and the or-operator (||) employ short-circuiting to prevent unnecessary work if the outcome
'F'
of the operation does not change with the extra work.
'T'

In x && y, y will not be evaluated if x evaluates to false, because the whole expression is guaranteed to be false.
Short-circuiting to prevent errors
In x || y, y will not be evaluated if x evaluated to true, because the whole expression is guaranteed to be true.
var obj; // object has value of undefined
Example with functions if([Link]){ }// TypeError: Cannot read property 'property' of undefined
if([Link] && obj !== undefined){}// Line A TypeError: Cannot read property 'property' of
Take the following two functions: undefined

function T() { // True Line A: if you reverse the order the first conditional statement will prevent the error on the second by not executing
[Link]("T");
it if it would throw the error
return true;
}
if(obj !== undefined && [Link]){}; // no error thrown
function F() { // False
[Link]("F"); But should only be used if you expect undefined
return false;
}
if(typeof obj === "object" && [Link]){}; // safe option but slower

Example 1
Short-circuiting to provide a default value

T() && F(); // false The || operator can be used to select either a "truthy" value, or the default value.

Output: For example, this can be used to ensure that a nullable value is converted to a non-nullable value:

var nullableObj = null;


'T' var obj = nullableObj || {}; // this selects {}
'F'
var nullableObj2 = {x: 5};
var obj2 = nullableObj2 || {} // this selects {x: 5}
Example 2
Or to return the first truthy value
F() && T(); // false
var truthyValue = {x: 10};
Output: return truthyValue || {}; // will return {x: 10}

The same can be used to fall back multiple times:


'F'
envVariable || configValue || defaultConstValue // select the first "truthy" of these
Example 3
Short-circuiting to call an optional function
T() || F(); // true
The && operator can be used to evaluate a callback, only if it is passed:
Output:
function myMethod(cb) {
// This can be simplified
'T' if (cb) {
cb();
}
Example 4

[Link] – JavaScript® Notes for Professionals 63 [Link] – JavaScript® Notes for Professionals 64
// To this conversion happens is based on the specification of the operator:
cb && cb();
} Specification for the == operator:

Of course, the test above does not validate that cb is in fact a function and not just an
Object/Array/String/Number. 7.2.13 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or false. Such a comparison is
Section 10.4: Null and Undefined performed as follows:

The differences between null and undefined 1. If Type(x) is the same as Type(y), then:

a. Return the result of performing Strict Equality Comparison x === y.


null and undefined share abstract equality == but not strict equality ===,
2. If x is null and y is undefined, return true.
null == undefined // true 3. If x is undefined and y is null, return true.
null === undefined // false
4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
They represent slightly different things:
6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
undefined represents the absence of a value, such as before an identifier/Object property has been created
7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
or in the period between identifier/Function parameter creation and it's first set, if any. 8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the
comparison x == ToPrimitive(y).
null represents the intentional absence of a value for an identifier or property which has already been
9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the
created.
comparison ToPrimitive(x) == y.
They are different types of syntax: 10. Return false.

undefined is a property of the global Object, usually immutable in the global scope. This means anywhere you
Examples:
can define an identifier other than in the global namespace could hide undefined from that scope (although
1 == 1; // true
things can still be undefined)
1 == true; // true (operand converted to number: true => 1)
null is a word literal, so it's meaning can never be changed and attempting to do so will throw an Error. 1 == '1'; // true (operand converted to number: '1' => 1 )
1 == '1.00'; // true
The similarities between null and undefined 1 == '1.00000000001'; // false
1 == '1.00000000000000001'; // true (true due to precision loss)
null and undefined are both falsy. null == undefined; // true (spec #2)
1 == 2; // false
if (null) [Link]("won't be logged"); 0 == false; // true
if (undefined) [Link]("won't be logged"); 0 == undefined; // false
0 == ""; // true

Neither null or undefined equal false (see this question).


Section 10.6: Logic Operators with Booleans
false == undefined // false
false == null // false
var x = true,
false === undefined // false
y = false;
false === null // false

Using undefined
AND
If the current scope can't be trusted, use something which evaluates to undefined, for example void 0;.
If undefined is shadowed by another value, it's just as bad as shadowing Array or Number. This operator will return true if both of the expressions evaluate to true. This boolean operator will employ short-
Avoid setting something as undefined. If you want to remove a property bar from an Object foo, delete circuiting and will not evaluate y if x evaluates to false.
[Link]; instead.
x && y;
Existence testing identifier foo against undefined could throw a Reference Error, use typeof foo against
"undefined" instead.
This will return false, because y is false.

Section 10.5: Abstract Equality (==) OR

Operands of the abstract equality operator are compared after being converted to a common type. How this This operator will return true if one of the two expressions evaluate to true. This boolean operator will employ

[Link] – JavaScript® Notes for Professionals 65 [Link] – JavaScript® Notes for Professionals 66
short-circuiting and y will not be evaluated if x evaluates to true. var a = 'hello' && ''; // a = ''
var b = '' && []; // b = ''
x || y; var c = undefined && 0; // c = undefined
var d = 1 && 5; // d = 5
var e = 0 && {}; // e = 0
This will return true, because x is true.
var f = 'hi' && [] && 'done'; // f = 'done'
var g = 'bye' && undefined && 'adios'; // g = undefined
NOT

This trick can be used, for example, to set a default value to a function argument (prior to ES6).
This operator will return false if the expression on the right evaluates to true, and return true if the expression on
the right evaluates to false.
var foo = function(val) {
// if val evaluates to falsey, 'default' will be returned instead.
!x; return val || 'default';
}
This will return false, because x is true.
[Link]( foo('burger') ); // burger

Section 10.7: Automatic Type Conversions [Link](


[Link](
foo(100) );
foo([]) );
//
//
100
[]
[Link]( foo(0) ); // default
Beware that numbers can accidentally be converted to strings or NaN (Not a Number). [Link]( foo(undefined) ); // default

JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:
Just keep in mind that for arguments, 0 and (to a lesser extent) the empty string are also often valid values that
should be able to be explicitly passed and override a default, which, with this pattern, they won’t (because they are
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number falsy).

When doing mathematical operations, JavaScript can convert numbers to strings: Section 10.9: Empty Array
var x = 5 + 7; // [Link]() is 12, typeof x is a number /* ToNumber(ToPrimitive([])) == ToNumber(false) */
var x = 5 + "7"; // [Link]() is 57, typeof x is a string [] == false; // true
var x = "5" + 7; // [Link]() is 57, typeof x is a string
var x = 5 - 7; // [Link]() is -2, typeof x is a number When [].toString() is executed it calls [].join() if it exists, or [Link]() otherwise. This
var x = 5 - "7"; // [Link]() is -2, typeof x is a number
comparison is returning true because [].join() returns '' which, coerced into 0, is equal to false ToNumber.
var x = "5" - 7; // [Link]() is -2, typeof x is a number
var x = 5 - "x"; // [Link]() is NaN, typeof x is a number
Beware though, all objects are truthy and Array is an instance of Object:

Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):
// Internally this is evaluated as ToBoolean([]) === true ? 'truthy' : 'falsy'
[] ? 'truthy' : 'falsy'; // 'truthy'
"Hello" - "Dolly" // returns NaN

Section 10.10: Equality comparison operations


Section 10.8: Logic Operators with Non-boolean values
(boolean coercion) JavaScript has four different equality comparison operations.

Logical OR (||), reading left to right, will evaluate to the first truthy value. If no truthy value is found, the last value is SameValue
returned.
It returns true if both operands belong to the same Type and are the same value.
var a = 'hello' || ''; // a = 'hello'
var b = '' || []; // b = [] Note: the value of an object is a reference.
var c = '' || undefined; // c = undefined
var d = 1 || 5; // d = 1 You can use this comparison algorithm via [Link] (ECMAScript 6).
var e = 0 || {}; // e = {}
var f = 0 || '' || 5; // f = 5 Examples:
var g = '' || 'yay' || 'boo'; // g = 'yay'
[Link](1, 1); // true
Logical AND (&&), reading left to right, will evaluate to the first falsy value. If no falsey value is found, the last value is [Link](+0, -0); // false
returned. [Link](NaN, NaN); // true
[Link](true, "true"); // false
[Link](false, 0); // false

[Link] – JavaScript® Notes for Professionals 67 [Link] – JavaScript® Notes for Professionals 68
[Link](null, undefined); // false Symmetry: x === y is true if, and only if, y === xistrue, for any valuesxandy`.
[Link](1, "1"); // false
Transitivity: If x === y and y === z are true, then x === z is also true, for any values x, y and z.
[Link]([], []); // false

But is not an equivalence relation because


This algorithm has the properties of an equivalence relation:
NaN is not reflexive: NaN !== NaN
Reflexivity: [Link](x, x) is true, for any value x
Symmetry: [Link](x, y) is true if, and only if, [Link](y, x) is true, for any values x and y. Abstract Equality Comparison
Transitivity: If [Link](x, y) and [Link](y, z) are true, then [Link](x, z) is also true, for any
If both operands belong to the same Type, it behaves like the Strict Equality Comparison.
values x, y and z.

SameValueZero Otherwise, it coerces them as follows:

It behaves like SameValue, but considers +0 and -0 to be equal. undefined and null are considered to be equal
When comparing a number with a string, the string is coerced to a number
You can use this comparison algorithm via [Link] (ECMAScript 7). When comparing a boolean with something else, the boolean is coerced to a number
When comparing an object with a number, string or symbol, the object is coerced to a primitive
Examples:
If there was a coercion, the coerced values are compared recursively. Otherwise the algorithm returns false.
[1].includes(1); // true
[+0].includes(-0); // true You can use this comparison algorithm via the == operator (ECMAScript 1).
[NaN].includes(NaN); // true
[true].includes("true"); // false There is also the != operator (ECMAScript 1), which negates the result of ==.
[false].includes(0); // false
[1].includes("1"); // false
Examples:
[null].includes(undefined); // false
[[]].includes([]); // false
1 == 1; // true
+0 == -0; // true
This algorithm still has the properties of an equivalence relation: NaN == NaN; // false
true == "true"; // false
Reflexivity: [x].includes(x) is true, for any value x false == 0; // true
Symmetry: [x].includes(y) is true if, and only if, [y].includes(x) is true, for any values x and y. 1 == "1"; // true
Transitivity: If [x].includes(y) and [y].includes(z) are true, then [x].includes(z) is also true, for any null == undefined; // true
[] == []; // false
values x, y and z.

Strict Equality Comparison This algorithm has the following property:

It behaves like SameValue, but Symmetry: x == y is true if, and only if, y == x is true, for any values x and y.

Considers +0 and -0 to be equal. But is not an equivalence relation because


Considers NaN different than any value, including itself
NaN is not reflexive: NaN != NaN
You can use this comparison algorithm via the === operator (ECMAScript 3). Transitivity does not hold, e.g. 0 == '' and 0 == '0', but '' != '0'

There is also the !== operator (ECMAScript 3), which negates the result of ===. Section 10.11: Relational operators (<, <=, >, >=)
Examples: When both operands are numeric, they are compared normally:

1 === 1; // true
1 < 2 // true
+0 === -0; // true
2 <= 2 // true
NaN === NaN; // false
3 >= 5 // false
true === "true"; // false
true < false // false (implicitly converted to numbers, 1 > 0)
false === 0; // false
1 === "1"; // false
null === undefined; // false When both operands are strings, they are compared lexicographically (according to alphabetical order):
[] === []; // false
'a' < 'b' // true
This algorithm has the following properties: '1' < '2' // true

[Link] – JavaScript® Notes for Professionals 69 [Link] – JavaScript® Notes for Professionals 70
'100' > '12' // false ('100' is less than '12' lexicographically!)
Section 10.13: List of Comparison Operators
When one operand is a string and the other is a number, the string is converted to a number before comparison: Operator Comparison Example
== Equal i == 0
'1' < 2 // true === Equal Value and Type i === "5"
'3' > 2 // true
true > '2' // false (true implicitly converted to number, 1 < 2) != Not Equal i != 5
!== Not Equal Value or Type i !== 5
When the string is non-numeric, numeric conversion returns NaN (not-a-number). Comparing with NaN always > Greater than i > 5
returns false: < Less than i < 5
>= Greater than or equal i >= 5
1 < 'abc' // false
1 > 'abc' // false
<= Less than or equal i <= 5

But be careful when comparing a numeric value with null, undefined or empty strings: Section 10.14: Grouping multiple logic statements
1 > '' // true You can group multiple boolean logic statements within parenthesis in order to create a more complex logic
1 < '' // false evaluation, especially useful in if statements.
1 > null // true
1 < null // false
if ((age >= 18 && height >= 5.11) || (status === 'royalty' && hasInvitation)) {
1 > undefined // false
[Link]('You can enter our club');
1 < undefined // false
}

When one operand is a object and the other is a number, the object is converted to a number before
We could also move the grouped logic to variables to make the statement a bit shorter and descriptive:
[Link] null is particular case because Number(null);//0
var isLegal = age >= 18;
new Date(2015)< 1479480185280 // true var tall = height >= 5.11;
null > -1 //true var suitable = isLegal && tall;
({toString:function(){return 123}}) > 122 //true var isRoyalty = status === 'royalty';
var specialCase = isRoyalty && hasInvitation;

Section 10.12: Inequality var canEnterOurBar = suitable || specialCase;

if (canEnterOurBar) [Link]('You can enter our club');


Operator != is the inverse of the == operator.
Will return true if the operands aren't equal. Notice that in this particular example (and many others), grouping the statements with parenthesis works the same
The JavaScript engine will try and convert both operands to matching types if they aren't of the same type. Note: if as if we removed them, just follow a linear logic evaluation and you'll find yourself with the same result. I do prefer
the two operands have different internal references in memory, then false will be returned. using parenthesis as it allows me to understand clearer what I intended and might prevent for logic mistakes.

Sample:
Section 10.15: Bit fields to optimise comparison of multi state
1 != '1' // false data
1 != 2 // true
A bit field is a variable that holds various boolean states as individual bits. A bit on would represent true, and off
In the sample above, 1 != '1' is false because, a primitive number type is being compared to a char value. would be false. In the past bit fields were routinely used as they saved memory and reduced processing load.
Therefore, the JavaScript engine doesn't care about the datatype of the R.H.S value. Though the need to use bit field is no longer so important they do offer some benefits that can simplify many
processing tasks.
Operator: !== is the inverse of the === operator. Will return true if the operands are not equal or if their types do
not match. For example user input. When getting input from a keyboard's direction keys up, down, left, right you can encode
the various keys into a single variable with each direction assigned a bit.
Example:
Example reading keyboard via bitfield
1 !== '1' // true
1 !== 2 // true var bitField = 0; // the value to hold the bits
1 !== 1 // false const KEY_BITS = [4,1,8,2]; // left up right down
const KEY_MASKS = [0b1011,0b1110,0b0111,0b1101]; // left up right down
[Link] = [Link] = function (e) {
if([Link] >= 37 && [Link] <41){

[Link] – JavaScript® Notes for Professionals 71 [Link] – JavaScript® Notes for Professionals 72
if([Link] === "keydown"){
bitField |= KEY_BITS[[Link] - 37];
}else{
Chapter 11: Conditions
bitField &= KEY_MASKS[[Link] - 37];
Conditional expressions, involving keywords such as if and else, provide JavaScript programs with the ability to
}
} perform different actions depending on a Boolean condition: true or false. This section covers the use of JavaScript
} conditionals, Boolean logic, and ternary statements.

Example reading as an array Section 11.1: Ternary operators


var directionState = [false,false,false,false]; Can be used to shorten if/else operations. This comes in handy for returning a value quickly (i.e. in order to assign it
[Link] = [Link] = function (e) { to another variable).
if([Link] >= 37 && [Link] <41){
directionState[[Link] - 37] = [Link] === "keydown"; For example:
}
}
var animal = 'kitty';
var result = (animal === 'kitty') ? 'cute' : 'still nice';
To turn on a bit use bitwise or | and the value corresponding to the bit. So if you wish to set the 2nd bit bitField
|= 0b10 will turn it on. If you wish to turn a bit off use bitwise and & with a value that has all by the required bit on.
In this case, result gets the 'cute' value, because the value of animal is 'kitty'. If animal had another value, result
Using 4 bits and turning the 2nd bit off bitfield &= 0b1101; would get the 'still nice' value.

You may say the above example seems a lot more complex than assigning the various key states to an array. Yes, it Compare this to what the code would like with if/else conditions.
is a little more complex to set but the advantage comes when interrogating the state.
var animal = 'kitty';
If you want to test if all keys are up. var result = '';
if (animal === 'kitty') {
// as bit field result = 'cute';
if(!bitfield) // no keys are on } else {
result = 'still nice';
// as array test each item in array }
if(!(directionState[0] && directionState[1] && directionState[2] && directionState[3])){
The if or else conditions may have several operations. In this case the operator returns the result of the last
You can set some constants to make things easier expression.

// postfix U,D,L,R for Up down left right var a = 0;


const KEY_U = 1; var str = 'not a';
const KEY_D = 2; var b = '';
const KEY_L = 4; b = a === 0 ? (a = 1, str += ' test') : (a = 2);
const KEY_R = 8;
const KEY_UL = KEY_U + KEY_L; // up left
const KEY_UR = KEY_U + KEY_R; // up Right Because a was equal to 0, it becomes 1, and str becomes 'not a test'. The operation which involved str was the
const KEY_DL = KEY_D + KEY_L; // down left last, so b receives the result of the operation, which is the value contained in str, i.e. 'not a test'.
const KEY_DR = KEY_D + KEY_R; // down right
Ternary operators always expect else conditions, otherwise you'll get a syntax error. As a workaround you could
You can then quickly test for many various keyboard states return a zero something similar in the else branch - this doesn't matter if you aren't using the return value but just
shortening (or attempting to shorten) the operation.
if ((bitfield & KEY_UL) === KEY_UL) { // is UP and LEFT only down
if (bitfield & KEY_UL) { // is Up left down var a = 1;
if ((bitfield & KEY_U) === KEY_U) { // is Up only down a === 1 ? alert('Hey, it is 1!') : 0;
if (bitfield & KEY_U) { // is Up down (any other key may be down)
if (!(bitfield & KEY_U)) { // is Up up (any other key may be down)
As you see, if (a === 1) alert('Hey, it is 1!'); would do the same thing. It would be just a char longer, since
if (!bitfield ) { // no keys are down
if (bitfield ) { // any one or more keys are down it doesn't need an obligatory else condition. If an else condition was involved, the ternary method would be much
cleaner.
The keyboard input is just one example. Bitfields are useful when you have various states that must in combination
a === 1 ? alert('Hey, it is 1!') : alert('Weird, what could it be?');
be acted on. JavaScript can use up to 32 bits for a bit field. Using them can offer significant performance increases.
if (a === 1) alert('Hey, it is 1!') else alert('Weird, what could it be?');
They are worth being familiar with.

[Link] – JavaScript® Notes for Professionals 73 [Link] – JavaScript® Notes for Professionals 74
Ternaries can be nested to encapsulate additional logic. For example The break statement "breaks" out of the switch statement and ensures no more code within the switch statement
is executed. This is how sections are defined and allows the user to make "fall through" cases.
foo ? bar ? 1 : 2 : 3

// To be clear, this is evaluated left to right Warning: lack of a break or return statement for each case means the program will continue to evaluate
// and can be more explicitly expressed as: the next case, even if the case criteria is unmet!

foo ? (bar ? 1 : 2) : 3
switch (value) {
This is the same as the following if/else case 1:
[Link]('I will only run if value === 1');
if (foo) { // Here, the code "falls through" and will run the code under case 2
if (bar) { case 2:
1 [Link]('I will run if value === 1 or value === 2');
} else { break;
2 case 3:
} [Link]('I will only run if value === 3');
} else { break;
3 }
}
The last case is the default case. This one will run if no other matches were made.
Stylistically this should only be used with short variable names, as multi-line ternaries can drastically decrease
readability. var animal = 'Lion';
switch (animal) {
The only statements which cannot be used in ternaries are control statements. For example, you cannot use return case 'Dog':
[Link]('I will not run since animal !== "Dog"');
or break with ternaries. The following expression will be invalid.
break;
case 'Cat':
var animal = 'kitty'; [Link]('I will not run since animal !== "Cat"');
for (var i = 0; i < 5; ++i) { break;
(animal === 'kitty') ? break:[Link](i); default:
} [Link]('I will run since animal does not match any other case');
}
For return statements, the following would also be invalid:
It should be noted that a case expression can be any kind of expression. This means you can use comparisons,
var animal = 'kitty'; function calls, etc. as case values.
(animal === 'kitty') ? return 'meow' : return 'woof';
function john() {
To do the above properly, you would return the ternary as follows: return 'John';
}
var animal = 'kitty';
return (animal === 'kitty') ? 'meow' : 'woof'; function jacob() {
return 'Jacob';
}
Section 11.2: Switch statement
switch (name) {
Switch statements compare the value of an expression against 1 or more values and executes different sections of case john(): // Compare name with the return value of john() (name == "John")
[Link]('I will run if name === "John"');
code based on that comparison.
break;
case 'Ja' + 'ne': // Concatenate the strings together then compare (name == "Jane")
var value = 1; [Link]('I will run if name === "Jane"');
switch (value) { break;
case 1: case john() + ' ' + jacob() + ' Jingleheimer Schmidt':
[Link]('I will always run'); [Link]('His name is equal to name too!');
break; break;
case 2: }
[Link]('I will never run');
break; Multiple Inclusive Criteria for Cases
}
Since cases "fall through" without a break or return statement, you can use this to create multiple inclusive criteria:

[Link] – JavaScript® Notes for Professionals 75 [Link] – JavaScript® Notes for Professionals 76
var x = "c" }
switch (x) {
case "a": Some important footnotes about the above examples:
case "b":
case "c": If any one condition evaluated to true, no other condition in that chain of blocks will be evaluated, and all
[Link]("Either a, b, or c was selected.");
corresponding blocks (including the else block) will not be executed.
break;
case "d": The number of else if parts is practically unlimited. The last example above only contains one, but you can
[Link]("Only d was selected.");
have as many as you like.
break;
default: The condition inside an if statement can be anything that can be coerced to a boolean value, see the topic on
[Link]("No case was matched.");
boolean logic for more details;
break; // precautionary break if case order changes
}
The if-else-if ladder exits at the first success. That is, in the example above, if the value of i is 0.5 then the
first branch is executed. If the conditions overlap, the first criteria occurring in the flow of execution is
Section 11.3: If / Else If / Else Control executed. The other condition, which could also be true is ignored.

In its most simple form, an if condition can be used like this: If you have only one statement, the braces around that statement are technically optional, e.g this is fine:

var i = 0; if (i < 1) [Link]("i is smaller than 1");

if (i < 1) {
And this will work as well:
[Link]("i is smaller than 1");
}
if (i < 1)
[Link]("i is smaller than 1");
The condition i < 1 is evaluated, and if it evaluates to true the block that follows is executed. If it evaluates to
false, the block is skipped.
If you want to execute multiple statements inside an if block, then the curly braces around them are
mandatory. Only using indentation isn't enough. For example, the following code:
An if condition can be expanded with an else block. The condition is checked once as above, and if it evaluates to
false a secondary block will be executed (which would be skipped if the condition were true). An example:
if (i < 1)
[Link]("i is smaller than 1");
if (i < 1) { [Link]("this will run REGARDLESS of the condition"); // Warning, see text!
[Link]("i is smaller than 1");
} else {
[Link]("i was not smaller than 1"); is equivalent to:
}
if (i < 1) {
[Link]("i is smaller than 1");
Supposing the else block contains nothing but another if block (with optionally an else block) like this:
}
[Link]("this will run REGARDLESS of the condition");
if (i < 1) {
[Link]("i is smaller than 1");
} else {
if (i < 2) { Section 11.4: Strategy
[Link]("i is smaller than 2");
} else { A strategy pattern can be used in JavaScript in many cases to replace a switch statement. It is especially helpful
[Link]("none of the previous conditions was true"); when the number of conditions is dynamic or very large. It allows the code for each condition to be independent
}
and separately testable.
}

Strategy object is simple an object with multiple functions, representing each separate condition. Example:
Then there is also a different way to write this which reduces nesting:
const AnimalSays = {
if (i < 1) { dog () {
[Link]("i is smaller than 1"); return 'woof';
} else if (i < 2) { },
[Link]("i is smaller than 2");
} else { cat () {
[Link]("none of the previous conditions was true"); return 'meow';
},

[Link] – JavaScript® Notes for Professionals 77 [Link] – JavaScript® Notes for Professionals 78
lion () {

},
return 'roar'; Chapter 12: Arrays
// ... other animals Section 12.1: Converting Array-like Objects to Arrays
default () { What are Array-like Objects?
return 'moo';
} JavaScript has "Array-like Objects", which are Object representations of Arrays with a length property. For example:
};
var realArray = ['a', 'b', 'c'];
The above object can be used as follows: var arrayLike = {
0: 'a',
function makeAnimalSpeak (animal) { 1: 'b',
// Match the animal by type 2: 'c',
const speak = AnimalSays[animal] || [Link]; length: 3
[Link](animal + ' says ' + speak()); };
}
Common examples of Array-like Objects are the arguments object in functions and HTMLCollection or NodeList
Results: objects returned from methods like [Link] or [Link].

makeAnimalSpeak('dog') // => 'dog says woof' However, one key difference between Arrays and Array-like Objects is that Array-like objects inherit from
makeAnimalSpeak('cat') // => 'cat says meow' [Link] instead of [Link]. This means that Array-like Objects can't access common Array
makeAnimalSpeak('lion') // => 'lion says roar' prototype methods like forEach(), push(), map(), filter(), and slice():
makeAnimalSpeak('snake') // => 'snake says moo'

var parent = [Link]('myDropdown');


In the last case, our default function handles any missing animals. var desiredOption = [Link]('option[value="desired"]');
var domList = [Link];

Section 11.5: Using || and && short circuiting [Link](desiredOption); // Error! indexOf is not defined.
[Link](function() {
The Boolean operators || and && will "short circuit" and not evaluate the second parameter if the first is true or [Link](/* Stuff here */) // Error! map is not defined.
false respectively. This can be used to write short conditionals like: }); // Error! forEach is not defined.

var x = 10 function func() {


[Link](arguments);
x == 10 && alert("x is 10") }
x == 10 || alert("x is not 10") func(1, 2, 3); // → [1, 2, 3]

Convert Array-like Objects to Arrays in ES6

1. [Link]:

Version ≥ 6
const arrayLike = {
0: 'Value 0',
1: 'Value 1',
length: 2
};
[Link](value => {/* Do something */}); // Errors
const realArray = [Link](arrayLike);
[Link](value => {/* Do something */}); // Works

2. for...of:

Version ≥ 6
var realArray = [];
for(const element of arrayLike) {
[Link](element);
}

[Link] – JavaScript® Notes for Professionals 79 [Link] – JavaScript® Notes for Professionals 80
3. Spread operator: }); // Wow! this works

Version ≥ 6 Modifying Items During Conversion


[...arrayLike]
In ES6, while using [Link], we can specify a map function that returns a mapped value for the new array being
4. [Link]: created.

Version ≥ 7 Version ≥ 6

var realArray = [Link](arrayLike); [Link](domList, element => [Link]); // Creates an array of tagName's

5. [Link]: See Arrays are Objects for a detailed analysis.


Version ≥ 6
var realArray = Object Section 12.2: Reducing values
.keys(arrayLike)
.map((key) => arrayLike[key]); Version ≥ 5.1

Convert Array-like Objects to Arrays in ≤ ES5 The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to
reduce it to a single value.
Use [Link] like so:
Array Sum
var arrayLike = {
0: 'Value 0', This method can be used to condense all values of an array into a single value:
1: 'Value 1',
length: 2
[1, 2, 3, 4].reduce(function(a, b) {
};
return a + b;
var realArray = [Link](arrayLike);
});
realArray = [].[Link](arrayLike); // Shorter version
// → 10
[Link]('Value 1'); // Wow! this works
Optional second parameter can be passed to reduce(). Its value will be used as the first argument (specified as a)
You can also use [Link] to call [Link] methods on Array-like objects directly, without for the first call to the callback (specified as function(a, b)).
converting them:
[2].reduce(function(a, b) {
Version ≥ 5.1 [Link](a, b); // prints: 1 2
var domList = [Link]('#myDropdown option'); return a + b;
}, 1);
[Link](function() { // → 3
// Do stuff
}); // Error! forEach is not defined.
Version ≥ 5.1
Flatten Array of Objects
[Link](domList, function() {
// Do stuff
}); // Wow! this works The example below shows how to flatten an array of objects into a single object.

var array = [{
You can also use [].[Link]( arrayLikeObject ) to borrow array methods and glom them on to your object:
key: 'one',
Version ≥ 5.1 value: 1
}, {
var arrayLike = {
key: 'two',
0: 'Value 0',
value: 2
1: 'Value 1',
}, {
length: 2
key: 'three',
};
value: 3
}];
[Link](function() {
Version ≤ 5.1
// Do stuff
}); // Error! forEach is not defined. [Link](function(obj, current) {
obj[[Link]] = [Link];
[].[Link](arrayLike)(function(val){ return obj;
// Do stuff with val }, {});

[Link] – JavaScript® Notes for Professionals 81 [Link] – JavaScript® Notes for Professionals 82
Version ≥ 6
var arr = [1, 2, 1, 5, 9, 5];
[Link]((obj, current) => [Link](obj, {
[[Link]]: [Link] [Link]((prev, number) => {
}), {}); if([Link](number) === -1) {
Version ≥ 7 [Link](number);
[Link]((obj, current) => ({...obj, [[Link]]: [Link]}), {}); }
return prev;
}, []);
Note that the Rest/Spread Properties is not in the list of finished proposals of ES2016. It isn't supported by ES2016. // → [1, 2, 5, 9]
But we can use babel plugin babel-plugin-transform-object-rest-spread to support it.

Section 12.3: Mapping values


All of the above examples for Flatten Array result in:
It is often necessary to generate a new array based on the values of an existing array.
{
one: 1, For example, to generate an array of string lengths from an array of strings:
two: 2,
three: 3 Version ≥ 5.1
} ['one', 'two', 'three', 'four'].map(function(value, index, arr) {
return [Link];
Version ≥ 5.1 });
// → [3, 3, 5, 4]
Map Using Reduce
Version ≥ 6
As another example of using the initial value parameter, consider the task of calling a function on an array of items, ['one', 'two', 'three', 'four'].map(value => [Link]);
returning the results in a new array. Since arrays are ordinary values and list concatenation is an ordinary function, // → [3, 3, 5, 4]
we can use reduce to accumulate a list, as the following example demonstrates:
In this example, an anonymous function is provided to the map() function, and the map function will call it for every
function map(list, fn) { element in the array, providing the following parameters, in this order:
return [Link](function(newList, item) {
return [Link](fn(item)); The element itself
}, []); The index of the element (0, 1...)
}
The entire array
// Usage:
map([1, 2, 3], function(n) { return n * n; }); Additionally, map() provides an optional second parameter in order to set the value of this in the mapping
// → [1, 4, 9] function. Depending on the execution environment, the default value of this might vary:

In a browser, the default value of this is always window:


Note that this is for illustration (of the initial value parameter) only, use the native map for working with list
transformations (see Mapping values for the details).
['one', 'two'].map(function(value, index, arr) {
[Link](this); // window (the default value in browsers)
return [Link];
Version ≥ 5.1
});
Find Min or Max Value

You can change it to any custom object like this:


We can use the accumulator to keep track of an array element as well. Here is an example leveraging this to find
the min value:
['one', 'two'].map(function(value, index, arr) {
[Link](this); // Object { documentation: "randomObject" }
var arr = [4, 2, 1, -10, 9] return [Link];
}, {
[Link](function(a, b) { documentation: 'randomObject'
return a < b ? a : b });
}, Infinity);
// → -10
Version ≥ 6 Section 12.4: Filtering Object Arrays
Find Unique Values
The filter() method accepts a test function, and returns a new array containing only the elements of the original
Here is an example that uses reduce to return the unique numbers to an array. An empty array is passed as the array that pass the test provided.
second argument and is referenced by prev.

[Link] – JavaScript® Notes for Professionals 83 [Link] – JavaScript® Notes for Professionals 84
// Suppose we want to get all odd number in an array: This returns:
var numbers = [5, 32, 43, 4];
Version ≥ 5.1 [{
var odd = [Link](function(n) { id: 1,
return n % 2 !== 0; name: "John",
}); age: 28
},{
Version ≥ 6
id: 2,
let odd = [Link](n => n % 2 !== 0); // can be shortened to (n => n % 2) name: "Jane",
age: 31
odd would contain the following array: [5, 43]. }]

It also works on an array of objects:


Section 12.5: Sorting Arrays
var people = [{
The .sort() method sorts the elements of an array. The default method will sort the array according to string
id: 1,
name: "John",
Unicode code points. To sort an array numerically the .sort() method needs to have a compareFunction passed to
age: 28 it.
}, {
id: 2,
name: "Jane", Note: The .sort() method is impure. .sort() will sort the array in-place, i.e., instead of creating a
age: 31 sorted copy of the original array, it will re-order the original array and return it.
}, {
id: 3,
name: "Peter", Default Sort
age: 55
}]; Sorts the array in UNICODE order.
Version ≥ 5.1
var young = [Link](function(person) { ['s', 't', 'a', 34, 'K', 'o', 'v', 'E', 'r', '2', '4', 'o', 'W', -1, '-4'].sort();
return [Link] < 35;
});
Results in:
Version ≥ 6
let young = [Link](person => [Link] < 35); [-1, '-4', '2', 34, '4', 'E', 'K', 'W', 'a', 'l', 'o', 'o', 'r', 's', 't', 'v']

young would contain the following array:


Note: The uppercase characters have moved above lowercase. The array is not in alphabetical order, and
[{ numbers are not in numerical order.
id: 1,
name: "John",
age: 28 Alphabetical Sort
}, {
id: 2,
['s', 't', 'a', 'c', 'K', 'o', 'v', 'E', 'r', 'f', 'l', 'W', '2', '1'].sort((a, b) => {
name: "Jane",
return [Link](b);
age: 31
});
}]

Results in:
You can search in the whole array for a value like this:

['1', '2', 'a', 'c', 'E', 'f', 'K', 'l', 'o', 'r', 's', 't', 'v', 'W']
var young = [Link]((obj) => {
var flag = false;
[Link](obj).forEach((val) => {
if(String(val).indexOf("J") > -1) { Note: The above sort will throw an error if any array items are not a string. If you know that the array
flag = true; may contain items that are not strings use the safe version below.
return;
}
}); ['s', 't', 'a', 'c', 'K', 1, 'v', 'E', 'r', 'f', 'l', 'o', 'W'].sort((a, b) => {
if(flag) return obj; return [Link]().localeCompare(b);
}); });

[Link] – JavaScript® Notes for Professionals 85 [Link] – JavaScript® Notes for Professionals 86
String sorting by length (longest first) new Date(2009, 6, 11),
new Date(2016, 7, 23)
];
["zebras", "dogs", "elephants", "penguins"].sort(function(a, b) {
return [Link] - [Link];
[Link](function(a, b) {
});
if (a > b) return -1;
if (a < b) return 1;
Results in return 0;
});
["elephants", "penguins", "zebras", "dogs"];
// the date objects can also sort by its difference
// the same way that numbers array is sorting
String sorting by length (shortest first)
[Link](function(a, b) {
return b-a;
["zebras", "dogs", "elephants", "penguins"].sort(function(a, b) { });
return [Link] - [Link];
});
Results in:

Results in
[
"Tue Aug 23 2016 00:00:00 GMT-0600 (MDT)",
["dogs", "zebras", "penguins", "elephants"]; "Fri Mar 21 2014 00:00:00 GMT-0600 (MDT)",
"Sat Jul 11 2009 00:00:00 GMT-0600 (MDT)",
Numerical Sort (ascending) "Mon Dec 10 2007 00:00:00 GMT-0700 (MST)"
]

[100, 1000, 10, 10000, 1].sort(function(a, b) {


return a - b;
});
Section 12.6: Iteration
A traditional for-loop
Results in:
A traditional for loop has three components:
[1, 10, 100, 1000, 10000]
1. The initialization: executed before the look block is executed the first time
Numerical Sort (descending) 2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false
3. The afterthought: performed every time after the loop block is executed
[100, 1000, 10, 10000, 1].sort(function(a, b) {
return b - a; These three components are separated from each other by a ; symbol. Content for each of these three
}); components is optional, which means that the following is the most minimal for loop possible:

Results in: for (;;) {


// Do stuff
[10000, 1000, 100, 10, 1] }

Sorting array by even and odd numbers Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) {
return; } somewhere inside that for-loop to get it to stop running.
[10, 21, 4, 15, 7, 99, 0, 12].sort(function(a, b) {
return (a & 1) - (b & 1) || a - b; Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a
}); minimum or maximum value, and the afterthought is used to increment the index:

Results in: for (var i = 0, length = 10; i < length; i++) {


[Link](i);
[0, 4, 10, 12, 7, 15, 21, 99] }

Date Sort (descending) Using a traditional for loop to loop through an array

var dates = [ The traditional way to loop through an array, is this:


new Date(2007, 11, 10),
new Date(2014, 2, 21), for (var i = 0, length = [Link]; i < length; i++) {

[Link] – JavaScript® Notes for Professionals 87 [Link] – JavaScript® Notes for Professionals 88
[Link](myArray[i]); for (i in myArray) {
} [Link](myArray[i]);
}
Or, if you prefer to loop backwards, you do this:
This should be used with care, however, as it doesn't behave the same as a traditional for loop in all cases, and
for (var i = [Link] - 1; i > -1; i--) { there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad
[Link](myArray[i]);
idea? for more details.
}

for...of
There are, however, many variations possible, like for example this one:
In ES 6, the for-of loop is the recommended way of iterating over a the values of an array:
for (var key = 0, value = myArray[key], length = [Link]; key < length; value =
myArray[++key]) { Version ≥ 6
[Link](value); let myArray = [1, 2, 3, 4];
} for (let value of myArray) {
let twoValue = value * 2;
... or this one ... [Link]("2 * value is: %d", twoValue);
}

var i = 0, length = [Link];


for (; i < length;) { The following example shows the difference between a for...of loop and a for...in loop:
[Link](myArray[i]);
i++; Version ≥ 6

} let myArray = [3, 5, 7];


[Link] = "hello";
... or this one:
for (var i in myArray) {
[Link](i); // logs 0, 1, 2, "foo"
var key = 0, value; }
for (; value = myArray[key++];){
[Link](value); for (var i of myArray) {
} [Link](i); // logs 3, 5, 7
}
Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.
[Link]()
Note that each of these variations is supported by all browsers, including very very old ones!
The [Link]() method can be used to iterate over indices like this:

A while loop Version ≥ 6


let myArray = [1, 2, 3, 4];
One alternative to a for loop is a while loop. To loop through an array, you could do this: for (let i of [Link]()) {
let twoValue = myArray[i] * 2;
var key = 0; [Link]("2 * value is: %d", twoValue);
while(value = myArray[key++]){ }
[Link](value);
} [Link]()

Like traditional for loops, while loops are supported by even the oldest of browsers. The .forEach(...) method is an option in ES 5 and above. It is supported by all modern browsers, as well as
Internet Explorer 9 and later.
Also, note that every while loop can be rewritten as a for loop. For example, the while loop hereabove behaves the
exact same way as this for-loop: Version ≥ 5
[1, 2, 3, 4].forEach(function(value, index, arr) {
for(var key = 0; value = myArray[key++];){ var twoValue = value * 2;
[Link](value); [Link]("2 * value is: %d", twoValue);
} });

Comparing with the traditional for loop, we can't jump out of the loop in .forEach(). In this case, use the for loop,
for...in
or use partial iteration presented below.
In JavaScript, you can also do this:

[Link] – JavaScript® Notes for Professionals 89 [Link] – JavaScript® Notes for Professionals 90
In all versions of JavaScript, it is possible to iterate through the indices of an array using a traditional C-style for Libraries
loop.
Finally, many utility libraries also have their own foreach variation. Three of the most popular ones are these:
var myArray = [1, 2, 3, 4];
for(var i = 0; i < [Link]; ++i) { [Link](), in jQuery:
var twoValue = myArray[i] * 2;
[Link]("2 * value is: %d", twoValue); $.each(myArray, function(key, value) {
} [Link](value);
});
It's also possible to use while loop:
_.each(), in [Link]:
var myArray = [1, 2, 3, 4],
i = 0, sum = 0; _.each(myArray, function(value, key, myArray) {
while(i++ < [Link]) { [Link](value);
sum += i; });
}
[Link](sum);
_.forEach(), in [Link]:

[Link] _.forEach(myArray, function(value, key) {


[Link](value);
Since ES5, if you want to iterate over a portion of an array, you can use [Link], which iterates until });
we return false:
See also the following question on SO, where much of this information was originally posted:
Version ≥ 5
// [].every() stops once it finds a false result
Loop through an array in JavaScript
// thus, this iteration will stop on value 7 (since 7 % 2 !== 0)
[2, 4, 7, 9].every(function(value, index, arr) {
[Link](value); Section 12.7: Destructuring an array
return value % 2 === 0; // iterate until an odd number is found
}); Version ≥ 6

An array can be destructured when being assigned to a new variable.


Equivalent in any JavaScript version:

const triangle = [3, 4, 5];


var arr = [2, 4, 7, 9];
const [length, height, hypotenuse] = triangle;
for (var i = 0; i < [Link] && (arr[i] % 2 !== 0); i++) { // iterate until an odd number is
found
length === 3; // → true
[Link](arr[i]);
} height === 4; // → true
hypotneuse === 5; // → true

[Link]
Elements can be skipped
[Link] iterates until we return true:
const [,b,,c] = [1, 2, 3, 4];
Version ≥ 5
// [].some stops once it finds a false result [Link](b, c); // → 2, 4
// thus, this iteration will stop on value 7 (since 7 % 2 !== 0)
[2, 4, 7, 9].some(function(value, index, arr) { Rest operator can be used too
[Link](value);
return value === 7; // iterate until we find value 7
const [b,c, ...xs] = [2, 3, 4, 5];
});
[Link](b, c, xs); // → 2, 3, [4, 5]

Equivalent in any JavaScript version:


An array can also be destructured if it's an argument to a function.
var arr = [2, 4, 7, 9];
for (var i = 0; i < [Link] && arr[i] !== 7; i++) { function area([length, height]) {
[Link](arr[i]); return (length * height) / 2;
} }

[Link] – JavaScript® Notes for Professionals 91 [Link] – JavaScript® Notes for Professionals 92
const triangle = [3, 4, 5]; if (!compareArrays(array1[i], array2[i])) { // Do items compare recursively
return false;
area(triangle); // → 6 }
}
return true; // must be equal
Notice the third argument is not named in the function because it's not needed.
}

Learn more about destructuring syntax.


WARNING: Using the above function is dangerous and should be wrapped in a try catch if you suspect there is a
chance the array has cyclic references (a reference to an array that contains a reference to itself)
Section 12.8: Removing duplicate elements
a = [0] ;
From ES5.1 onwards, you can use the native method [Link] to loop through an array and leave a[1] = a;
b = [0, a];
only entries that pass a given callback function.
compareArrays(a, b); // throws RangeError: Maximum call stack size exceeded

In the following example, our callback checks if the given value occurs in the array. If it does, it is a duplicate and will
not be copied to the resulting array. Note: The function uses the strict equality operator === to compare non array items {a: 0} === {a: 0}
Version ≥ 5.1 is false
var uniqueArray = ['a', 1, 'a', 2, '1', 1].filter(function(value, index, self) {
return [Link](value) === index;
}); // returns ['a', 1, 2, '1'] Section 12.10: Reversing arrays
If your environment supports ES6, you can also use the Set object. This object lets you store unique values of any .reverse is used to reverse the order of items inside an array.

type, whether primitive values or object references:


Example for .reverse:
Version ≥ 6
var uniqueArray = [... new Set(['a', 1, 'a', 2, '1', 1])]; [1, 2, 3, 4].reverse();

Results in:
Section 12.9: Array comparison
[4, 3, 2, 1]
For simple array comparison you can use JSON stringify and compare the output strings:

[Link](array1) === [Link](array2)


Note: Please note that .reverse([Link]) will reverse the array in place. Instead of
returning a reversed copy, it will return the same array, reversed.
Note: that this will only work if both objects are JSON serializable and do not contain cyclic references. It
var arr1 = [11, 22, 33];
may throw TypeError: Converting circular structure to JSON
var arr2 = [Link]();
[Link](arr2); // [33, 22, 11]
[Link](arr1); // [33, 22, 11]
You can use a recursive function to compare arrays.

You can also reverse an array 'deeply' by:


function compareArrays(array1, array2) {
var i, isA1, isA2;
isA1 = [Link](array1); function deepReverse(arr) {
isA2 = [Link](array2); [Link]().forEach(elem => {
if([Link](elem)) {
if (isA1 !== isA2) { // is one an array and the other not? deepReverse(elem);
return false; // yes then can not be the same }
} });
if (! (isA1 && isA2)) { // Are both not arrays return arr;
return array1 === array2; // return strict equality }
}
if ([Link] !== [Link]) { // if lengths differ then can not be the same Example for deepReverse:
return false;
}
var arr = [1, 2, 3, [1, 2, 3, ['a', 'b', 'c']]];
// iterate arrays and compare them
for (i = 0; i < [Link]; i += 1) {

[Link] – JavaScript® Notes for Professionals 93 [Link] – JavaScript® Notes for Professionals 94
deepReverse(arr); Version ≥ 3

Provide more Array arguments to [Link]()


Results in:

var arrConc = [Link](array2, array3, array4);


arr // -> [[['c','b','a'], 3, 2, 1], 3, 2, 1]
Version ≥ 6

Section 12.11: Shallow cloning an array Provide more arguments to []

Sometimes, you need to work with an array while ensuring you don't modify the original. Instead of a clone var arrConc = [...array1, ...array2, ...array3, ...array4]
method, arrays have a slice method that lets you perform a shallow copy of any part of an array. Keep in mind
that this only clones the first level. This works well with primitive types, like numbers and strings, but not objects. Results in a new Array:

To shallow-clone an array (i.e. have a new array instance but with the same elements), you can use the following ["a", "b", "c", "d", "e", "f", "g", "h"]
one-liner:
Without Copying the First Array
var clone = [Link]();
var longArray = [1, 2, 3, 4, 5, 6, 7, 8],
This calls the built-in JavaScript [Link] method. If you pass arguments to slice, you can get more shortArray = [9, 10];
complicated behaviors that create shallow clones of only part of an array, but for our purposes just calling slice() Version ≥ 3
will create a shallow copy of the entire array.
Provide the elements of shortArray as parameters to push using [Link]
All method used to convert array like objects to array are applicable to clone an array:
[Link](longArray, shortArray);
Version ≥ 6 Version ≥ 6
arrayToClone = [1, 2, 3, 4, 5];
clone1 = [Link](arrayToClone); Use the spread operator to pass the elements of shortArray as separate arguments to push
clone2 = [Link](...arrayToClone);
clone3 = [...arrayToClone] // the shortest way [Link](...shortArray)
Version ≤ 5.1
arrayToClone = [1, 2, 3, 4, 5]; The value of longArray is now:
clone1 = [Link](arrayToClone);
clone2 = [].[Link](arrayToClone);
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Section 12.12: Concatenating Arrays Note that if the second array is too long (>100,000 entries), you may get a stack overflow error (because of how
apply works). To be safe, you can iterate instead:
Two Arrays
[Link](function (elem) {
var array1 = [1, 2]; [Link](elem);
var array2 = [3, 4, 5]; });
Version ≥ 3
var array3 = [Link](array2); // returns a new array Array and non-array values
Version ≥ 6
var array3 = [...array1, ...array2] var array = ["a", "b"];
Version ≥ 3

Results in a new Array: var arrConc = [Link]("c", "d");


Version ≥ 6
[1, 2, 3, 4, 5] var arrConc = [...array, "c", "d"]

Multiple Arrays Results in a new Array:

var array1 = ["a", "b"], ["a", "b", "c", "d"]


array2 = ["c", "d"],
array3 = ["e", "f"],
You can also mix arrays with non-arrays
array4 = ["g", "h"];

[Link] – JavaScript® Notes for Professionals 95 [Link] – JavaScript® Notes for Professionals 96
var arr1 = ["a","b"]; If the mapping is not performed then:
var arr2 = ["e", "f"];
let arr = [..."123456"]; // ["1", "2", "3", "4", "5", "6"]
var arrConc = [Link]("c", "d", arr2);

The spread operator can also be used to spread arguments into a function:
Results in a new Array:
function myFunction(a, b, c) { }
["a", "b", "c", "d", "e", "f"] let args = [0, 1, 2];

Section 12.13: Merge two array as key value pair myFunction(...args);

// in ES < 6, this would be equivalent to:


When we have two separate array and we want to make key value pair from that two array, we can use array's [Link](null, args);
reduce function like below:
Rest operator

var columns = ["Date", "Number", "Size", "Location", "Age"]; The rest operator does the opposite of the spread operator by coalescing several elements into a single one
var rows = ["2001", "5", "Big", "Sydney", "25"];
var result = [Link](function(result, field, index) {
[a, b, ...rest] = [1, 2, 3, 4, 5, 6]; // rest is assigned [3, 4, 5, 6]
result[columns[index]] = field;
return result;
}, {}) Collect arguments of a function:

[Link](result); function myFunction(a, b, ...rest) { [Link](rest); }

Output: myFunction(0, 1, 2, 3, 4, 5, 6); // rest is [2, 3, 4, 5, 6]

{
Date: "2001",
Section 12.15: Filtering values
Number: "5",
The filter() method creates an array filled with all array elements that pass a test provided as a function.
Size: "Big",
Location: "Sydney",
Version ≥ 5.1
Age: "25"
} [1, 2, 3, 4, 5].filter(function(value, index, arr) {
return value > 2;
});
Section 12.14: Array spread / rest Version ≥ 6
[1, 2, 3, 4, 5].filter(value => value > 2);
Spread operator
Version ≥ 6
Results in a new array:
With ES6, you can use spreads to separate individual elements into a comma-separated syntax:
[3, 4, 5]

let arr = [1, 2, 3, ...[4, 5, 6]]; // [1, 2, 3, 4, 5, 6] Filter falsy values


Version ≥ 5.1
// in ES < 6, the operations above are equivalent to var filtered = [ 0, undefined, {}, null, '', true, 5].filter(Boolean);
arr = [1, 2, 3];
[Link](4, 5, 6);
Since Boolean is a native JavaScript function/constructor that takes [one optional parameter] and the filter method
also takes a function and passes it the current array item as parameter, you could read it like the following:
The spread operator also acts upon strings, separating each individual character into a new string element.
Therefore, using an array function for converting these into integers, the array created above is equivalent to the 1. Boolean(0) returns false
one below: 2. Boolean(undefined) returns false
3. Boolean({}) returns true which means push it to the returned array
let arr = [1, 2, 3, ...[..."456"].map(x=>parseInt(x))]; // [1, 2, 3, 4, 5, 6]
4. Boolean(null) returns false
5. Boolean('') returns false
Or, using a single string, this could be simplified to:
6. Boolean(true) returns true which means push it to the returned array
let arr = [..."123456"].map(x=>parseInt(x)); // [1, 2, 3, 4, 5, 6] 7. Boolean(5) returns true which means push it to the returned array

[Link] – JavaScript® Notes for Professionals 97 [Link] – JavaScript® Notes for Professionals 98
so the overall process will result ];
var index = [Link](item => [Link] === 3); // 2
[ {}, true, 5 ] var index = [Link](item => [Link] === 12); // -1

Another simple example


Section 12.17: Convert a String to an Array
This example utilises the same concept of passing a function that takes one argument
The .split() method splits a string into an array of substrings. By default .split() will break the string into
Version ≥ 5.1 substrings on spaces (" "), which is equivalent to calling .split(" ").
function startsWithLetterA(str) {
if(str && str[0].toLowerCase() == 'a') { The parameter passed to .split() specifies the character, or the regular expression, to use for splitting the string.
return true
} To split a string into an array call .split with an empty string (""). Important Note: This only works if all of your
return false; characters fit in the Unicode lower range characters, which covers most English and most European languages. For
}
languages that require 3 and 4 byte Unicode characters, slice("") will separate them.
var str = 'Since Boolean is a native javascript function/constructor that takes [one
optional parameter] and the filter method also takes a function and passes it the current array var strArray = "StackOverflow".split("");
item as a parameter, you could read it like the following'; // strArray = ["S", "t", "a", "c", "k", "O", "v", "e", "r", "f", "l", "o", "w"]
var strArray = [Link](" "); Version ≥ 6
var wordsStartsWithA = [Link](startsWithLetterA);
//["a", "and", "also", "a", "and", "array", "as"] Using the spread operator (...), to convert a string into an array.

Section 12.16: Searching an Array var strArray = [..."sky is blue"];


// strArray = ["s", "k", "y", " ", "i", "s", " ", "b", "l", "u", "e"]

The recommended way (Since ES5) is to use [Link].find:


Section 12.18: Removing items from an array
let people = [
{ name: "bob" }, Shift
{ name: "john" }
]; Use .shift to remove the first item of an array.

let bob = [Link](person => [Link] === "bob"); For example:

// Or, more verbose


var array = [1, 2, 3, 4];
let bob = [Link](function(person) {
[Link]();
return [Link] === "bob";
});
array results in:
In any version of JavaScript, a standard for loop can be used as well:
[2, 3, 4]

for (var i = 0; i < [Link]; i++) {


if (people[i].name === "bob") { Pop
break; // we found bob
}
Further .pop is used to remove the last item from an array.
}

For example:
FindIndex
var array = [1, 2, 3];
The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing [Link]();
function. Otherwise -1 is returned.
array results in:
array = [
{ value: 1 }, [1, 2]
{ value: 2 },
{ value: 3 },
Both methods return the removed item;
{ value: 4 },
{ value: 5 }
Splice

[Link] – JavaScript® Notes for Professionals 99 [Link] – JavaScript® Notes for Professionals 100
Use .splice() to remove a series of elements from an array. .splice() accepts two parameters, the starting Care must be taken as this does not remove any items from the original array. The array may have been closed
index, and an optional number of elements to delete. If the second parameter is left out .splice() will remove all over when passed to a function. The array will remain in memory for the life of the function though you may not be
elements from the starting index through the end of the array. aware of this. This is a common source of memory leaks.

For example: Example of a memory leak resulting from bad array clearing:

var array = [1, 2, 3, 4]; var count = 0;


[Link](1, 2);
function addListener(arr) { // arr is closed over
var b = [Link]("#foo" + (count++));
leaves array containing:
[Link]("click", function(e) { // this functions reference keeps
// the closure current while the
[1, 4] // event is active
// do something but does not need arr
The return of [Link]() is a new array containing the removed elements. For the example above, the return });
would be: }

arr = ["big data"];


[2, 3]
var i = 100;
while (i > 0) {
Thus, omitting the second parameter effectively splits the array into two arrays, with the original ending before the addListener(arr); // the array is passed to the function
index specified: arr = []; // only removes the reference, the original array remains
[Link]("some large data"); // more memory allocated
i--;
var array = [1, 2, 3, 4];
}
[Link](2);
// there are now 100 arrays closed over, each referencing a different array
// no a single item has been deleted
...leaves array containing [1, 2] and returns [3, 4].
To prevent the risk of a memory leak use the one of the following 2 methods to empty the array in the above
Delete
example's while loop.
Use delete to remove item from array without changing the length of array:
Method 2
var array = [1, 2, 3, 4, 5];
Setting the length property deletes all array element from the new array length to the old array length. It is the
[Link]([Link]); // 5
delete array[2]; most efficient way to remove and dereference all items in the array. Keeps the reference to the original array
[Link](array); // [1, 2, undefined, 4, 5]
[Link]([Link]); // 5 [Link] = 0;

Method 3
[Link]
Similar to method 2 but returns a new array containing the removed items. If you do not need the items this
Assigning value to length of array changes the length to given value. If new value is less than array length items will method is inefficient as the new array is still created only to be immediately dereferenced.
be removed from the end of value.
[Link](0); // should not use if you don't want the removed items
array = [1, 2, 3, 4, 5]; // only use this method if you do the following
[Link] = 2; var keepArr = [Link](0); // empties the array and creates a new array containing the
[Link](array); // [1, 2] // removed items

Related question.
Section 12.19: Removing all elements
var arr = [1, 2, 3, 4]; Section 12.20: Finding the minimum or maximum element
Method 1 If your array or array-like object is numeric, that is, if all its elements are numbers, then you can use [Link]
or [Link] by passing null as the first argument, and your array as the second.
Creates a new array and overwrites the existing array reference with a new one.

var myArray = [1, 2, 3, 4];


arr = [];
[Link](null, myArray); // 1

[Link] – JavaScript® Notes for Professionals 101 [Link] – JavaScript® Notes for Professionals 102
[Link](null, myArray); // 4 var arr = [1, 2, 3, 4];
Version ≥ 6 var arr2 = new Array(1, 2, 3, 4);

In ES6 you can use the ... operator to spread an array and take the minimum or maximum element.
If the Array constructor is used with no arguments, an empty array is created.

var myArray = [1, 2, 3, 4, 99, 20];


var arr3 = new Array();

var maxValue = [Link](...myArray); // 99


var minValue = [Link](...myArray); // 1 results in:

The following example uses a for loop: []

var maxValue = myArray[0]; Note that if it's used with exactly one argument and that argument is a number, an array of that length with all
for(var i = 1; i < [Link]; i++) { undefined values will be created instead:
var currentValue = myArray[i];
if(currentValue > maxValue) { var arr4 = new Array(4);
maxValue = currentValue;
}
} results in:
Version ≥ 5.1
[undefined, undefined, undefined, undefined]
The following example uses [Link]() to find the minimum or maximum:
That does not apply if the single argument is non-numeric:
var myArray = [1, 2, 3, 4];
var arr5 = new Array("foo");
[Link](function(a, b) {
return [Link](a, b);
results in:
}); // 1

[Link](function(a, b) { ["foo"]
return [Link](a, b); Version ≥ 6
}); // 4
Version ≥ 6 Similar to an array literal, [Link] can be used to create a new Array instance given a number of arguments:

or using arrow functions: [Link](21, "Hello", "World");

[Link]((a, b) => [Link](a, b)); // 1 results in:


[Link]((a, b) => [Link](a, b)); // 4
Version ≥ 5.1 [21, "Hello", "World"]

To generalize the reduce version we'd have to pass in an initial value to cover the empty list case:
In contrast to the Array constructor, creating an array with a single number such as [Link](23) will create a new
array [23], rather than an Array with length 23.
function myMax(array) {
return [Link](function(maxSoFar, element) {
return [Link](maxSoFar, element);
The other way to create and initialize an array would be [Link]
}, -Infinity);
} var newArray = [Link]({ length: 5 }, (_, index) => [Link](index, 4));

myMax([3, 5]); // 5 will result:


myMax([]); // -Infinity
[Link](null, []); // -Infinity
[0, 1, 16, 81, 256]

For the details on how to properly use reduce see Reducing values.
Section 12.22: Joining array elements in a string
Section 12.21: Standard array initialization To join all of an array's elements into a string, you can use the join method:

There are many ways to create arrays. The most common are to use array literals, or the Array constructor: [Link](["Hello", " ", "world"].join("")); // "Hello world"

[Link] – JavaScript® Notes for Professionals 103 [Link] – JavaScript® Notes for Professionals 104
[Link]([1, 800, 555, 1234].join("-")); // "1-800-555-1234" Or if you want to change the array itself without creating a copy (for example if you write a function that get an
array as a function and manipulates it) you can use this snippet:
As you can see in the second line, items that are not strings will be converted first.
while(index = [Link](3) !== -1) { [Link](index, 1); }
Section 12.23: Removing/Adding elements using splice()
And if you need to remove just the first value found, remove the while loop:
The splice()method can be used to remove elements from an array. In this example, we remove the first 3 from
the array. var index = [Link](to_remove);
if(index !== -1) { [Link](index , 1); }
var values = [1, 2, 3, 4, 5, 3];
var i = [Link](3);
if (i >= 0) {
Section 12.26: Flattening Arrays
[Link](i, 1);
} 2 Dimensional arrays
// [1, 2, 4, 5, 3] Version ≥ 6

In ES6, we can flatten the array by the spread operator ...:


The splice() method can also be used to add elements to an array. In this example, we will insert the numbers 6,
7, and 8 to the end of the array. function flattenES6(arr) {
return [].concat(...arr);
var values = [1, 2, 4, 5, 3]; }
var i = [Link] + 1;
[Link](i, 0, 6, 7, 8); var arrL1 = [1, 2, [3, 4]];
//[1, 2, 4, 5, 3, 6, 7, 8] [Link](flattenES6(arrL1)); // [1, 2, 3, 4]
Version ≥ 5
The first argument of the splice() method is the index at which to remove/insert elements. The second argument
is the number of elements to remove. The third argument and onwards are the values to insert into the array. In ES5, we can achieve that by .apply():

Section 12.24: The entries() method function flatten(arr) {


return [].[Link]([], arr);
}
The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the
array. var arrL1 = [1, 2, [3, 4]];
[Link](flatten(arrL1)); // [1, 2, 3, 4]
Version ≥ 6
Higher Dimension Arrays
var letters = ['a','b','c'];

Given a deeply nested array like so


for(const[index,element] of [Link]()){
[Link](index,element);
} var deeplyNested = [4,[5,6,[7,8],9]];

result It can be flattened with this magic

0 "a" [Link](String(deeplyNested).split(',').map(Number);
1 "b" #=> [4,5,6,7,8,9]
2 "c"
Or
Note: This method is not supported in Internet Explorer.
const flatten = [Link]().split(',').map(Number)
Portions of this content from [Link] by Mozilla Contributors licensed under CC-by-SA 2.5 [Link](flatten);
#=> [4,5,6,7,8,9]

Section 12.25: Remove value from array


Both of the above methods only work when the array is made up exclusively of numbers. A multi-dimensional array
When you need to remove a specific value from an array, you can use the following one-liner to create a copy array of objects cannot be flattened by this method.
without the given value:

[Link](function(val) { return val !== to_remove; });

[Link] – JavaScript® Notes for Professionals 105 [Link] – JavaScript® Notes for Professionals 106
Section 12.27: Append / Prepend items to Array Section 12.29: Logical connective of values
Unshift Version ≥ 5.1

.some and .every allow a logical connective of Array values.


Use .unshift to add one or more items in the beginning of an array.

For example: While .some combines the return values with OR, .every combines them with AND.

Examples for .some


var array = [3, 4, 5, 6];
[Link](1, 2);
[false, false].some(function(value) {
return value;
array results in: });
// Result: false
[1, 2, 3, 4, 5, 6]
[false, true].some(function(value) {
return value;
Push });
// Result: true
Further .push is used to add items after the last currently existent item.
[true, true].some(function(value) {
For example: return value;
});
var array = [1, 2, 3]; // Result: true
[Link](4, 5, 6);
And examples for .every
array results in:
[false, false].every(function(value) {
[1, 2, 3, 4, 5, 6] return value;
});
// Result: false
Both methods return the new array length.
[false, true].every(function(value) {
Section 12.28: Object keys and values to array return value;
});
// Result: false
var object = {
key1: 10,
[true, true].every(function(value) {
key2: 3,
return value;
key3: 40,
});
key4: 20
// Result: true
};

var array = [];


for(var people in object) {
Section 12.30: Checking if an object is an Array
[Link]([people, object[people]]);
[Link](obj) returns true if the object is an Array, otherwise false.
}

[Link]([]) // true
Now array is
[Link]([1, 2, 3]) // true
[Link]({}) // false
[ [Link](1) // false
["key1", 10],
["key2", 3],
In most cases you can instanceof to check if an object is an Array.
["key3", 40],
["key4", 20]
] [] instanceof Array; // true
{} instanceof Array; // false

[Link] has the an advantage over using a instanceof check in that it will still return true even if the
prototype of the array has been changed and will return false if a non-arrays prototype was changed to the Array

[Link] – JavaScript® Notes for Professionals 107 [Link] – JavaScript® Notes for Professionals 108
prototype. Version ≥ 6
[Link]((a,b) => a[1] - b[1]);
var arr = [];
[Link](arr, null); This will output
[Link](arr); // true
arr instanceof Array; // false
[
["key2", 3],

Section 12.31: Insert an item into an array at a specific index ["key1",


["key4",
10],
20],
["key3", 40]
Simple item insertion can be done with [Link] method: ]

[Link](index, 0, item);
Be aware that the sort method operates on the array in place. It changes the array. Most other array methods
return a new array, leaving the original one intact. This is especially important to note if you use a functional
More advanced variant with multiple arguments and chaining support:
programming style and expect functions to not have side-effects.

/* Syntax:
[Link](index, value1, value2, ..., valueN) */ Section 12.33: Test all array items for equality
[Link] = function(index) { The .every method tests if all array elements pass a provided predicate test.
[Link](this, [index, 0].concat(
[Link](arguments, 1))); To test all objects for equality, you can use the following code snippets.
return this;
};
[1, 2, 1].every(function(item, i, list) { return item === list[0]; }); // false
[1, 1, 1].every(function(item, i, list) { return item === list[0]; }); // true
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6); // ["b", "X", "Y", "Z", "c"]
Version ≥ 6
[1, 1, 1].every((item, i, list) => item === list[0]); // true
And with array-type arguments merging and chaining support:

/* Syntax: The following code snippets test for property equality


[Link](index, value1, value2, ..., valueN) */
let data = [
[Link] = function(index) { { name: "alice", id: 111 },
index = [Link](index, [Link]); { name: "alice", id: 222 }
[Link] > 1 ];
&& [Link](this, [index, 0].concat([].[Link](arguments)))
&& [Link](this, arguments); [Link](function(item, i, list) { return item === list[0]; }); // false
return this; [Link](function(item, i, list) { return [Link] === list[0].name; }); // true
}; Version ≥ 6
[Link]((item, i, list) => [Link] === list[0].name); // true
["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-"); // "a-b-V-W-X-Y-Z-c-d"

Section 12.32: Sorting multidimensional array Section 12.34: Copy part of an Array
The slice() method returns a copy of a portion of an array.
Given the following array
It takes two parameters, [Link]([begin[, end]]) :
var array = [
["key1", 10],
begin
["key2", 3],
["key3", 40],
Zero-based index which is the beginning of extraction.
["key4", 20]
];
end

You can sort it sort it by number(second index)


Zero-based index which is the end of extraction, slicing up to this index but it's not included.

[Link](function(a, b) { If the end is a negative number,end = [Link] + end.


return a[1] - b[1];
})
Example 1

[Link] – JavaScript® Notes for Professionals 109 [Link] – JavaScript® Notes for Professionals 110
// Let's say we have this Array of Alphabets
var arr = ["a", "b", "c", "d"...]; Chapter 13: Objects
// I want an Array of the first two Alphabets Property Description
var newArr = [Link](0, 2); // newArr === ["a", "b"] value The value to assign to the property.
Example 2 writable Whether the value of the property can be changed or not.
// Let's say we have this Array of Numbers enumerable Whether the property will be enumerated in for in loops or not.
// and I don't know it's end
configurable Whether it will be possible to redefine the property descriptor or not.
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9...];
get A function to be called that will return the value of the property.
// I want to slice this Array starting from set A function to be called when the property is assigned a value.
// number 5 to its end
var newArr = [Link](4); // newArr === [5, 6, 7, 8, 9...]
Section 13.1: Shallow cloning
Version ≥ 6

ES6's [Link]() function can be used to copy all of the enumerable properties from an existing Object
instance to a new one.

const existing = { a: 1, b: 2, c: 3 };

const clone = [Link]({}, existing);

This includes Symbol properties in addition to String ones.

Object rest/spread destructuring which is currently a stage 3 proposal provides an even simpler way to create
shallow clones of Object instances:

const existing = { a: 1, b: 2, c: 3 };

const { ...clone } = existing;

If you need to support older versions of JavaScript, the most-compatible way to clone an Object is by manually
iterating over its properties and filtering out inherited ones using .hasOwnProperty().

var existing = { a: 1, b: 2, c: 3 };

var clone = {};


for (var prop in existing) {
if ([Link](prop)) {
clone[prop] = existing[prop];
}
}

Section 13.2: [Link]


Version ≥ 5

[Link] makes an object immutable by preventing the addition of new properties, the removal of existing
properties, and the modification of the enumerability, configurability, and writability of existing properties. It also
prevents the value of existing properties from being changed. However, it does not work recursively which means
that child objects are not automatically frozen and are subject to change.

The operations following the freeze will fail silently unless the code is running in strict mode. If the code is in strict

[Link] – JavaScript® Notes for Professionals 111 [Link] – JavaScript® Notes for Professionals 112
mode, a TypeError will be thrown. function deepClone(obj) {
function clone(obj, traversedObjects) {
var obj = { var copy;
foo: 'foo', // primitive types
bar: [1, 2, 3], if(obj === null || typeof obj !== "object") {
baz: { return obj;
foo: 'nested-foo' }
}
}; // detect cycles
for(var i = 0; i < [Link]; i++) {
[Link](obj); if(traversedObjects[i] === obj) {
throw new Error("Cannot clone circular object.");
// Cannot add new properties }
[Link] = true; }

// Cannot modify existing values or their descriptors // dates


[Link] = 'not foo'; if(obj instanceof Date) {
[Link](obj, 'foo', { copy = new Date();
writable: true [Link]([Link]());
}); return copy;
}
// Cannot delete existing properties // arrays
delete [Link]; if(obj instanceof Array) {
copy = [];
// Nested objects are not frozen for(var i = 0; i < [Link]; i++) {
[Link](4); [Link](clone(obj[i], [Link](obj)));
[Link] = 'new foo'; }
return copy;
}
Section 13.3: Object cloning // simple objects
if(obj instanceof Object) {
When you want a complete copy of an object (i.e. the object properties and the values inside those properties, copy = {};
etc...), that is called deep cloning. for(var key in obj) {
if([Link](key)) {
Version ≥ 5.1 copy[key] = clone(obj[key], [Link](obj));
}
If an object can be serialized to JSON, then you can create a deep clone of it with a combination of [Link] and }
return copy;
[Link]:
}
throw new Error("Not a cloneable object.");
var existing = { a: 1, b: { c: 2 } }; }
var copy = [Link]([Link](existing));
existing.b.c = 3; // copy.b.c will not change return clone(obj, []);
}
Note that [Link] will convert Date objects to ISO-format string representations, but [Link] will not
convert the string back into a Date.
Section 13.4: Object properties iteration
You can access each property that belongs to an object with this loop
There is no built-in function in JavaScript for creating deep clones, and it is not possible in general to create deep
clones for every object for many reasons. For example,
for (var property in object) {
// always check if an object has a property
objects can have non-enumerable and hidden properties which cannot be detected.
if ([Link](property)) {
object getters and setters cannot be copied. // do stuff
objects can have a cyclic structure. }
function properties can depend on state in a hidden scope. }

Assuming that you have a "nice" object whose properties only contain primitive values, dates, arrays, or other "nice" You should include the additional check for hasOwnProperty because an object may have properties that are
objects, then the following function can be used for making deep clones. It is a recursive function that can detect inherited from the object's base class. Not performing this check can raise errors.
objects with a cyclic structure and will throw an error in such cases.
Version ≥ 5

[Link] – JavaScript® Notes for Professionals 113 [Link] – JavaScript® Notes for Professionals 114
You can also use [Link] function which return an Array containing all properties of an object and then you Use it as reducer: (merges an array to an object)
can loop through this array with [Link] or [Link] function.
return [Link]((result, user) => [Link]({}, {[[Link]]: user})
var obj = { 0: 'a', 1: 'b', 2: 'c' };

[Link](obj).map(function(key) {
Section 13.6: Object rest/spread (...)
[Link](key);
Version > 7
});
// outputs: 0, 1, 2
Object spreading is just syntactic sugar for [Link]({}, obj1, ..., objn);

Section 13.5: [Link] It is done with the ... operator:

The [Link]() method is used to copy the values of all enumerable own properties from one or more source let obj = { a: 1 };
objects to a target object. It will return the target object.
let obj2 = { ...obj, b: 2, c: 3 };
Use it to assign values to an existing object:
[Link](obj2); // { a: 1, b: 2, c: 3 };

var user = {
firstName: "John" As [Link] it does shallow merging, not deep merging.
};
let obj3 = { ...obj, b: { c: 2 } };
[Link](user, {lastName: "Doe", age:39});
[Link](user); // Logs: {firstName: "John", lastName: "Doe", age: 39} [Link](obj3); // { a: 1, b: { c: 2 } };

Or to create a shallow copy of an object: NOTE: This specification is currently in stage 3

var obj = [Link]({}, user);

[Link](obj); // Logs: {firstName: "John", lastName: "Doe", age: 39}


Section 13.7: [Link]fineProperty
Version ≥ 5
Or merge many properties from multiple objects to one:
It allows us to define a property in an existing object using a property descriptor.
var obj1 = {
a: 1 var obj = { };
};
var obj2 = { [Link](obj, 'foo', { value: 'foo' });
b: 2
}; [Link]([Link]);
var obj3 = {
c: 3 Console output
};
var obj = [Link](obj1, obj2, obj3);
foo
[Link](obj); // Logs: { a: 1, b: 2, c: 3 }
[Link](obj1); // Logs: { a: 1, b: 2, c: 3 }, target object itself is changed
[Link] can be called with the following options:
Primitives will be wrapped, null and undefined will be ignored:
[Link](obj, 'nameOfTheProperty', {
var var_1 = 'abc'; value: valueOfTheProperty,
var var_2 = true; writable: true, // if false, the property is read-only
var var_3 = 10; configurable : true, // true means the property can be changed later
var var_4 = Symbol('foo'); enumerable : true // true means property can be enumerated such as in a for..in loop
});
var obj = [Link]({}, var_1, null, var_2, undefined, var_3, var_4);
[Link](obj); // Logs: { "0": "a", "1": "b", "2": "c" } [Link] allows you to define multiple properties at a time.

var obj = {};


Note, only string wrappers can have own enumerable properties

[Link] – JavaScript® Notes for Professionals 115 [Link] – JavaScript® Notes for Professionals 116
[Link](obj, { alert(word + '\n\n' + definition)
property1: {
value: true,
Note how we are using [] bracket notation to look at the variable named word; if we were to use the traditional .
writable: true
},
notation, then it would take the value literally, hence:
property2: {
value: 'Hello', [Link]([Link]) // doesn't work because word is taken literally and dictionary has no
writable: false field named `word`
} [Link]([Link]) // it works! because apple is taken literally
});
[Link](dictionary[word]) // it works! because word is a variable, and the user perfectly typed
in one of the words from our dictionary when prompted
Section 13.8: Accesor properties (get and set) [Link](dictionary[apple]) // error! apple is not defined (as a variable)

Version ≥ 5
You could also write literal values with [] notation by replacing the variable word with a string 'apple'. See
Treat a property as a combination of two functions, one to get the value from it, and another one to set the value in [Properties with special characters or reserved words] example.
it.
You can also set dynamic properties with the bracket syntax:

The get property of the property descriptor is a function that will be called to retrieve the value from the property. var property="test";
var obj={
The set property is also a function, it will be called when the property has been assigned a value, and the new value [property]=1;
};
will be passed as an argument.
[Link]([Link]);//1
You cannot assign a value or writable to a descriptor that has get or set

It does the same as:


var person = { name: "John", surname: "Doe"};
[Link](person, 'fullName', {
get: function () { var property="test";
return [Link] + " " + [Link]; var obj={};
}, obj[property]=1;
set: function (value) {

}
[[Link], [Link]] = [Link](" ");
Section 13.10: Arrays are Objects
});

[Link]([Link]); // -> "John Doe" Disclaimer: Creating array-like objects is not recommend. However, it is helpful to understand how they
work, especially when working with DOM. This will explain why regular array operations don't work on
[Link] = "Hill"; DOM objects returned from many DOM document functions. (i.e. querySelectorAll, [Link])
[Link]([Link]); // -> "John Hill"

[Link] = "Mary Jones"; Supposing we created the following object which has some properties you would expect to see in an Array.
[Link]([Link]) // -> "Mary"
var anObject = {
Section 13.9: Dynamic / variable property names foo: 'bar',
length: 'interesting',
'0': 'zero!',
Sometimes the property name needs to be stored into a variable. In this example, we ask the user what word needs
'1': 'one!'
to be looked up, and then provide the result from an object I've named dictionary. };

var dictionary = { Then we'll create an array.


lettuce: 'a veggie',
banana: 'a fruit',
var anArray = ['zero.', 'one.'];
tomato: 'it depends on who you ask',
apple: 'a fruit',
Apple: 'Steve Jobs rocks!' // properties are case-sensitive Now, notice how we can inspect both the object, and the array in the same way.
}
[Link](anArray[0], anObject[0]); // outputs: zero. zero!
var word = prompt('What word would you like to look up today?') [Link](anArray[1], anObject[1]); // outputs: one. one!
var definition = dictionary[word] [Link]([Link], [Link]); // outputs: 2 interesting

[Link] – JavaScript® Notes for Professionals 117 [Link] – JavaScript® Notes for Professionals 118
[Link]([Link], [Link]); // outputs: undefined bar writable: false
}); // TypeError
Since anArray is actually an object, just like anObject, we can even add custom wordy properties to anArray
[Link] = 'newFoo';
[Link]; // 'foo';
Disclaimer: Arrays with custom properties are not usually recommended as they can be confusing, but it
can be useful in advanced cases where you need the optimized functions of an Array. (i.e. jQuery objects) In strict mode these operations will throw a TypeError

(function () {
[Link] = 'it works!'; 'use strict';
[Link]([Link]);
var obj = { foo: 'foo' };

We can even make anObject to be an array-like object by adding a length. [Link](obj);

[Link] = 2; [Link] = 'newFoo'; // TypeError


}());
Then you can use the C-style for loop to iterate over anObject just as if it were an Array. See Array Iteration

Note that anObject is only an array-like object. (also known as a List) It is not a true Array. This is important,
Section 13.12: Convert object's values to array
because functions like push and forEach (or any convenience function found in [Link]) will not work by Given this object:
default on array-like objects.
var obj = {
Many of the DOM document functions will return a List (i.e. querySelectorAll, [Link]) which is similar to a: "hello",
the array-like anObject we created above. See Converting Array-like Objects to Arrays b: "this is",
c: "javascript!",
[Link](typeof anArray == 'object', typeof anObject == 'object'); // outputs: true true };
[Link](anArray instanceof Object, anObject instanceof Object); // outputs: true true
[Link](anArray instanceof Array, anObject instanceof Array); // outputs: true false You can convert its values to an array by doing:
[Link]([Link](anArray), [Link](anObject)); // outputs: true false
var array = [Link](obj)
Section 13.11: [Link] .map(function(key) {
return obj[key];
Version ≥ 5 });

[Link] prevents the addition or removal of properties from an object. Once an object has been sealed its [Link](array); // ["hello", "this is", "javascript!"]

property descriptors can't be converted to another type. Unlike [Link] it does allow properties to be
edited. Section 13.13: Retrieving properties from an object
Attempts to do this operations on a sealed object will fail silently Characteristics of properties :

var obj = { foo: 'foo', bar: function () { return 'bar'; } }; Properties that can be retrieved from an object could have the following characteristics,

[Link](obj) Enumerable
Non - Enumerable
[Link] = 'newFoo';
own
[Link] = function () { return 'foo' };

[Link]; // undefined While creating the properties using [Link]fineProperty(ies), we could set its characteristics except "own".
[Link](); // 'foo' Properties which are available in the direct level not in the prototype level (__proto__) of an object are called as own
properties.
// Can't make foo an accessor property
[Link](obj, 'foo', { And the properties that are added into an object without using [Link](ies) will don't have its
get: function () { return 'newFoo'; }
enumerable characteristic. That means it be considered as true.
}); // TypeError

// But you can make it read only


Purpose of enumerability :
[Link](obj, 'foo', {
The main purpose of setting enumerable characteristics to a property is to make the particular property's

[Link] – JavaScript® Notes for Professionals 119 [Link] – JavaScript® Notes for Professionals 120
availability when retrieving it from its object, by using different programmatical methods. Those different methods [Link](props); //["a"]
will be discussed deeply below.
//Ex 3 : Data with non enumerable properties
var x = { a : 10 } , props;
Methods of retrieving properties :
[Link](x, "b", {value : 5, enumerable : false});

Properties from an object could be retrieved by the following methods, props = [Link](x);

1. for..in loop [Link](props); //["a"]

This loop is very useful in retrieving enumerable properties from an object. Additionally this loop will retrieve 3. [Link]() function
enumerable own properties as well as it will do the same retrieval by traversing through the prototype chain
until it sees the prototype as null.
This function will retrieve both enumerable and non enumerable, own properties from an object. It was also
released as a part of ECMAScript 5.
//Ex 1 : Simple data
var x = { a : 10 , b : 3} , props = [];
//Ex 1 : Simple data
for(prop in x){ var x = { a : 10 , b : 3} , props;
[Link](prop);
} props = [Link](x);

[Link](props); //["a","b"] [Link](props); //["a","b"]

//Ex 2 : Data with enumerable properties in prototype chain //Ex 2 : Data with enumerable properties in prototype chain
var x = { a : 10 , __proto__ : { b : 10 }} , props = []; var x = { a : 10 , __proto__ : { b : 10 }} , props;

for(prop in x){ props = [Link](x);


[Link](prop);
} [Link](props); //["a"]

[Link](props); //["a","b"] //Ex 3 : Data with non enumerable properties


var x = { a : 10 } , props;
//Ex 3 : Data with non enumerable properties [Link](x, "b", {value : 5, enumerable : false});
var x = { a : 10 } , props = [];
[Link](x, "b", {value : 5, enumerable : false}); props = [Link](x);

for(prop in x){ [Link](props); //["a", "b"]


[Link](prop);
}
Miscellaneous :
[Link](props); //["a"]
A technique for retrieving all (own, enumerable, non enumerable, all prototype level) properties from an object is
2. [Link]() function given below,

function getAllProperties(obj, props = []){


This function was unveiled as a part of ECMAScript 5. It is used to retrieve enumerable own properties from return obj == null ? props :
an object. Prior to its release people used to retrieve own properties from an object by combining for..in getAllProperties([Link](obj),
loop and [Link]() function. [Link]([Link](obj)));
}
//Ex 1 : Simple data
var x = { a : 10 , b : 3} , props; var x = {a:10, __proto__ : { b : 5, c : 15 }};

props = [Link](x); //adding a non enumerable property to first level prototype


[Link](x.__proto__, "d", {value : 20, enumerable : false});
[Link](props); //["a","b"]
[Link](getAllProperties(x)); ["a", "b", "c", "d", "...other default core props..."]
//Ex 2 : Data with enumerable properties in prototype chain
var x = { a : 10 , __proto__ : { b : 10 }} , props; And this will be supported by the browsers which supports ECMAScript 5.

props = [Link](x);

[Link] – JavaScript® Notes for Professionals 121 [Link] – JavaScript® Notes for Professionals 122
Section 13.14: Read-Only property var obj = {};

Version ≥ 5 // Define 'foo' as read only and lock it


[Link](obj, "foo", {
Using property descriptors we can make a property read only, and any attempt to change its value will fail silently, value: "original value",
the value will not be changed and no error will be thrown. writable: false,
configurable: false
});
The writable property in a property descriptor indicates whether that property can be changed or not.
[Link](obj, "foo", {writable: true});

var a = { };
This error will be thrown:
[Link](a, 'foo', { value: 'original', writable: false });

[Link] = 'new'; TypeError: Cannot redefine property: foo

[Link]([Link]);
And the property will still be read only.
Console output
[Link] = "new value";
[Link](foo);
original
Console output

Section 13.15: Non enumerable property original value


Version ≥ 5

We can avoid a property from showing up in for (... in ...) loops Section 13.17: [Link]
Get the description of a specific property in an object.
The enumerable property of the property descriptor tells whether that property will be enumerated while looping
through the object's properties. var sampleObject = {
hello: 'world'
var obj = { }; };

[Link](obj, "foo", { value: 'show', enumerable: true }); [Link](sampleObject, 'hello');


[Link](obj, "bar", { value: 'hide', enumerable: false }); // Object {value: "world", writable: true, enumerable: true, configurable: true}

for (var prop in obj) {


[Link](obj[prop]); Section 13.18: Descriptors and Named Properties
}
Properties are members of an object. Each named property is a pair of (name, descriptor). The name is a string that
Console output allows access (using the dot notation [Link] or the square brackets notation
object['propertyName']). The descriptor is a record of fields defining the bevahiour of the property when it is
accessed (what happens to the property and what is the value returned from accessing it). By and large, a property
show
associates a name to a behavior (we can think of the behavior as a black box).

There are two types of named properties:


Section 13.16: Lock property description
1. data property: the property's name is associated with a value.
Version ≥ 5
2. accessor property: the property's name is associated with one or two accessor functions.
A property's descriptor can be locked so no changes can be made to it. It will still be possible to use the property
Demonstration:
normally, assigning and retrieving the value from it, but any attempt to redefine it will throw an exception.

obj.propertyName1 = 5; //translates behind the scenes into


The configurable property of the property descriptor is used to disallow any further changes on the descriptor. //either assigning 5 to the value field* if it is a data property
//or calling the set function with the parameter 5 if accessor property

[Link] – JavaScript® Notes for Professionals 123 [Link] – JavaScript® Notes for Professionals 124
//*actually whether an assignment would take place in the case of a data property var obj = {propertyName1: 1}; //the pair is actually ('propertyName1', {value:1,
//also depends on the presence and value of the writable field - on that later on // writable:true,
// enumerable:true,
The property's type is determined by its descriptor's fields, and a property cannot be of both types. // configurable:true})
[Link](obj, 'propertyName2', {get: function() {
Data descriptors - [Link]('this will be logged ' +
'every time propertyName2 is accessed to get its value');
},
Required fields: value or writable or both
set: function() {
Optional fields:configurable,enumerable [Link]('and this will be logged ' +
'every time propertyName2\'s value is tried to be set')
Sample: //will be treated like it has enumerable:false, configurable:false
}});
{ //propertyName1 is the name of obj's data property
value: 10, //and propertyName2 is the name of its accessor property
writable: true;
}

Accessor descriptors -
obj.propertyName1 = 3;
Required fields: get or set or both
[Link](obj.propertyName1); //3
Optional fields: configurable, enumerable
obj.propertyName2 = 3; //and this will be logged every time propertyName2's value is tried to be set
Sample: [Link](obj.propertyName2); //this will be logged every time propertyName2 is accessed to get
its value
{
get: function () {
return 10; Section 13.19: [Link]
},
Version ≥ 5
enumerable: true
}
[Link](obj) returns an array of a given object's keys.

meaning of fields and their defaults


var obj = {
configurable,enumerable and writable: a: "hello",
b: "this is",
These keys all default to false. c: "javascript!"
configurable is true if and only if the type of this property descriptor may be changed and if the property };
may be deleted from the corresponding object.
var keys = [Link](obj);
enumerable is true if and only if this property shows up during enumeration of the properties on the
corresponding object. [Link](keys); // ["a", "b", "c"]
writable is true if and only if the value associated with the property may be changed with an assignment
operator.
Section 13.20: Properties with special characters or reserved
get and set: words
These keys default to undefined. While object property notation is usually written as [Link], this will only allow characters that are
get is a function which serves as a getter for the property, or undefined if there is no getter. The function normally found in JavaScript variable names, which is mainly letters, numbers and underscore (_).
return will be used as the value of the property.
If you need special characters, such as space, ☺, or user-provided content, this is possible using [] bracket notation.
set is a function which serves as a setter for the property, or undefined if there is no setter. The function will
receive as only argument the new value being assigned to the property.
myObject['special property ☺'] = 'it works!'
[Link](myObject['special property ☺'])
value:
All-digit properties:
This key defaults to undefined.
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc). In addition to special characters, property names that are all-digits will require bracket notation. However, in this
case the property need not be written as a string.
Example:

[Link] – JavaScript® Notes for Professionals 125 [Link] – JavaScript® Notes for Professionals 126
myObject[123] = 'hi!' // number 123 is automatically converted to a string regardless.
[Link](myObject['123']) // notice how using string 123 produced the same result
[Link](myObject['12' + '3']) // string concatenation const obj = {
[Link](myObject[120 + 3]) // arithmetic, still resulting in 123 and producing the same result one: 1,
[Link](myObject[123.0]) // this works too because 123.0 evaluates to 123 two: 2,
[Link](myObject['123.0']) // this does NOT work, because '123' != '123.0' three: 3
};
However, leading zeros are not recommended as that is interpreted as Octal notation. (TODO, we should produce
[Link](obj);
and link to an example describing octal, hexadecimal and exponent notation)

See also: [Arrays are Objects] example. Results in:

Section 13.21: Creating an Iterable object [


["one", 1],
["two", 2],
Version ≥ 6
["three", 3]
var myIterableObject = {}; ]
// An Iterable object must define a method located at the [Link] key:
myIterableObject[[Link]] = function () {
// The iterator should return an Iterator object It is an useful way of iterating over the key/value pairs of an object:
return {
// The Iterator object must implement a method, next() for(const [key, value] of [Link](obj)) {
next: function () { [Link](key); // "one", "two" and "three"
// next must itself return an IteratorResult object [Link](value); // 1, 2 and 3
if (![Link]) { }
[Link] = true;
// The IteratorResult object has two properties
return { Section 13.23: [Link]()
// whether the iteration is complete, and
done: false, Version ≥ 8

// the value of the current iteration


value: 'One' The [Link]() method returns an array of a given object's own enumerable property values, in the same
}; order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the
} prototype chain as well).
return {
// When iteration is complete, just the done property is needed
var obj = { 0: 'a', 1: 'b', 2: 'c' };
done: true
[Link]([Link](obj)); // ['a', 'b', 'c']
};
},
iterated: false Note:
};
}; For browser support, please refer to this link

for (var c of myIterableObject) {


[Link](c);
}

Console output

One

Section 13.22: Iterating over Object entries - [Link]()


Version ≥ 8

The proposed [Link]() method returns an array of key/value pairs for the given object. It does not return
an iterator like [Link](), but the Array returned by [Link]() can be iterated

[Link] – JavaScript® Notes for Professionals 127 [Link] – JavaScript® Notes for Professionals 128
Chapter 14: Arithmetic (Math) x % 2 != 0 // true if x is odd number

Since 0 === -0, this also works for x <= -0.


Section 14.1: Constants
2. Implement cyclic increment/decrement of value within [0, n) interval.
Constants Description Approximate
Math.E Base of natural logarithm e 2.718
Suppose that we need to increment integer value from 0 to (but not including) n, so the next value after n-1 become
Math.LN10 Natural logarithm of 10 2.302
0. This can be done by such pseudocode:
Math.LN2 Natural logarithm of 2 0.693
Math.LOG10E Base 10 logarithm of e 0.434 var n = ...; // given n
Math.LOG2E Base 2 logarithm of e 1.442 var i = 0;
function inc() {
Pi: the ratio of circle circumference to
[Link] 3.14 i = (i + 1) % n;
diameter (π)
}
Math.SQRT1_2 Square root of 1/2 0.707 while (true) {
Math.SQRT2 Square root of 2 1.414 inc();
// update something with i
Difference between one and the smallest
}
[Link] value greater than one representable as 2.2204460492503130808472633361816E-16
a Number
Largest integer n such that n and n + 1 Now generalize the above problem and suppose that we need to allow to both increment and decrement that value
Number.MAX_SAFE_INTEGER are both exactly representable as a 2^53 - 1 from 0 to (not including) n, so the next value after n-1 become 0 and the previous value before 0 become n-1.
Number
Number.MAX_VALUE Largest positive finite value of Number 1.79E+308 var n = ...; // given n
var i = 0;
Smallest integer n such that n and n - 1
function delta(d) { // d - any signed integer
Number.MIN_SAFE_INTEGER are both exactly representable as a -(2^53 - 1)
i = (i + d + n) % n; // we add n to (i+d) to ensure the sum is positive
Number
}
Number.MIN_VALUE Smallest positive value for Number 5E-324
Number.NEGATIVE_INFINITY Value of negative infinity (-∞) Now we can call delta() function passing any integer, both positive and negative, as delta parameter.
Number.POSITIVE_INFINITY Value of positive infinity (∞)
Infinity Value of positive infinity (∞)
Using modulus to obtain the fractional part of a number

Section 14.2: Remainder / Modulus (%) var myNum = 10 / 4; // 2.5


var fraction = myNum % 1; // 0.5
myNum = -20 / 7; // -2.857142857142857
The remainder / modulus operator (%) returns the remainder after (integer) division. fraction = myNum % 1; // -0.857142857142857

[Link]( 42 % 10); // 2
[Link]( 42 % -10); // 2 Section 14.3: Rounding
[Link](-42 % 10); // -2
[Link](-42 % -10); // -2 Rounding
[Link](-40 % 10); // -0
[Link]( 40 % 10); // 0 [Link]() will round the value to the closest integer using half round up to break ties.

This operator returns the remainder left over when one operand is divided by a second operand. When the first var a = [Link](2.3); // a is now 2
operand is a negative value, the return value will always be negative, and vice versa for positive values. var b = [Link](2.7); // b is now 3
var c = [Link](2.5); // c is now 3
In the example above, 10 can be subtracted four times from 42 before there is not enough left to subtract again
without it changing sign. The remainder is thus: 42 - 4 * 10 = 2. But

The remainder operator may be useful for the following problems: var c = [Link](-2.7); // c is now -3
var c = [Link](-2.5); // c is now -2
1. Test if an integer is (not) divisible by another number:
Note how -2.5 is rounded to -2. This is because half-way values are always rounded up, that is they're rounded to
x % 4 == 0 // true if x is divisible by 4 the integer with the next higher value.
x % 2 == 0 // true if x is even number

[Link] – JavaScript® Notes for Professionals 129 [Link] – JavaScript® Notes for Professionals 130
Rounding up var b = [Link] (myNum * multiplier) / multiplier; // 3400
var c = [Link](myNum * multiplier) / multiplier; // 3300
[Link]() will round the value up.
As a more usable function:
var a = [Link](2.3); // a is now 3
var b = [Link](2.7); // b is now 3 // value is the value to round
// places if positive the number of decimal places to round to
ceiling a negative number will round towards zero // places if negative the number of digits to round to
function roundTo(value, places){
var power = [Link](10, places);
var c = [Link](-1.1); // c is now 1
return [Link](value * power) / power;
}
Rounding down var myNum = 10000/3; // 3333.3333333333335
roundTo(myNum, 2); // 3333.33
roundTo(myNum, 0); // 3333
[Link]() will round the value down.
roundTo(myNum, -2); // 3300

var a = [Link](2.3); // a is now 2


var b = [Link](2.7); // b is now 2 And the variants for ceil and floor:

function ceilTo(value, places){


flooring a negative number will round it away from zero.
var power = [Link](10, places);
return [Link](value * power) / power;
var c = [Link](-1.1); // c is now -1 }
function floorTo(value, places){
var power = [Link](10, places);
Truncating
return [Link](value * power) / power;
}
Caveat: using bitwise operators (except >>>) only applies to numbers between -2147483649 and 2147483648.

2.3 | 0; // 2 (floor) Section 14.4: Trigonometry


-2.3 | 0; // -2 (ceil)
NaN | 0; // 0 All angles below are in radians. An angle r in radians has measure 180 * r / [Link] in degrees.
Version ≥ 6
Sine
[Link]()
[Link](r);

[Link](2.3); // 2 (floor)
[Link](-2.3); // -2 (ceil) This will return the sine of r, a value between -1 and 1.
[Link](2147483648.1); // 2147483648 (floor)
[Link](-2147483649.1); // -2147483649 (ceil) [Link](r);
[Link](NaN); // NaN
This will return the arcsine (the reverse of the sine) of r.
Rounding to decimal places
[Link](r)
[Link], [Link](), and [Link]() can be used to round to a number of decimal places
This will return the hyperbolic arcsine of r.
To round to 2 decimal places:
Cosine
var myNum = 2/3; // 0.6666666666666666 [Link](r);
var multiplier = 100;
var a = [Link](myNum * multiplier) / multiplier; // 0.67
var b = [Link] (myNum * multiplier) / multiplier; // 0.67 This will return the cosine of r, a value between -1 and 1
var c = [Link](myNum * multiplier) / multiplier; // 0.66
[Link](r);

You can also round to a number of digits:


This will return the arccosine (the reverse of the cosine) of r.
var myNum = 10000/3; // 3333.3333333333335
var multiplier = 1/100; [Link](r);
var a = [Link](myNum * multiplier) / multiplier; // 3300

[Link] – JavaScript® Notes for Professionals 131 [Link] – JavaScript® Notes for Professionals 132
This will return the hyperbolic arccosine of r. Shift left is equivalent to integer multiply by [Link](2, n). When doing integer math, shift can significantly
improve the speed of some math operations.
Tangent
[Link](r); var n = 2;
var a = 5.4;
var result = (a << n) === [Link](a) * [Link](2,n);
This will return the tangent of r.
// result is true
a = 5.4 << n; // 20
[Link](r);
Bitwise right shift >> (Sign-propagating shift) >>> (Zero-fill right shift)
This will return the arctangent (the reverse of the tangent) of r. Note that it will return an angle in radians between a = 0b1001 >> 1; // a === 0b0100
a = 0b1001 >> 2; // a === 0b0010
-π/2 and π/2.
a = 0b1001 >> 3; // a === 0b0001

[Link](r); a = 0b1001 >>> 1; // a === 0b0100


a = 0b1001 >>> 2; // a === 0b0010
This will return the hyperbolic arctangent of r. a = 0b1001 >>> 3; // a === 0b0001

Math.atan2(x, y); A negative 32bit value always has the left most bit on:

This will return the value of an angle from (0, 0) to (x, y) in radians. It will return a value between -π and π, not a = 0b11111111111111111111111111110111 | 0;
including π. [Link](a); // -9
b = a >> 2; // leftmost bit is shifted 1 to the right then new left most bit is set to on (1)
[Link](b); // -3
Section 14.5: Bitwise operators b = a >>> 2; // leftmost bit is shifted 1 to the right. the new left most bit is set to off (0)
[Link](b); // 2147483643
Note that all bitwise operations operate on 32-bit integers by passing any operands to the internal function ToInt32.
The result of a >>> operation is always positive.
Bitwise or
The result of a >> is always the same sign as the shifted value.
var a;
a = 0b0011 | 0b1010; // a === 0b1011 Right shift on positive numbers is the equivalent of dividing by the [Link](2,n) and flooring the result:
// truth table
// 1010 | (or)
a = 256.67;
// 0011
n = 4;
// 1011 (result)
result = (a >> n) === [Link]( [Link](a) / [Link](2,n) );
Bitwise and // result is true
a = a >> n; // 16
a = 0b0011 & 0b1010; // a === 0b0010
// truth table
result = (a >>> n) === [Link]( [Link](a) / [Link](2,n) );
// 1010 & (and)
// result is true
// 0011
a = a >>> n; // 16
// 0010 (result)

Bitwise not
Right shift zero fill (>>>) on negative numbers is different. As JavaScript does not convert to unsigned ints when
a = ~0b0011; // a === 0b1100 doing bit operations there is no operational equivalent:
// truth table
// 10 ~(not)
a = -256.67;
// 01 (result)
result = (a >>> n) === [Link]( [Link](a) / [Link](2,n) );
Bitwise xor (exclusive or) // result is false
a = 0b1010 ^ 0b0011; // a === 0b1001 Bitwise assignment operators
// truth table
// 1010 ^ (xor) With the exception of not (~) all the above bitwise operators can be used as assignment operators:
// 0011
// 1001 (result)
a |= b; // same as: a = a | b;
Bitwise left shift a ^= b; // same as: a = a ^ b;
a = 0b0001 << 1; // a === 0b0010 a &= b; // same as: a = a & b;
a = 0b0001 << 2; // a === 0b0100 a >>= b; // same as: a = a >> b;
a = 0b0001 << 3; // a === 0b1000 a >>>= b; // same as: a = a >>> b;
a <<= b; // same as: a = a << b;

[Link] – JavaScript® Notes for Professionals 133 [Link] – JavaScript® Notes for Professionals 134
Warning: JavaScript uses Big Endian to store integers. This will not always match the Endian of the device/OS. When c = a ** b;
using typed arrays with bit lengths greater than 8 bits you should check if the environment is Little Endian or Big
Endian before applying bitwise operations. c will now be 8

Warning: Bitwise operators such as & and | are not the same as the logical operators && (and) and || (or). They will
provide incorrect results if used as logical operators. The ^ operator is not the power operator (ab). Use [Link] to find the nth root of a number.

Finding the nth roots is the inverse of raising to the nth power. For example 2 to the power of 5 is 32. The 5th root
Section 14.6: Incrementing (++) of 32 is 2.

The Increment operator (++) increments its operand by one.


[Link](v, 1 / n); // where v is any positive real number
// and n is any positive integer
If used as a postfix, then it returns the value before incrementing.
If used as a prefix, then it returns the value after incrementing. var a = 16;
var b = [Link](a, 1 / 2); // return the square root of 16 = 4
var c = [Link](a, 1 / 3); // return the cubed root of 16 = 2.5198420997897464
//postfix var d = [Link](a, 1 / 4); // return the 4th root of 16 = 2
var a = 5, // 5
b = a++, // 5
c = a // 6 Section 14.8: Random Integers and Floats
In this case, a is incremented after setting b. So, b will be 5, and c will be 6. var a = [Link]();

Sample value of a: 0.21322848065742162


//prefix
var a = 5, // 5 [Link]() returns a random number between 0 (inclusive) and 1 (exclusive)
b = ++a, // 6
c = a // 6 function getRandom() {
return [Link]();
}
In this case, a is incremented before setting b. So, b will be 6, and c will be 6.

The increment and decrement operators are commonly used in for loops, for example: To use [Link]() to get a number from an arbitrary range (not [0,1)) use this function to get a random
number between min (inclusive) and max (exclusive): interval of [min, max)
for(var i = 0; i < 42; ++i)
{ function getRandomArbitrary(min, max) {
// do something awesome! return [Link]() * (max - min) + min;
} }

Notice how the prefix variant is used. This ensures that a temporarily variable isn't needlessly created (to return the To use [Link]() to get an integer from an arbitrary range (not [0,1)) use this function to get a random
value prior to the operation). number between min (inclusive) and max (exclusive): interval of [min, max)

Section 14.7: Exponentiation ([Link]() or **) function getRandomInt(min, max) {


return [Link]([Link]() * (max - min)) + min;
}
Exponentiation makes the second operand the power of the first operand (ab).

var a = 2, To use [Link]() to get an integer from an arbitrary range (not [0,1)) use this function to get a random
b = 3, number between min (inclusive) and max (inclusive): interval of [min, max]
c = [Link](a, b);
function getRandomIntInclusive(min, max) {
c will now be 8 return [Link]([Link]() * (max - min + 1)) + min;
}
Version > 6

Functions taken from


Stage 3 ES2016 (ECMAScript 7) Proposal:
[Link]

let a = 2,
b = 3,

[Link] – JavaScript® Notes for Professionals 135 [Link] – JavaScript® Notes for Professionals 136
Section 14.9: Addition (+) var data = new Uint32Array(buf);
data[0] = 0x0F000000;
if(buf8[0] === 0x0f){
The addition operator (+) adds numbers.
isLittleEndian = false;
}
})();
var a = 9,
b = 3, Little-Endian stores most significant bytes from right to left.
c = a + b;
Big-Endian stores most significant bytes from left to right.
c will now be 12
var myNum = 0x11223344 | 0; // 32 bit signed integer
This operand can also be used multiple times in a single assignment: var buf = new ArrayBuffer(4);
var data8 = new Uint8ClampedArray(buf);
var a = 9, var data32 = new Uint32Array(buf);
b = 3, data32[0] = myNum; // store number in 32Bit array
c = 8,
d = a + b + c; If the system uses Little-Endian, then the 8bit byte values will be

d will now be 20. [Link](data8[0].toString(16)); // 0x44


[Link](data8[1].toString(16)); // 0x33
Both operands are converted to primitive types. Then, if either one is a string, they're both converted to strings and [Link](data8[2].toString(16)); // 0x22
concatenated. Otherwise, they're both converted to numbers and added. [Link](data8[3].toString(16)); // 0x11

null + null; // 0 If the system uses Big-Endian, then the 8bit byte values will be
null + undefined; // NaN
null + {}; // "null[object Object]" [Link](data8[0].toString(16)); // 0x11
null + ''; // "null" [Link](data8[1].toString(16)); // 0x22
[Link](data8[2].toString(16)); // 0x33
If the operands are a string and a number, the number is converted to a string and then they're concatenated, [Link](data8[3].toString(16)); // 0x44
which may lead to unexpected results when working with strings that look numeric.
Example where Endian type is important
"123" + 1; // "1231" (not 124)
var canvas = [Link]("canvas");
var ctx = [Link]("2d");
If a boolean value is given in place of any of the number values, the boolean value is converted to a number (0 for
var imgData = [Link](0, 0, [Link], [Link]);
false, 1 for true) before the sum is calculated:
// To speed up read and write from the image buffer you can create a buffer view that is
// 32 bits allowing you to read/write a pixel in a single operation
true + 1; // 2 var buf32 = new Uint32Array([Link]);
false + 5; // 5 // Mask out Red and Blue channels
null + 1; // 1 var mask = 0x00FF00FF; // bigEndian pixel channels Red,Green,Blue,Alpha
undefined + 1; // NaN if(isLittleEndian){
mask = 0xFF00FF00; // littleEndian pixel channels Alpha,Blue,Green,Red
If a boolean value is given alongside a string value, the boolean value is converted to a string instead: }
var len = [Link];
var i = 0;
true + "1"; // "true1"
while(i < len){ // Mask all pixels
false + "bar"; // "falsebar"
buf32[i] &= mask; //Mask out Red and Blue
}
Section 14.10: Little / Big endian for typed arrays when using [Link](imgData);

bitwise operators
Section 14.11: Get Random Between Two Numbers
To detect the endian of the device
Returns a random integer between min and max:
var isLittleEndian = true;
(()=>{ function randomBetween(min, max) {
var buf = new ArrayBuffer(4); return [Link]([Link]() * (max - min + 1) + min);
var buf8 = new Uint8ClampedArray(buf); }

[Link] – JavaScript® Notes for Professionals 137 [Link] – JavaScript® Notes for Professionals 138
Examples: As you probably noticed, these functions return an index, so you could have more descriptive outcomes stored in
an array. Here's an example.
// randomBetween(0, 10);
[Link]([Link]() * 11); var rewards = ["gold coin","silver coin","diamond","god sword"];
var likelihoods = [5,9,1,0];
// randomBetween(1, 10); // least likely to get a god sword (0/15 = 0%, never),
[Link]([Link]() * 10) + 1; // most likely to get a silver coin (9/15 = 60%, more than half the time)

// randomBetween(5, 20); // simulate event, log reward


[Link]([Link]() * 16) + 5; [Link]("You get a "+rewards[simulateEvent(likelihoods)]); // You get a silver coin

// randomBetween(-10, -2);
[Link]([Link]() * 9) - 10; Section 14.13: Subtraction (-)
The subtraction operator (-) subtracts numbers.
Section 14.12: Simulating events with dierent probabilities
Sometimes you may only need to simulate an event with two outcomes, maybe with different probabilities, but you
var a = 9;
may find yourself in a situation that calls for many possible outcomes with different probabilities. Let's imagine you
var b = 3;
want to simulate an event that has six equally probable outcomes. This is quite simple. var c = a - b;

function simulateEvent(numEvents) {
c will now be 6
var event = [Link](numEvents*[Link]());
return event;
If a string or boolean is provided in place of a number value, it gets converted to a number before the difference is
}
calculated (0 for false, 1 for true):
// simulate fair die
[Link]("Rolled a "+(simulateEvent(6)+1)); // Rolled a 2 "5" - 1; // 4
7 - "3"; // 4
"5" - true; // 4
However, you may not want equally probable outcomes. Say you had a list of three outcomes represented as an
array of probabilities in percents or multiples of likelihood. Such an example might be a weighted die. You could
If the string value cannot be converted into a Number, the result will be NaN:
rewrite the previous function to simulate such an event.

"foo" - 1; // NaN
function simulateEvent(chances) {
100 - "bar"; // NaN
var sum = 0;
[Link](function(chance) {

});
sum+=chance;
Section 14.14: Multiplication (*)
var rand = [Link]();
The multiplication operator (*) perform arithmetic multiplication on numbers (literals or variables).
var chance = 0;
for(var i=0; i<[Link]; i++) {
chance+=chances[i]/sum; [Link]( 3 * 5); // 15
if(rand<chance) { [Link](-3 * 5); // -15
return i; [Link]( 3 * -5); // -15
} [Link](-3 * -5); // 15
}

// should never be reached unless sum of probabilities is less than 1 Section 14.15: Getting maximum and minimum
// due to all being zero or some being negative probabilities
return -1; The [Link]() function returns the largest of zero or more numbers.
}
[Link](4, 12); // 12
// simulate weighted dice where 6 is twice as likely as any other face [Link](-1, -15); // -1
// using multiples of likelihood
[Link]("Rolled a "+(simulateEvent([1,1,1,1,1,2])+1)); // Rolled a 1
The [Link]() function returns the smallest of zero or more numbers.
// using probabilities
[Link]("Rolled a "+(simulateEvent([1/7,1/7,1/7,1/7,1/7,2/7])+1)); // Rolled a 6 [Link](4, 12); // 4
[Link](-1, -15); // -15

[Link] – JavaScript® Notes for Professionals 139 [Link] – JavaScript® Notes for Professionals 140
Getting maximum and minimum from an array: [Link](n);
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9],
max = [Link](Math, arr), Example:
min = [Link](Math, arr);
[Link]([Link](0.60)); // 0
[Link](max); // Logs: 9
[Link]([Link](0.40)); // 0
[Link](min); // Logs: 1
[Link]([Link](5.1)); // 5
[Link]([Link](-5.1)); // -6
ECMAScript 6 spread operator, getting the maximum and minimum of an array: [Link]([Link](-5.9)); // -6

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9],


max = [Link](...arr),
Section 14.18: Getting roots of a number
min = [Link](...arr);
Square Root
[Link](max); // Logs: 9
[Link](min); // Logs: 1 Use [Link]() to find the square root of a number

Section 14.16: Restrict Number to Min/Max Range [Link](16) #=> 4

If you need to clamp a number to keep it inside a specific range boundary Cube Root

function clamp(min, max, val) { To find the cube root of a number, use the [Link]() function
return [Link]([Link](min, +val), max);
} Version ≥ 6
[Link](27) #=> 3
[Link](clamp(-10, 10, "4.30")); // 4.3
Finding nth-roots
[Link](clamp(-10, 10, -8)); // -8
[Link](clamp(-10, 10, 12)); // 10
To find the nth-root, use the [Link]() function and pass in a fractional exponent.
[Link](clamp(-10, 10, -15)); // -10

[Link](64, 1/6) #=> 2


Use-case example (jsFiddle)

Section 14.17: Ceiling and Floor Section 14.19: Random with gaussian distribution
ceil() The [Link]() function should give random numbers that have a standard deviation approaching 0. When
picking from a deck of card, or simulating a dice roll this is what we want.
The ceil() method rounds a number upwards to the nearest integer, and returns the result.
But in most situations this is unrealistic. In the real world the randomness tends to gather around an common
Syntax: normal value. If plotted on a graph you get the classical bell curve or gaussian distribution.

[Link](n); To do this with the [Link]() function is relatively simple.

Example: var randNum = ([Link]() + [Link]()) / 2;


var randNum = ([Link]() + [Link]() + [Link]()) / 3;
[Link]([Link](0.60)); // 1 var randNum = ([Link]() + [Link]() + [Link]() + [Link]()) / 4;
[Link]([Link](0.40)); // 1
[Link]([Link](5.1)); // 6 Adding a random value to the last increases the variance of the random numbers. Dividing by the number of times
[Link]([Link](-5.1)); // -5 you add normalises the result to a range of 0–1
[Link]([Link](-5.9)); // -5
As adding more than a few randoms is messy a simple function will allow you to select a variance you want.
floor()

// v is the number of times random is summed and should be over >= 1


The floor() method rounds a number downwards to the nearest integer, and returns the result. // return a random number between 0-1 exclusive
function randomG(v){
Syntax: var r = 0;
for(var i = v; i > 0; i --){
r += [Link]();

[Link] – JavaScript® Notes for Professionals 141 [Link] – JavaScript® Notes for Professionals 142
} vec.y = [Link](dir) * dist; // get the y component
return r / v;
}
You can also ignore the distance to create a normalised (1 unit long) vector in the direction of dir

var dir = 1.4536; // direction in radians


var vec = {};
vec.x = [Link](dir); // get the x component
vec.y = [Link](dir); // get the y component

If your coordinate system has y as up then you need to switch cos and sin. In this case a positive direction is in a
counterclockwise direction from the x axis.

The image shows the distribution of random values for different values of v. The top left is standard single // get the directional vector where y points up
var dir = 1.4536; // direction in radians
[Link]() call the bottom right is [Link]() summed 8 times. This is from 5,000,000 samples using
var vec = {};
Chrome vec.x = [Link](dir); // get the x component
vec.y = [Link](dir); // get the y component
This method is most efficient at v<5

Section 14.20: Math.atan2 to find direction Section 14.22: [Link]


To find the distance between two points we use pythagoras to get the square root of the sum of the square of the
If you are working with vectors or lines you will at some stage want to get the direction of a vector, or line. Or the
component of the vector between them.
direction from a point to another point.
var v1 = {x : 10, y :5};
[Link](yComponent, xComponent) return the angle in radius within the range of -[Link] to [Link] (-180 to
var v2 = {x : 20, y : 10};
180 deg) var x = v2.x - v1.x;
var y = v2.y - v1.y;
Direction of a vector var distance = [Link](x * x + y * y); // 11.180339887498949
var vec = {x : 4, y : 3};
var dir = Math.atan2(vec.y, vec.x); // 0.6435011087932844 With ECMAScript 6 came [Link] which does the same thing
Direction of a line
var v1 = {x : 10, y :5};
var line = {
var v2 = {x : 20, y : 10};
p1 : { x : 100, y : 128},
var x = v2.x - v1.x;
p2 : { x : 320, y : 256}
var y = v2.y - v1.y;
}
var distance = [Link](x,y); // 11.180339887498949
// get the direction from p1 to p2
var dir = Math.atan2(line.p2.y - line.p1.y, line.p2.x - line.p1.x); // 0.5269432271894297
Now you don't have to hold the interim vars to stop the code becoming a mess of variables
Direction from a point to another point
var point1 = { x: 123, y : 294}; var v1 = {x : 10, y :5};
var point2 = { x: 354, y : 284}; var v2 = {x : 20, y : 10};
// get the direction from point1 to point2 var distance = [Link](v2.x - v1.x, v2.y - v1.y); // 11.180339887498949
var dir = Math.atan2(point2.y - point1.y, point2.x - point1.x); // -0.04326303140726714

[Link] can take any number of dimensions


Section 14.21: Sin & Cos to create a vector given direction &
distance // find distance in 3D
var v1 = {x : 10, y : 5, z : 7};
var v2 = {x : 20, y : 10, z : 16};
If you have a vector in polar form (direction & distance) you will want to convert it to a cartesian vector with a x and
var dist = [Link](v2.x - v1.x, v2.y - v1.y, v2.z - v1.z); // 14.352700094407325
y component. For reference the screen coordinate system has directions as 0 deg points from left to right, 90 (PI/2)
point down the screen, and so on in a clock wise direction. // find length of 11th dimensional vector
var v = [1,3,2,6,1,7,3,7,5,3,1];
var dir = 1.4536; // direction in radians var i = 0;
var dist = 200; // distance dist = [Link](v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++]);
var vec = {};
vec.x = [Link](dir) * dist; // get the x component

[Link] – JavaScript® Notes for Professionals 143 [Link] – JavaScript® Notes for Professionals 144
Section 14.23: Periodic functions using [Link] t += phase * [Link] * 2; // add the phase offset
var v = [Link](t); // get the value at the calculated position in the cycle
v *= amplitude; // set the amplitude
[Link] and [Link] are cyclic with a period of 2*PI radians (360 deg) they output a wave with an amplitude of 2
v += offset; // add the offset
in the range -1 to 1. return v;
}
Graph of sine and cosine function: (courtesy Wikipedia)
Or in a more compact (and slightly quicker form):

function oscillator(time, frequency = 1, amplitude = 1, phase = 0, offset = 0){


return [Link](time * frequency * [Link] * 2 + phase * [Link] * 2) * amplitude + offset;
}

All the arguments apart from time are optional

Section 14.24: Division (/)


The division operator (/) perform arithmetic division on numbers (literals or variables).

[Link](15 / 3); // 5
[Link](15 / 4); // 3.75

Section 14.25: Decrementing (--)


The decrement operator (--) decrements numbers by one.

If used as a postfix to n, the operator returns the current n and then assigns the decremented the value.
If used as a prefix to n, the operator assigns the decremented n and then returns the changed value.
They are both very handy for many types of periodic calculations, from creating sound waves, to animations, and
even encoding and decoding image data var a = 5, // 5
b = a--, // 5
This example shows how to create a simple sin wave with control over period/frequency, phase, amplitude, and c = a // 4

offset.
In this case, b is set to the initial value of a. So, b will be 5, and c will be 4.
The unit of time being used is seconds.
The most simple form with control over frequency only. var a = 5, // 5
b = --a, // 4
c = a // 4
// time is the time in seconds when you want to get a sample
// Frequency represents the number of oscillations per second
function oscillator(time, frequency){ In this case, b is set to the new value of a. So, b will be 4, and c will be 4.
return [Link](time * 2 * [Link] * frequency);
} Common Uses

In almost all cases you will want to make some changes to the value returned. The common terms for modifications The decrement and increment operators are commonly used in for loops, for example:

Phase: The offset in terms of frequency from the start of the oscillations. It is a value in the range of 0 to 1 for (var i = 42; i > 0; --i) {
where the value 0.5 move the wave forward in time by half its frequency. A value of 0 or 1 makes no change. [Link](i)
}
Amplitude: The distance from the lowest value and highest value during one cycle. An amplitude of 1 has a
range of 2. The lowest point (trough) -1 to the highest (peak) 1. For a wave with frequency 1 the peak is at
Notice how the prefix variant is used. This ensures that a temporarily variable isn't needlessly created (to return the
0.25 seconds, and trough at 0.75.
value prior to the operation).
Offset: moves the whole wave up or down.

To include all these in the function: Note: Neither -- nor ++ are like normal mathematical operators, but rather they are very concise
operators for assignment. Notwithstanding the return value, both
function oscillator(time, frequency = 1, amplitude = 1, phase = 0, offset = 0){
var t = time * frequency * [Link] * 2; // get phase at time

[Link] – JavaScript® Notes for Professionals 145 [Link] – JavaScript® Notes for Professionals 146
x--

and
Chapter 15: Bitwise operators
--x Section 15.1: Bitwise operators
reassign to x such that x = x - 1. Bitwise operators perform operations on bit values of data. These operators convert operands to signed 32-bit
integers in two's complement.
const x = 1;
[Link](x--) // TypeError: Assignment to constant variable.
Conversion to 32-bit integers
[Link](--x) // TypeError: Assignment to constant variable.
[Link](--3) // ReferenceError: Invalid left-hand size expression in prefix operation.
Numbers with more than 32 bits discard their most significant bits. For example, the following integer with more
[Link](3--) // ReferenceError: Invalid left-hand side expression in postfix operation.
than 32 bits is converted to a 32-bit integer:

Before: 10100110111110100000000010000011110001000001
After: 10100000000010000011110001000001

Two's Complement

In normal binary we find the binary value by adding the 1's based on their position as powers of 2 - The rightmost
bit being 2^0 to the leftmost bit being 2^n-1 where n is the number of bits. For example, using 4 bits:

// Normal Binary
// 8 4 2 1
0 1 1 0 => 0 + 4 + 2 + 0 => 6

Two complement's format means that the number's negative counterpart (6 vs -6) is all the bits for a number
inverted, plus one. The inverted bits of 6 would be:

// Normal binary
0 1 1 0
// One's complement (all bits inverted)
1 0 0 1 => -8 + 0 + 0 + 1 => -7
// Two's complement (add 1 to one's complement)
1 0 1 0 => -8 + 0 + 2 + 0 => -6

Note: Adding more 1's to the left of a binary number does not change its value in two's compliment. The value 1010
and 1111111111010 are both -6.

Bitwise AND

The bitwise AND operation a & b returns the binary value with a 1 where both binary operands have 1's in a
specific position, and 0 in all other positions. For example:

13 & 7 => 5
// 13: 0..01101
// 7: 0..00111
//-----------------
// 5: 0..00101 (0 + 0 + 4 + 0 + 1)

Real world example: Number's Parity Check

Instead of this "masterpiece" (unfortunately too often seen in many real code parts):

function isEven(n) {
return n % 2 == 0;
}

[Link] – JavaScript® Notes for Professionals 147 [Link] – JavaScript® Notes for Professionals 148
function isOdd(n) {
if (isEven(n)) {
Section 15.2: Shift Operators
return false;
Bitwise shifting can be thought as "moving" the bits either left or right, and hence changing the value of the data
} else {
return true; operated on.
}
} Left Shift

You can check the (integer) number's parity in much more effective and simple manner: The left shift operator (value) << (shift amount) will shift the bits to the left by (shift amount) bits; the new
bits coming in from the right will be 0's:
if(n & 1) {
[Link]("ODD!"); 5 << 2 => 20
} else { // 5: 0..000101
[Link]("EVEN!"); // 20: 0..010100 <= adds two 0's to the right
}

Right Shift (Sign-propagating)


Bitwise OR
The right shift operator (value) >> (shift amount) is also known as the "Sign-propagating right shift" because it
The bitwise OR operation a | b returns the binary value with a 1 where either operands or both operands have 1's keeps the sign of the initial operand. The right shift operator shifts the value the specified shift amount of bits to
in a specific position, and 0 when both values have 0 in a position. For example: the right. Excess bits shifted off the right are discarded. The new bits coming in from the left will be based on the
sign of the initial operand. If the left-most bit was 1 then the new bits will all be 1 and vice-versa for 0's.
13 | 7 => 15
// 13: 0..01101
20 >> 2 => 5
// 7: 0..00111
// 20: 0..010100
//-----------------
// 5: 0..000101 <= added two 0's from the left and chopped off 00 from the right
// 15: 0..01111 (0 + 8 + 4 + 2 + 1)
-5 >> 3 => -1
Bitwise NOT // -5: 1..111011
// -2: 1..111111 <= added three 1's from the left and chopped off 011 from the right

The bitwise NOT operation ~a flips the bits of the given value a. This means all the 1's will become 0's and all the 0's
will become 1's. Right Shift (Zero fill)

The zero-fill right shift operator (value) >>> (shift amount) will move the bits to the right, and the new bits will
~13 => -14
be 0's. The 0's are shifted in from the left, and excess bits to the right are shifted off and discarded. This means it
// 13: 0..01101
//----------------- can make negative numbers into positive ones.
//-14: 1..10010 (-16 + 0 + 0 + 2 + 0)
-30 >>> 2 => 1073741816
// -30: 111..1100010
Bitwise XOR //1073741816: 001..1111000

The bitwise XOR (exclusive or) operation a ^ b places a 1 only if the two bits are different. Exclusive or means either Zero-fill right shift and sign-propagating right shift yield the same result for non negative numbers.
one or the other, but not both.

13 ^ 7 => 10
// 13: 0..01101
// 7: 0..00111
//-----------------
// 10: 0..01010 (0 + 8 + 0 + 2 + 0)

Real world example: swapping two integer values without additional memory allocation

var a = 11, b = 22;


a = a ^ b;
b = a ^ b;
a = a ^ b;
[Link]("a = " + a + "; b = " + b);// a is now 22 and b is now 11

[Link] – JavaScript® Notes for Professionals 149 [Link] – JavaScript® Notes for Professionals 150
Chapter 16: Constructor functions Chapter 17: Declarations and Assignments
Section 16.1: Declaring a constructor function Section 17.1: Modifying constants
Constructor functions are functions designed to construct a new object. Within a constructor function, the keyword Declaring a variable const only prevents its value from being replaced by a new value. const does not put any
this refers to a newly created object which values can be assigned to. Constructor functions "return" this new restrictions on the internal state of an object. The following example shows that a value of a property of a const
object automatically. object can be changed, and even new properties can be added, because the object that is assigned to person is
modified, but not replaced.
function Cat(name) {
[Link] = name; const person = {
[Link] = "Meow"; name: "John"
} };
[Link]('The name of the person is', [Link]);
Constructor functions are invoked using the new keyword:
[Link] = "Steve";
[Link]('The name of the person is', [Link]);
let cat = new Cat("Tom");
[Link]; // Returns "Meow"
[Link] = "Fox";
[Link]('The name of the person is', [Link], 'and the surname is', [Link]);
Constructor functions also have a prototype property which points to an object whose properties are automatically
inherited by all objects created with that constructor: Result:

[Link] = function() {
The name of the person is John
[Link]([Link]);
The name of the person is Steve
}
The name of the person is Steve and the surname is Fox

[Link](); // Outputs "Meow" to the console


In this example we've created constant object called person and we've reassigned [Link] property and
Objects created by constructor functions also have a special property on their prototype called constructor, which created new [Link] property.
points to the function used to create them:
Section 17.2: Declaring and initializing constants
[Link] // Returns the `Cat` function
You can initialize a constant by using the const keyword.
Objects created by constructor functions are also considered to be "instances" of the constructor function by the
const foo = 100;
instanceof operator:
const bar = false;
const person = { name: "John" };
cat instanceof Cat // Returns "true" const fun = function () = { /* ... */ };
const arrowFun = () => /* ... */ ;

Important
You must declare and initialize a constant in the same statement.

Section 17.3: Declaration


There are four principle ways to declare a variable in JavaScript: using the var, let or const keywords, or without a
keyword at all ("bare" declaration). The method used determines the resulting scope of the variable, or
reassignability in the case of const.

The var keyword creates a function-scope variable.


The let keyword creates a block-scope variable.
The const keyword creates a block-scope variable that cannot be reassigned.
A bare declaration creates a global variable.

var a = 'foo'; // Function-scope

[Link] – JavaScript® Notes for Professionals 151 [Link] – JavaScript® Notes for Professionals 152
let b = 'foo'; // Block-scope b += a;
const c = 'foo'; // Block-scope & immutable reference
b will now be 12
Keep in mind that you can't declare constants without initializing them at the same time.
This is functionally the same as
const foo; // "Uncaught SyntaxError: Missing initializer in const declaration"
b = b + a;
(An example of keyword-less variable declaration is not included above for technical reasons. Continue reading to
see an example.) Decrement by
var a = 9,
Section 17.4: Undefined b = 3;
b -= a;
Declared variable without a value will have the value undefined
b will now be 6
var a;
This is functionally the same as
[Link](a); // logs: undefined
b = b - a;
Trying to retrieve the value of undeclared variables results in a ReferenceError. However, both the type of
undeclared and unitialized variables is "undefined":
Multiply by
var a = 5,
var a;
b = 3;
[Link](typeof a === "undefined"); // logs: true
b *= a;
[Link](typeof variableDoesNotExist === "undefined"); // logs: true

b will now be 15
Section 17.5: Data Types
This is functionally the same as
JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:
b = b * a;
// Number
var length = 16;
Divide by
// String var a = 3,
var message = "Hello, World!"; b = 15;
b /= a;
// Array
var carNames = ['Chevrolet', 'Nissan', 'BMW'];
b will now be 5
// Object
var person = { This is functionally the same as
firstName: "John",
lastName: "Doe" b = b / a;
};
Version ≥ 7
JavaScript has dynamic types. This means that the same variable can be used as different types: Raised to the power of
var a = 3,
var a; // a is undefined b = 15;
var a = 5; // a is a Number b **= a;
var a = "John"; // a is a String

b will now be 3375


Section 17.6: Mathematic operations and assignment
This is functionally the same as
Increment by
var a = 9, b = b ** a;
b = 3;

[Link] – JavaScript® Notes for Professionals 153 [Link] – JavaScript® Notes for Professionals 154
Section 17.7: Assignment Chapter 18: Loops
To assign a value to a previously declared variable, use the assignment operator, =:
Section 18.1: Standard "for" loops
a = 6;
b = "Foo"; Standard usage
for (var i = 0; i < 100; i++) {
As an alternative to independent declaration and assignment, it is possible to perform both steps in one statement: [Link](i);
}
var a = 6;
let b = "Foo"; Expected output:

It is in this syntax that global variables may be declared without a keyword; if one were to declare a bare variable
0
without an assignment immediately afterword, the interpreter would not be able to differentiate global
declarations a; from references to variables a;. 1
...
c = 5; 99
c = "Now the value is a String.";
myNewGlobal; // ReferenceError
Multiple declarations
Note, however, that the above syntax is generally discouraged and is not strict-mode compliant. This is to avoid the
Commonly used to cache the length of an array.
scenario in which a programmer inadvertently drops a let or var keyword from their statement, accidentally
creating a variable in the global namespace without realizing it. This can pollute the global namespace and conflict
var array = ['a', 'b', 'c'];
with libraries and the proper functioning of a script. Therefore global variables should be declared and initialized for (var i = 0; i < [Link]; i++) {
using the var keyword in the context of the window object, instead, so that the intent is explicitly stated. [Link](array[i]);
}
Additionally, variables may be declared several at a time by separating each declaration (and optional value
assignment) with a comma. Using this syntax, the var and let keywords need only be used once at the beginning of Expected output:
each statement.

'a'
globalA = "1", globalB = "2";
let x, y = 5; 'b'
var person = 'John Doe', 'c'
foo,
age = 14,
date = new Date(); Changing the increment
for (var i = 0; i < 100; i += 2 /* Can also be: i = i + 2 */) {
Notice in the preceding code snippet that the order in which declaration and assignment expressions occur (var a, [Link](i);
b, c = 2, d;) does not matter. You may freely intermix the two. }

Function declaration effectively creates variables, as well. Expected output:

0
2
4
...
98

Decremented loop
for (var i = 100; i >=0; i--) {
[Link](i);
}

[Link] – JavaScript® Notes for Professionals 155 [Link] – JavaScript® Notes for Professionals 156
Expected output: const names = ['bob', 'alejandro', 'zandra', 'anna', 'bob'];

const uniqueNames = new Set(names);


100
99 for (let name of uniqueNames) {
98 [Link](name);
}
...
0
Expected output:

Section 18.2: "for ... of" loop bob


alejandro
Version ≥ 6
zandra
const iterable = [0, 1, 2];
for (let i of iterable) { anna
[Link](i);
}
Maps

Expected output:
You can also use for...of loops to iterate over Maps. This works similarly to arrays and sets, except the iteration
variable stores both a key and a value.
0
1 const map = new Map()
.set('abc', 1)
2
.set('def', 2)

for (const iteration of map) {


The advantages from the for...of loop are:
[Link](iteration) //will log ['abc', 1] and then ['def', 2]
}
This is the most concise, direct syntax yet for looping through array elements
It avoids all the pitfalls of for...in
You can use destructuring assignment to capture the key and the value separately:
Unlike forEach(), it works with break, continue, and return
const map = new Map()
Support of for...of in other collections
.set('abc', 1)
Strings .set('def', 2)

for...of will treat a string as a sequence of Unicode characters: for (const [key, value] of map) {
[Link](key + ' is mapped to ' + value)
const string = "abc"; }
for (let chr of string) { /*Logs:
[Link](chr); abc is mapped to 1
} def is mapped to 2
*/
Expected output:
Objects

abc for...of loops do not work directly on plain Objects; but, it is possible to iterate over an object’s properties by
switching to a for...in loop, or using [Link]():
Sets
const someObject = { name: 'Mike' };
for...of works on Set objects.
for (let key of [Link](someObject)) {
[Link](key + ": " + someObject[key]);
Note:
}

A Set object will eliminate duplicates.


Expected output:
Please check this reference for Set() browser support.

[Link] – JavaScript® Notes for Professionals 157 [Link] – JavaScript® Notes for Professionals 158
name: Mike [Link](i);
i--; /* equivalent to i=i-1 */
}

Section 18.3: "for ... in" loop Expected output:

Warning 100
for...in is intended for iterating over object keys, not array indexes. Using it to loop through an array is 99
generally discouraged. It also includes properties from the prototype, so it may be necessary to check if 98
the key is within the object using hasOwnProperty. If any attributes in the object are defined by the ...
defineProperty/defineProperties method and set the param enumerable: false, those attributes will 1
be inaccessible.
Do...while Loop
var object = {"a":"foo", "b":"bar", "c":"baz"};
A do...while loop will always execute at least once, regardless of whether the condition is true or false:
// `a` is inaccessible
[Link](object , 'a', {
enumerable: false, var i = 101;
}); do {
for (var key in object) { [Link](i);
if ([Link](key)) { } while (i < 100);
[Link]('object.' + key + ', ' + object[key]);
} Expected output:
}

Expected output: 101

object.b, bar Section 18.5: "continue" a loop


object.c, baz
Continuing a "for" Loop

Section 18.4: "while" Loops When you put the continue keyword in a for loop, execution jumps to the update expression (i++ in the example):

Standard While Loop for (var i = 0; i < 3; i++) {


if (i === 1) {
A standard while loop will execute until the condition given is false: continue;
}
[Link](i);
var i = 0;
}
while (i < 100) {
[Link](i);
i++; Expected output:
}

Expected output: 0
2

0
1 Continuing a While Loop
...
When you continue in a while loop, execution jumps to the condition (i < 3 in the example):
99

var i = 0;
while (i < 3) {
Decremented loop
if (i === 1) {
var i = 100; i = 2;
while (i > 0) { continue;

[Link] – JavaScript® Notes for Professionals 159 [Link] – JavaScript® Notes for Professionals 160
} }
[Link](i);
i++;
} i=0 j=0 skips rest of j values
10
Expected output:
i=1 j=1 skips rest of j values
20
0 2 1 i=2 j=2 skips rest of j values
2 30
31
32
Section 18.6: Break specific nested loops i=3 j=3 skips rest of j values
40
We can name our loops and break the specific one when necessary. 41
42
outerloop:
43
for (var i = 0;i<3;i++){
innerloop: i=4 j=4 does not log and loops are done
for (var j = 0;j <3; j++){
[Link](i);
[Link](j);
if (j == 1){
break outerloop;
}
}
}

Output:

0
0
0
1

Section 18.7: "do ... while" loop


var availableName;
do {
availableName = getRandomName();
} while (isNameUsed(name));

A do while loop is guaranteed to run at least once as it's condition is only checked at the end of an iteration. A
traditional while loop may run zero or more times as its condition is checked at the beginning of an iteration.

Section 18.8: Break and continue labels


Break and continue statements can be followed by an optional label which works like some kind of a goto
statement, resumes execution from the label referenced position

for(var i = 0; i < 5; i++){


nextLoop2Iteration:
for(var j = 0; j < 5; j++){
if(i == j) break nextLoop2Iteration;
[Link](i, j);
}

[Link] – JavaScript® Notes for Professionals 161 [Link] – JavaScript® Notes for Professionals 162
Chapter 19: Functions }

This climbing behavior can also mean that one reference may "shadow" over a similarly named reference in the
Functions in JavaScript provide organized, reusable code to perform a set of actions. Functions simplify the coding outer scope since it gets seen first.
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. var a = 'hello';

Section 19.1: Function Scoping function foo() {


var a = 'world';

When you define a function, it creates a scope. function bar() {


[Link](a); // => 'world'
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. }
Version ≥ 6
function foo() {
var a = 'hello'; The way JavaScript resolves scoping also applies to the const keyword. Declaring a variable with the const keyword
[Link](a); // => 'hello' 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.

[Link](a); // reference error


function foo() {
const a = true;
Nested functions are possible in JavaScript and the same rules apply.
function bar() {
function foo() { const a = false; // different variable
var a = 'hello'; [Link](a); // false
}
function bar() {
var b = 'world'; const a = false; // SyntaxError
[Link](a); // => 'hello' a = false; // TypeError
[Link](b); // => 'world' [Link](a); // true
} }

[Link](a); // => 'hello' However, functions are not the only blocks that create a scope (if you are using let or const). let and const
[Link](b); // reference error
declarations have a scope of the nearest block statement. See here for a more detailed description.
}

[Link](a); // reference error


[Link](b); // reference error Section 19.2: Currying
When JavaScript tries to resolve a reference or variable, it starts looking for it in the current scope. If it cannot find Currying is the transformation of a function of n arity or arguments into a sequence of n functions taking only one
that declaration in the current scope, it climbs up one scope to look for it. This process repeats until the declaration argument.
has been found. If the JavaScript parser reaches the global scope and still cannot find the reference, a reference
Use cases: When the values of some arguments are available before others, you can use currying to decompose a
error will be thrown.
function into a series of functions that complete the work in stages, as each value arrives. This can be useful:
var a = 'hello';
When the value of an argument almost never changes (e.g., a conversion factor), but you need to maintain
function foo() { the flexibility of setting that value (rather than hard-coding it as a constant).
var b = 'world'; 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.
function bar() {
var c = '!!'; For example, the volume of a rectangular prism can be explained by a function of three factors: length (l), width (w),
and height (h):
[Link](a); // => 'hello'
[Link](b); // => 'world'
[Link](c); // => '!!' var prism = function(l, w, h) {
[Link](d); // reference error return l * w * h;
} }

[Link] – JavaScript® Notes for Professionals 163 [Link] – JavaScript® Notes for Professionals 164
A curried version of this function would look like: (function namedIIFE() {
throw error; // We can now see the error thrown in 'namedIIFE()'
function prism(l) { }());
return function(w) {
return function(h) { While wrapping a function in parenthesis is the most common way to denote to the JavaScript parser to expect an
return l * w * h;
expression, in places where an expression is already expected, the notation can be made more concise:
}
}
} var a = function() { return 42 }();
[Link](a) // => 42
Version ≥ 6
// alternatively, with concise ECMAScript 6+ syntax:
var prism = l => w => h => l * w * h; Arrow version of immediately invoked function:

Version ≥ 6
You can call these sequence of functions with prism(2)(3)(5), which should evaluate to 30. (() => [Link]("Hello!"))(); // => Hello!

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 Section 19.4: Named Functions
function, you cannot use prism()(3)(5).
Functions can either be named or unnamed (anonymous functions):

Section 19.3: Immediately Invoked Function Expressions var namedSum = function sum (a, b) { // named
return a + b;
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. var anonSum = function (a, b) { // anonymous
An important thing to note about IIFE is that even if you name your function, IIFE are not hoisted like standard return a + b;
}
functions are and cannot be called by the function name they are declared with.
namedSum(1, 3);
(function() { anonSum(1, 3);
alert("I've run - but can't be run again because I'm immediately invoked at runtime,
leaving behind only the result I generate");
}());
4
4
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:
But their names are private to their own scope:
(function() {
alert("This is IIFE too."); var sumTwoNumbers = function sum (a, b) {
})(); return a + b;
}
You can easily pass parameters into an IIFE:
sum(1, 3);

(function(message) {
alert(message);
}("Hello World!")); Uncaught ReferenceError: sum is not defined

Additionally, you can return values to the surrounding scope:


Named functions differ from the anonymous functions in multiple scenarios:

var example = (function() { When you are debugging, the name of the function will appear in the error/stack trace
return 42;
Named functions are hoisted while anonymous functions are not
}());
[Link](example); // => 42 Named functions and anonymous functions behave differently when handling recursion
Depending on ECMAScript version, named and anonymous functions may treat the function name property
If required it is possible to name an IIFE. While less often seen, this pattern has several advantages, such as differently
providing a reference which can be used for a recursion and can make debugging simpler as the name is included
in the callstack.
Named functions are hoisted

[Link] – JavaScript® Notes for Professionals 165 [Link] – JavaScript® Notes for Professionals 166
When using an anonymous function, the function can only be called after the line of declaration, whereas a named Hello!
function can be called before declaration. Consider Uncaught TypeError: say is not a function

foo();
var foo = function () { // using an anonymous function This can be solved using a named function
[Link]('bar');
} // The outer variable can even have the same name as the function
// as they are contained in different scopes
var say = function say (times) {
Uncaught TypeError: foo is not a function if (times > 0) {
[Link]('Hello!');

// this time, 'say' doesn't use the outer variable


foo();
// it uses the named function
function foo () { // using a named function
say(times - 1);
[Link]('bar');
}
}
}

var sayHelloTimes = say;


bar say = "oops";

sayHelloTimes(2);

Named Functions in a recursive scenario


Hello!
A recursive function can be defined as: Hello!

var say = function (times) {


if (times > 0) { And as bonus, the named function can't be set to undefined, even from inside:
[Link]('Hello!');
var say = function say (times) {
say(times - 1);
// this does nothing
}
say = undefined;
}
if (times > 0) {
//you could call 'say' directly,
[Link]('Hello!');
//but this way just illustrates the example
var sayHelloTimes = say;
// this time, 'say' doesn't use the outer variable
// it's using the named function
sayHelloTimes(2);
say(times - 1);
}
}
Hello!
Hello! var sayHelloTimes = say;
say = "oops";

What if somewhere in your code the original function binding gets redefined? sayHelloTimes(2);

var say = function (times) {


if (times > 0) { Hello!
[Link]('Hello!'); Hello!

say(times - 1);
}
}
The name property of functions
var sayHelloTimes = say;
Before ES6, named functions had their name properties set to their function names, and anonymous functions had
say = "oops";
their name properties set to the empty string.
sayHelloTimes(2);

[Link] – JavaScript® Notes for Professionals 167 [Link] – JavaScript® Notes for Professionals 168
Version ≤ 5 function example() {
var foo = function () {} return this.x;
[Link]([Link]); // outputs '' }

function foo () {} [Link](example()); // 12


[Link]([Link]); // outputs 'foo'
In strict mode this is undefined by default
Post ES6, named and unnamed functions both set their name properties:
window.x = 12;
Version ≥ 6
var foo = function () {} function example() {
[Link]([Link]); // outputs 'foo' "use strict";
return this.x;
function foo () {} }
[Link]([Link]); // outputs 'foo'
[Link](example()); // Uncaught TypeError: Cannot read property 'x' of undefined(…)
var foo = function bar () {} Version ≥ 7
[Link]([Link]); // outputs 'bar'
Bind Operator

Section 19.5: Binding `this` and arguments The double colon bind operator can be used as a shortened syntax for the concept explained above:

Version ≥ 5.1 var log = [Link](console); // long version


const log = ::[Link]; // short version
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 [Link](foo); // long version
calling it will probably cause a crash. foo::bar(); // short version

[Link](foo, arg1, arg2, arg3); // long version


You can use the .bind() method on a function to create a wrapper that includes the value of this and any number
foo::bar(arg1, arg2, arg3); // short version
of leading arguments.
[Link](foo, args); // long version
var monitor = { foo::bar(...args); // short version
threshold: 5,
check: function(value) {
This syntax allows you to write normally, without worrying about binding this everywhere.
if (value > [Link]) {
[Link]("Value is too high!");
}
Binding console functions to variables
}, var log = [Link](console);
display(message) {
alert(message);
Usage:
}
};
log('one', '2', 3, [4], {5: 5});
[Link](7); // The value of `this` is implied by the method call syntax.
Output:

var badCheck = [Link];


one 2 3 [4] Object {5: 5}
badCheck(15); // The value of `this` is window object and [Link] is undefined, so value >
[Link] is false
Why would you do that?
var check = [Link](monitor);
check(15); // This value of `this` was explicitly bound, the function works. One use case can be when you have custom logger and you want to decide on runtime which one to use.

var check8 = [Link](monitor, 8); var logger = require('appLogger');


check8(); // We also bound the argument to `8` here. It can't be re-specified.
var log = logToServer ? [Link] : [Link](console);
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;

[Link] – JavaScript® Notes for Professionals 169 [Link] – JavaScript® Notes for Professionals 170
Section 19.6: Functions with an Unknown Number of Section 19.7: Anonymous Function
Arguments (variadic functions)
Defining an Anonymous Function
To create a function which accepts an undetermined number of arguments, there are two methods depending on
your environment. When a function is defined, you often give it a name and then invoke it using that name, like so:

Version ≤ 5 foo();

Whenever a function is called, it has an Array-like arguments object in its scope, containing all the arguments function foo(){
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 < [Link]; ++i) { When you define a function this way, the JavaScript runtime stores your function in memory and then creates a
[Link](arguments[i]); 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:
logSomeThings('hello', 'world');
// logs "hello" function() {
// logs "world" // ...
}

Note that you can convert arguments to an actual Array if need-be; see: Converting Array-like Objects to Arrays
When a function is defined without a name, it's known as an anonymous function. The function is stored in
Version ≥ 6 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.
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 Assigning an Anonymous Function to a Variable

function personLogsSomeThings(person, ...msg) { A very common use of anonymous functions is to assign them to a variable:
[Link](arg => {
[Link](person, 'says', arg);
var foo = function(){ /*...*/ };
});
}
foo();

personLogsSomeThings('John', 'hello', 'world');


// logs "John says hello" This use of anonymous functions is covered in more detail in Functions as a variable
// logs "John says world"
Supplying an Anonymous Function as a Parameter to Another Function
Functions can also be called with similar way, the spread syntax
Some functions may accept a reference to a function as a parameter. These are sometimes referred to as
const logArguments = (...args) => [Link](args) "dependency injections" or "callbacks", because it allows the function your calling to "call back" to your code, giving
const list = [1, 2, 3] 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
logArguments('a', 'b', 'c', ...list) element.
// output: Array [ "a", "b", "c", 1, 2, 3 ]

var nums = [0,1,2];


This syntax can be used to insert arbitrary number of arguments to any position, and can be used with any var doubledNums = [Link]( function(element){ return element * 2; } ); // [0,2,4]
iterable(apply accepts only array-like objects).
It would be tedious, sloppy and unnecessary to create a named function, which would clutter your scope with a
const logArguments = (...args) => [Link](args) function only needed in this one place and break the natural flow and reading of your code (a colleague would have
function* generateNumbers() {
to leave this code to find your function to understand what's going on).
yield 6
yield 5
yield 4 Returning an Anonymous Function From Another Function
}
Sometimes it's useful to return a function as the result of another function. For example:
logArguments('a', ...generateNumbers(), ...'pqr', 'b')
// output: Array [ "a", 6, 5, 4, "p", "q", "r", "b" ] var hash = getHashFunction( 'sha1' );

[Link] – JavaScript® Notes for Professionals 171 [Link] – JavaScript® Notes for Professionals 172
var hashValue = hash( 'Secret Value' ); [Link]('Bad.')
};
function getHashFunction( algorithm ){
bar(true);
if ( algorithm === 'sha1' ) return function( value ){ /*...*/ };
else if ( algorithm === 'md5' ) return function( value ){ /*...*/ }; // Console Output:
// Whassup?
} // Bad.

Immediately Invoking an Anonymous Function


The intent here was for the anonymous function to recursively call itself, but when the value of foo changes, you
Unlike many other languages, scoping in JavaScript is function-level, not block-level. (See Function Scoping ). In end up with a potentially difficult to trace bug.
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 <script> tag, rather than allowing variable names to be defined in the global scope (which runs Instead, we can give the anonymous function a reference to itself by giving it a private name, like so:
the risk of other scripts colliding with your variable names). A common method to handle this situation is to define
var foo = function myself(callAgain){
a new anonymous function and then immediately invoke it, safely hiding you variables within the scope of the
[Link]( 'Whassup?' );
anonymous function and without making your code accessible to third-parties via a leaked function name. For // Less than ideal... we're dependent on a variable reference...
example: if (callAgain === true) myself(false);
};
<!-- My Script -->
<script> foo(true);
function initialize(){
// foo is safely hidden within initialize, but... // Console Output:
var foo = ''; // Whassup?
} // Whassup?

// ...my initialize function is now accessible from global scope. // Assign bar to the original function, and assign foo to another function.
// There is a risk someone could call it again, probably by accident. var bar = foo;
initialize(); foo = function(){
</script> [Link]('Bad.')
};
<script>
// Using an anonymous function, and then immediately bar(true);
// invoking it, hides my foo variable and guarantees
// no one else can call it a second time. // Console Output:
(function(){ // Whassup?
var foo = ''; // Whassup?
}()) // <--- the parentheses invokes the function immediately
</script> Note that the function name is scoped to itself. The name has not leaked into the outer scope:
Self-Referential Anonymous Functions
myself(false); // ReferenceError: myself is not defined
Sometimes it's useful for an anonymous function to be able to refer to itself. For example, the function may need to
recursively call itself or add properties to itself. If the function is anonymous, though, this can be very difficult as it This technique is especially useful when dealing with recursive anonymous functions as callback parameters:
requires knowledge of the variable that the function has been assigned to. This is the less than ideal solution:
Version ≥ 5
// Calculate the Fibonacci value for each number in an array:
var foo = function(callAgain){
var fib = false,
[Link]( 'Whassup?' );
result = [1,2,3,4,5,6,7,8].map(
// Less than ideal... we're dependent on a variable reference...
function fib(n){
if (callAgain === true) foo(false);
return ( n <= 2 ) ? 1 : fib( n - 1 ) + fib( n - 2 );
};
});
// result = [1, 1, 2, 3, 5, 8, 13, 21]
foo(true);
// fib = false (the anonymous function name did not overwrite our fib variable)
// Console Output:
// Whassup?
// Whassup?
Section 19.8: Default parameters
Before ECMAScript 2015 (ES6), a parameter's default value could be assigned in the following way:
// Assign bar to the original function, and assign foo to another function.
var bar = foo;
foo = function(){ function printMsg(msg) {

[Link] – JavaScript® Notes for Professionals 173 [Link] – JavaScript® Notes for Professionals 174
msg = typeof msg !== 'undefined' ? // if a value was provided }
msg : // then, use that value in the reassignment
'Default value for msg.'; // else, assign a default value add(1); // 4, 4
[Link](msg); add(3); // 12, 12
} add(2, 7); // 18, 18
add(1, 2, 5); // 8, 10
add(1, 2, 5, 10); // 8, 20
ES6 provided a new syntax where the condition and reassignment depicted above is no longer necessary:
Reusing the function's return value in a new invocation's default value:
Version ≥ 6 Version ≥ 6
function printMsg(msg='Default value for msg.') { let array = [1]; // meaningless: this will be overshadowed in the function's scope
[Link](msg); function add(value, array = []) {
} [Link](value);
return array;
printMsg(); // -> "Default value for msg."
}
printMsg(undefined); // -> "Default value for msg."
add(5); // [5]
printMsg('Now my msg in different!'); // -> "Now my msg in different!"
add(6); // [6], not [5, 6]
add(6, add(5)); // [5, 6]
This also shows that if a parameter is missing when the function is invoked, its value is kept as undefined, as it can
arguments value and length when lacking parameters in invocation
be confirmed by explicitly providing it in the following example (using an arrow function):

Version ≥ 6 The arguments array object only retains the parameters whose values are not default, i.e. those that are explicitly
let param_check = (p = 'str') => [Link](p + ' is of type: ' + typeof p); provided when the function is invoked:

Version ≥ 6
param_check(); // -> "str is of type: string"
param_check(undefined); // -> "str is of type: string" function foo(a = 1, b = a + 1) {
[Link]([Link], arguments);
param_check(1); // -> "1 is of type: number" [Link](a,b);
param_check(this); // -> "[object Window] is of type: object" }

Functions/variables as default values and reusing parameters foo(); // info: 0 >> [] | log: 1, 2
foo(4); // info: 1 >> [4] | log: 4, 5
The default parameters' values are not restricted to numbers, strings or simple objects. A function can also be set foo(5, 6); // info: 2 >> [5, 6] | log: 5, 6
as the default value callback = function(){}:

Version ≥ 6 Section 19.9: Call and apply


function foo(callback = function(){ [Link]('default'); }) {
callback(); Functions have two built-in methods that allow the programmer to supply arguments and the this variable
} differently: call and apply.

foo(function (){ This is useful, because functions that operate on one object (the object that they are a property of) can be
[Link]('custom');
repurposed to operate on another, compatible object. Additionally, arguments can be given in one shot as arrays,
});
// custom similar to the spread (...) operator in ES6.

foo(); let obj = {


//default a: 1,
b: 2,
set: function (a, b) {
There are certain characteristics of the operations that can be performed through default values:
this.a = a;
this.b = b;
A previously declared parameter can be reused as a default value for the upcoming parameters' values.
}
Inline operations are allowed when assigning a default value to a parameter. };
Variables existing in the same scope of the function being declared can be used in its default values.
Functions can be invoked in order to provide their return value into a default value. [Link](3, 7); // normal syntax
[Link](obj, 3, 7); // equivalent to the above
Version ≥ 6 [Link](obj, [3, 7]); // equivalent to the above; note that an array is used
let zero = 0;
function multiply(x) { return x * 2;} [Link](obj); // prints { a: 3, b: 5 }

function add(a = 1 + zero, b = a, c = b + a, d = multiply(c)) { let myObj = {};


[Link]((a + b + c), d); [Link](5, 4); // fails; myObj has no `set` property

[Link] – JavaScript® Notes for Professionals 175 [Link] – JavaScript® Notes for Professionals 176
[Link](myObj, 5, 4); // success; `this` in set() is re-routed to myObj instead of obj multiplyTwoThenAddTen(10); // 30
[Link](myObj, [5, 4]); // same as above; note the array
The "application" part of partial application simply means fixing parameters of a function.
[Link](myObj); // prints { a: 3, b: 5 }

Section 19.11: Passing arguments by reference or value


Version ≥ 5

ECMAScript 5 introduced another method called bind() in addition to call() and apply() to explicitly set this
value of the function to specific object. In JavaScript all arguments are passed by value. When a function assigns a new value to an argument variable, that
change will not be visible to the caller:
It behaves quite differently than the other two. The first argument to bind() is the this value for the new function.
All other arguments represent named parameters that should be permanently set in the new function. var obj = {a: 2};
function myfunc(arg){
arg = {a: 5}; // Note the assignment is to the parameter variable itself
function showName(label) {
}
[Link](label + ":" + [Link]);
myfunc(obj);
}
[Link](obj.a); // 2
var student1 = {
name: "Ravi"
}; However, changes made to (nested) properties of such arguments, will be visible to the caller:
var student2 = {
name: "Vinod" var obj = {a: 2};
}; function myfunc(arg){
arg.a = 5; // assignment to a property of the argument
// create a function just for student1 }
var showNameStudent1 = [Link](student1); myfunc(obj);
showNameStudent1("student1"); // outputs "student1:Ravi" [Link](obj.a); // 5

// create a function just for student2


This can be seen as a call by reference: although a function cannot change the caller's object by assigning a new
var showNameStudent2 = [Link](student2, "student2");
showNameStudent2(); // outputs "student2:Vinod" value to it, it could mutate the caller's object.

// attaching a method to an object doesn't change `this` value of that method. As primitive valued arguments, like numbers or strings, are immutable, there is no way for a function to mutate
[Link] = showNameStudent1; them:
[Link]("student2"); // outputs "student2:Ravi"
var s = 'say';

Section 19.10: Partial Application function myfunc(arg){


arg += ' hello'; // assignment to the parameter variable itself
}
Similar to currying, partial application is used to reduce the number of arguments passed to a function. Unlike myfunc(s);
currying, the number need not go down by one. [Link](s); // 'say'

Example:
When a function wants to mutate an object passed as argument, but does not want to actually mutate the caller's
object, the argument variable should be reassigned:
This function ...
Version ≥ 6
function multiplyThenAdd(a, b, c) {
var obj = {a: 2, b: 3};
return a * b + c;
function myfunc(arg){
}
arg = [Link]({}, arg); // assignment to argument variable, shallow copy
arg.a = 5;
... can be used to create another function that will always multiply by 2 and then add 10 to the passed value; }
myfunc(obj);
function reversedMultiplyThenAdd(c, b, a) { [Link](obj.a); // 2
return a * b + c;
} As an alternative to in-place mutation of an argument, functions can create a new value, based on the argument,
and return it. The caller can then assign it, even to the original variable that was passed as argument:
function factory(b, c) {
return [Link](null, c, b);
var a = 2;
}
function myfunc(arg){
arg++;
var multiplyTwoThenAddTen = factory(2, 10);
return arg;

[Link] – JavaScript® Notes for Professionals 177 [Link] – JavaScript® Notes for Professionals 178
} and easily create a transformation track:
a = myfunc(a);
[Link](obj.a); // 3 Version ≥ 6
const formatText = compose(capitalize, sign);

Section 19.12: Function Arguments, "arguments" object, rest formatText('this is an example')


and spread parameters //This is an example,
//made with love
Functions can take inputs in form of variables that can be used and assigned inside their own scope. The following
function takes two numeric values and returns their sum: N.B. Composition is achieved through a utility function usually called compose as in our example.

function addition (argument1, argument2){ Implementation of compose are present in many JavaScript utility libraries (lodash, rambda, etc.) but you can also
return argument1 + argument2; start out with a simple implementation such as:
}
Version ≥ 6
[Link](addition(2, 3)); // -> 5
const compose = (...funs) =>
arguments object x =>
[Link]((ac, f) => f(ac), x);
The arguments object contains all the function's parameters that contain a non-default value. It can also be used
even if the parameters are not explicitly declared: Section 19.14: Get the name of a function object
(function() { [Link](arguments) })(0,'str', [2,{3}]) // -> [0, "str", Array[2]] Version ≥ 6

Although when printing arguments the output resembles an Array, it is in fact an object: ES6:

(function() { [Link](typeof arguments) })(); // -> object [Link]

Rest parameters: function (...parm) {}


Explanation on MDN. As of 2015 works in [Link] and all major browsers except IE.
In ES6, the ... syntax when used in the declaration of a function's parameters transforms the variable to its right
into a single object containing all the remaining parameters provided after the declared ones. This allows the Version ≥ 5
function to be invoked with an unlimited number of arguments, which will become part of this variable:
ES5:
(function(a, ...b){[Link](typeof b+': '+b[0]+b[1]+b[2]) })(0,1,'2',[3],{i:4});
// -> object: 123 If you have a reference to the function, you can do:
Spread parameters: function_name(...varb);
function functionName( func )
{
In ES6, the ... syntax can also be used when invoking a function by placing an object/variable to its right. This
// Match:
allows that object's elements to be passed into that function as a single object: // - ^ the beginning of the string
// - function the word 'function'
let nums = [2,42,-1]; // - \s+ at least some white space
[Link](...['a','b','c'], [Link](...nums)); // -> a b c 42 // - ([\w\$]+) capture one or more valid JavaScript identifier characters
// - \( followed by an opening brace

Section 19.13: Function Composition


//
var result = /^function\s+([\w\$]+)\(/.exec( [Link]() )

Composing multiple functions into one is a functional programming common practice; return result ? result[1] : ''
}
composition makes a pipeline through which our data will transit and get modified simply working on the function-
composition (just like snapping pieces of a track together)...
Section 19.15: Recursive Function
you start out with some single responsibility functions:
A recursive function is simply a function, that would call itself.
Version ≥ 6
const capitalize = x => [Link](/^\w/, m => [Link]()); function factorial (n) {
const sign = x => x + ',\nmade with love'; if (n <= 1) {
return 1;
}

[Link] – JavaScript® Notes for Professionals 179 [Link] – JavaScript® Notes for Professionals 180
}
return n * factorial(n - 1);
}
Running this function like so will look like this:

The above function shows a basic example of how to perform a recursive function to return a factorial. [Link](firstChar("JS"));

Another example, would be to retrieve the sum of even numbers in an array.


Console output:

function countEvenNumbers (arr) {


> The first action of the first char function
// Sentinel value. Recursion stops on empty array.
> J
if ([Link] < 1) {
return 0;
} It will not print the message after the return statement, as the function has now been ended.
// The shift() method removes the first element from an array
// and returns that element. This method changes the length of the array. Return statement spanning multiple lines:
var value = [Link]();
In JavaScript, you can normally split up a line of code into many lines for readability purposes or organization. This
// `value % 2 === 0` tests if the number is even or odd
is valid JavaScript:
// If it's even we add one to the result of counting the remainder of
// the array. If it's odd, we add zero to it.
return ((value % 2 === 0) ? 1 : 0) + countEvens(arr); var
} name = "bob",
age = 18;

It is important that such functions make some sort of sentinel value check to avoid infinite loops. In the first
When JavaScript sees an incomplete statement like var it looks to the next line to complete itself. However, if you
example above, when n is less than or equal to 1, the recursion stops, allowing the result of each call to be returned
make the same mistake with the return statement, you will not get what you expected.
back up the call stack.

return
Section 19.16: Using the Return Statement "Hi, my name is "+ name + ". " +
"I'm "+ age + " years old.";
The return statement can be a useful way to create output for a function. The return statement is especially useful
if you do not know in which context the function will be used yet. This code will return undefined because return by itself is a complete statement in JavaScript, so it will not look to
the next line to complete itself. If you need to split up a return statement into multiple lines, put a value next to
//An example function that will take a string as input and return return before you split it up, like so.
//the first character of the string.

return "Hi, my name is " + name + ". " +


function firstChar (stringIn){
"I'm " + age + " years old.";
return [Link](0);
}
Section 19.17: Functions as a variable
Now to use this function, you need to put it in place of a variable somewhere else in your code:
A normal function declaration looks like this:
Using the function result as an argument for another function:
function foo(){
[Link](firstChar("Hello world")); }

Console output will be: A function defined like this is accessible from anywhere within its context by its name. But sometimes it can be
useful to treat function references like object references. For example, you can assign an object to a variable based
> H on some set of conditions and then later retrieve a property from one or the other object:

The return statement ends the function var name = 'Cameron';


var spouse;
If we modify the function in the beginning, we can demonstrate that the return statement ends the function.
if ( name === 'Taylor' ) spouse = { name: 'Jordan' };
function firstChar (stringIn){ else if ( name === 'Cameron' ) spouse = { name: 'Casey' };
[Link]("The first action of the first char function");
return [Link](0); var spouseName = [Link];
[Link]("The last action of the first char function");

[Link] – JavaScript® Notes for Professionals 181 [Link] – JavaScript® Notes for Professionals 182
In JavaScript, you can do the same thing with functions: function getValue(){
return 41;
}
// Example 1
var hashAlgorithm = 'sha1';
var hash; A reference to a function is like any other value. As you've seen, a reference can be assigned to a variable, and that
variable's reference value can be subsequently assigned to other variables. You can pass around references to
if ( hashAlgorithm === 'sha1' ) hash = function(value){ /*...*/ };
functions like any other value, including passing a reference to a function as the return value of another function.
else if ( hashAlgorithm === 'md5' ) hash = function(value){ /*...*/ };
For example:
hash('Fred');
// Example 5
// getHashingFunction returns a function, which is assigned
In the example above, hash is a normal variable. It is assigned a reference to a function, after which the function it
// to hash for later use:
references can be invoked using parentheses, just like a normal function declaration. var hash = getHashingFunction( 'sha1' );
// ...
The example above references anonymous functions... functions that do not have their own name. You can also hash('Fred');
use variables to refer to named functions. The example above could be rewritten like so:

// Example 2 // return the function corresponding to the given algorithmName


var hashAlgorithm = 'sha1'; function getHashingFunction( algorithmName ){
var hash; // return a reference to an anonymous function
if (algorithmName === 'sha1') return function(value){ /**/ };
if ( hashAlgorithm === 'sha1' ) hash = sha1Hash; // return a reference to a declared function
else if ( hashAlgorithm === 'md5' ) hash = md5Hash; else if (algorithmName === 'md5') return md5;
}
hash('Fred');
function md5Hash(value){
function md5Hash(value){ // ...
// ... }
}
You don't need to assign a function reference to a variable in order to invoke it. This example, building off example
function sha1Hash(value){ 5, will call getHashingFunction and then immediately invoke the returned function and pass its return value to
// ...
hashedValue.
}

// Example 6
Or, you can assign function references from object properties: var hashedValue = getHashingFunction( 'sha1' )( 'Fred' );

A Note on Hoisting
// Example 3
var hashAlgorithms = {
sha1: function(value) { /**/ }, Keep in mind that, unlike normal function declarations, variables that reference functions are not "hoisted". In
md5: function(value) { /**/ } example 2, the md5Hash and sha1Hash functions are defined at the bottom of the script, but are available
}; everywhere immediately. No matter where you define a function, the interpreter "hoists" it to the top of its scope,
making it immediately available. This is not the case for variable definitions, so code like the following will break:
var hashAlgorithm = 'sha1';
var hash;
var functionVariable;
if ( hashAlgorithm === 'sha1' ) hash = hashAlgorithms.sha1;
else if ( hashAlgorithm === 'md5' ) hash = hashAlgorithms.md5; hoistedFunction(); // works, because the function is "hoisted" to the top of its scope
functionVariable(); // error: undefined is not a function.
hash('Fred');
function hoistedFunction(){}
functionVariable = function(){};
You can assign the reference to a function held by one variable to another by omitting the parentheses. This can
result in an easy-to-make mistake: attempting to assign the return value of a function to another variable, but
accidentally assigning the reference to the function.

// Example 4
var a = getValue;
var b = a; // b is now a reference to getValue.
var c = b(); // b is invoked, so c now holds the value returned by getValue (41)

[Link] – JavaScript® Notes for Professionals 183 [Link] – JavaScript® Notes for Professionals 184
Chapter 20: Functional JavaScript .bind(h, h1, h2)
.bind(g, g1, g2)
.bind(f, f1, f2);

Section 20.1: Higher-Order Functions


function identityMonad(value) {
In general, functions that operate on other functions, either by taking them as arguments or by returning them (or var monad = [Link](null);
both), are called higher-order functions.
// func should return a monad
[Link] = function (func, ...args) {
A higher-order function is a function that can take another function as an argument. You are using higher-order
return func(value, ...args);
functions when passing callbacks. };

function iAmCallbackFunction() { // whatever func does, we get our monad back


[Link]("callback has been invoked"); [Link] = function (func, ...args) {
} func(value, ...args);

function iAmJustFunction(callbackFn) { return identityMonad(value);


// do some stuff ... };

// invoke the callback function. // func doesn't have to know anything about monads
callbackFn(); [Link] = function (func, ...args) {
} return identityMonad(func(value, ...args));
};
// invoke your higher-order function with a callback function.
iAmJustFunction(iAmCallbackFunction); // Get the value wrapped in this monad
[Link] = function () {
A higher-order function is also a function that returns another function as its result. return value;
};

function iAmJustFunction() {
return monad;
// do some stuff ...
};

// return a function.
return function iAmReturnedFunction() { It works with primitive values
[Link]("returned function has been invoked");
} var value = 'foo',
} f = x => x + ' changed',
g = x => x + ' again';
// invoke your higher-order function and its returned function.
iAmJustFunction()(); identityMonad(value)
.apply(f)

Section 20.2: Identity Monad


.apply(g)
.bind(alert); // Alerts 'foo changed again'

This is an example of an implementation of the identity monad in JavaScript, and could serve as a starting point to
And also with objects
create other monads.
var value = { foo: 'foo' },
Based on the conference by Douglas Crockford on monads and gonads
f = x => identityMonad([Link](x, { foo: 'bar' })),
g = x => [Link](x, { bar: 'foo' }),
Using this approach reusing your functions will be easier because of the flexibility this monad provides, and h = x => [Link]('foo: ' + [Link] + ', bar: ' + [Link]);
composition nightmares:
identityMonad(value)
f(g(h(i(j(k(value), j1), i2), h1, h2), g1, g2), f1, f2) .bind(f)
.apply(g)
.bind(h); // Logs 'foo: bar, bar: foo'
readable, nice and clean:

Let's try everything:


identityMonad(value)
.bind(k)
.bind(j, j1, j2) var add = (x, ...args) => x + [Link]((r, n) => r + n, 0),
.bind(i, i2) multiply = (x, ...args) => x * [Link]((r, n) => r * n, 1),

[Link] – JavaScript® Notes for Professionals 185 [Link] – JavaScript® Notes for Professionals 186
divideMonad = (x, ...args) => identityMonad(x / multiply(...args)), let b = pure(obj)
log = x => [Link](x), [Link](obj) // Logs { "a": 0 }
substract = (x, ...args) => x - add(...args); [Link](b) // Logs 1

identityMonad(100)
The function did not change the object obj values
.apply(add, 10, 29, 13)
.apply(multiply, 2)
.bind(divideMonad, 2)
.apply(substract, 67, 34)
.apply(multiply, 1239)
Pure functions must not rely on variables outside their scope
.bind(divideMonad, 20, 54, 2)
.apply([Link])
.call(log); // Logs 29
Impure function

Section 20.3: Pure Functions let a = 1;

A basic principle of functional programming is that it avoids changing the application state (statelessness) and let impure = (input) => {
variables outside its scope (immutability). // Multiply with variable outside function scope
let output = input * a;
return output;
Pure functions are functions that:
}

with a given input, always return the same output [Link](impure(2)) // Logs 2
they do not rely on any variable outside their scope a++; // a becomes equal to 2
they do not modify the state of the application (no side effects) [Link](impure(2)) // Logs 4

Let's take a look at some examples: This impure function rely on variable a that is defined outside its scope. So, if a is modified, impure's function result
will be different.

Pure function
Pure functions must not change any variable outside their scope
let pure = (input) => {
let a = 1;
// Multiply with variable inside function scope
Impure function
let output = input * a;
return output;
let obj = { a: 0 } }

const impure = (input) => { [Link](pure(2)) // Logs 2


// Modifies input.a
input.a = input.a + 1;
return input.a; The pure's function result does not rely on any variable outside its scope.
}

let b = impure(obj)
Section 20.4: Accepting Functions as Arguments
[Link](obj) // Logs { "a": 1 }
[Link](b) // Logs 1 function transform(fn, arr) {
let result = [];
for (let el of arr) {
The function changed the obj.a value that is outside its scope. [Link](fn(el)); // We push the result of the transformed item to result
}
Pure function return result;
}
let obj = { a: 0 }
[Link](transform(x => x * 2, [1,2,3,4])); // [2, 4, 6, 8]
const pure = (input) => {
// Does not modify obj As you can see, our transform function accepts two parameters, a function and a collection. It will then iterate the
let output = input.a + 1;
collection, and push values onto the result, calling fn on each of them.
return output;
}
Looks familiar? This is very similar to how [Link]() works!

[Link] – JavaScript® Notes for Professionals 187 [Link] – JavaScript® Notes for Professionals 188
[Link]([1, 2, 3, 4].map(x => x * 2)); // [2, 4, 6, 8]
Chapter 21: Prototypes, objects
In the conventional JS there are no class instead we have prototypes. Like the class, prototype inherits the
properties including the methods and the variables declared in the class. We can create the new instance of the
object whenever it is necessary by, [Link](PrototypeName); (we can give the value for the constructor as
well)

Section 21.1: Creation and initialising Prototype


var Human = function() {
[Link] = true;
[Link] = true; //

};

[Link] = function() {
if ([Link]) { // checks whether this prototype has instance of speak
[Link] = "Steve"
[Link]('Hi, I am ' + [Link]);
} else{
[Link]('Sorry i can not speak');
}
};

The prototype can be instantiated like this

obj = [Link]([Link]);
[Link]();

We can pass value for the constructor and make the boolean true and false based on the requirement.

Detailed Explanation

var Human = function() {


[Link] = true;
};
// Basic greet function which will greet based on the canSpeak flag
[Link] = function() {
if ([Link]) {
[Link]('Hi, I am ' + [Link]);
}
};

var Student = function(name, title) {


[Link](this); // Instantiating the Human object and getting the memebers of the class
[Link] = name; // inheriting the name from the human class
[Link] = title; // getting the title from the called function
};

[Link] = [Link]([Link]);
[Link] = Student;

[Link] = function() {
if ([Link]) {
[Link]('Hi, I am ' + [Link] + ', the ' + [Link]);
}
};

[Link] – JavaScript® Notes for Professionals 189 [Link] – JavaScript® Notes for Professionals 190
var Customer = function(name) {
[Link](this); // inheriting from the base class
[Link] = name;
Chapter 22: Classes
Section 22.1: Class Constructor
};

[Link] = [Link]([Link]); // creating the object


[Link] = Customer; The fundamental part of most classes is its constructor, which sets up each instance's initial state and handles any
parameters that were passed when calling new.

var bill = new Student('Billy', 'Teacher'); It's defined in a class block as though you're defining a method named constructor, though it's actually handled
var carter = new Customer('Carter');
as a special case.
var andy = new Student('Andy', 'Bill');
var virat = new Customer('Virat');
class MyClass {
[Link](); constructor(option) {
// Hi, I am Bob, the Teacher [Link](`Creating instance using ${option} option.`);
[Link] = option;
[Link](); }
// Hi, I am Carter }

[Link](); Example usage:


// Hi, I am Andy, the Bill
const foo = new MyClass('speedy'); // logs: "Creating instance using speedy option"
[Link]();

A small thing to note is that a class constructor cannot be made static via the static keyword, as described below
for other methods.

Section 22.2: Class Inheritance


Inheritance works just like it does in other object-oriented languages: methods defined on the superclass are
accessible in the extending subclass.

If the subclass declares its own constructor then it must invoke the parents constructor via super() before it can
access this.

class SuperClass {

constructor() {
[Link] = [Link];
}

log() {
[Link](`Hello ${[Link]}`);
}

class SubClass extends SuperClass {

constructor() {
super();
[Link] = 'subclass';
}

const subClass = new SubClass();

[Link](); // logs: "Hello subclass"

[Link] – JavaScript® Notes for Professionals 191 [Link] – JavaScript® Notes for Professionals 192
Section 22.3: Static Methods const myClassInstance = new MyClass();
[Link] = 'Joe';
[Link] = 'Bob';
Static methods and properties are defined on the class/constructor itself, not on instance objects. These are specified
in a class definition by using the static keyword. [Link]([Link]); // logs: "Bob"
[Link](myClassInstance.names_); // logs: ["Joe", "Bob"]
class MyClass {
static myStaticMethod() { If you only define a setter, attempting to access the property will always return undefined.
return 'Hello';
}
const classInstance = new class {
set prop(value) {
static get myStaticProperty() {
[Link]('setting', value);
return 'Goodbye';
}
}
};
}

[Link] = 10; // logs: "setting", 10


[Link]([Link]()); // logs: "Hello"
[Link]([Link]); // logs: "Goodbye"
[Link]([Link]); // logs: undefined

We can see that static properties are not defined on object instances:
If you only define a getter, attempting to assign the property will have no effect.

const myClassInstance = new MyClass();


const classInstance = new class {
get prop() {
[Link]([Link]); // logs: undefined
return 5;
}
However, they are defined on subclasses: };

class MySubClass extends MyClass {}; [Link] = 10;

[Link]([Link]()); // logs: "Hello" [Link]([Link]); // logs: 5


[Link]([Link]); // logs: "Goodbye"

Section 22.5: Private Members


Section 22.4: Getters and Setters
JavaScript does not technically support private members as a language feature. Privacy - described by Douglas
Getters and setters allow you to define custom behaviour for reading and writing a given property on your class. To Crockford - gets emulated instead via closures (preserved function scope) that will be generated each with every
the user, they appear the same as any typical property. However, internally a custom function you provide is used instantiation call of a constructor function.
to determine the value when the property is accessed (the getter), and to perform any necessary changes when the
property is assigned (the setter). The Queue example demonstrates how, with constructor functions, local state can be preserved and made
accessible too via privileged methods.
In a class definition, a getter is written like a no-argument method prefixed by the get keyword. A setter is similar,
except that it accepts one argument (the new value being assigned) and the set keyword is used instead. class Queue {

Here's an example class which provides a getter and setter for its .name property. Each time it's assigned, we'll constructor () { // - does generate a closure with each instantiation.
record the new name in an internal .names_ array. Each time it's accessed, we'll return the latest name.
const list = []; // - local state ("private member").

class MyClass { [Link] = function (type) { // - privileged public method


constructor() { // accessing the local state
this.names_ = []; [Link](type); // "writing" alike.
} return type;
};
set name(value) { [Link] = function () { // - privileged public method
this.names_.push(value); // accessing the local state
} return [Link](); // "reading / writing" alike.
};
get name() { }
return this.names_[this.names_.length - 1]; }
}
}

[Link] – JavaScript® Notes for Professionals 193 [Link] – JavaScript® Notes for Professionals 194
var q = new Queue; // [METADATA]() {
// return {
[Link](9); // ... first in ... make: [Link],
[Link](8); // model: [Link]
[Link](7); // };
// }
[Link]([Link]()); // 9 ... first out.
[Link]([Link]()); // 8 // you can also use any javascript expression
[Link]([Link]()); // 7
[Link](q); // {} // this one is just a string, and could also be defined with simply add()
[Link]([Link](q)); // ["enqueue","dequeue"] ["add"](a, b) {
return a + b;
}
With every instantiation of a Queue type the constructor generates a closure.
// this one is dynamically evaluated
Thus both of a Queue type's own methods enqueue and dequeue (see [Link](q)) still do have access to list
[1 + 2]() {
that continues to live in its enclosing scope that, at construction time, has been preserved. return "three";
}
Making use of this pattern - emulating private members via privileged public methods - one should keep in mind }
that, with every instance, additional memory will be consumed for every own property method (for it is code that
can't be shared/reused). The same is true for the amount/size of state that is going to be stored within such a let MazdaMPV = new Car("Mazda", "MPV");
[Link](4, 5); // 9
closure.
MazdaMPV[3](); // "three"
MazdaMPV[METADATA](); // { make: "Mazda", model: "MPV" }
Section 22.6: Methods
Methods can be defined in classes to perform a function and optionally return a result.
Section 22.8: Managing Private Data with Classes
They can receive arguments from the caller.
One of the most common obstacles using classes is finding the proper approach to handle private states. There are
4 common solutions for handling private states:
class Something {
constructor(data) {
[Link] = data
Using Symbols
}
Symbols are new primitive type introduced on in ES2015, as defined at MDN
doSomething(text) {
return {
data: [Link], A symbol is a unique and immutable data type that may be used as an identifier for object properties.
text
}
} When using symbol as a property key, it is not enumerable.
}
As such, they won't be revealed using for var in or [Link].
var s = new Something({})
[Link]("hi") // returns: { data: {}, text: "hi" } Thus we can use symbols to store private data.

Section 22.7: Dynamic Method Names const topSecret = Symbol('topSecret'); // our private key; will only be accessible on the scope of
the module file
export class SecretAgent{
There is also the ability to evaluate expressions when naming methods similar to how you can access an objects' constructor(secret){
properties with []. This can be useful for having dynamic property names, however is often used in conjunction this[topSecret] = secret; // we have access to the symbol key (closure)
with Symbols. [Link] = 'just a simple gardner';
[Link] = () => {
let METADATA = Symbol('metadata'); figureWhatToDo(topSecret[topSecret]); // we have access to topSecret
};
class Car { }
constructor(make, model) { }
[Link] = make;
[Link] = model; Because symbols are unique, we must have reference to the original symbol to access the private property.
}
import {SecretAgent} from '[Link]'
// example using symbols

[Link] – JavaScript® Notes for Professionals 195 [Link] – JavaScript® Notes for Professionals 196
const agent = new SecretAgent('steal all the ice cream'); constructor(secret){
// ok let's try to get the secret out of him! const topSecret = secret;
[Link](agent); // ['coverStory'] only cover story is public, our secret is kept. [Link] = 'just a simple gardner';
agent[Symbol('topSecret')]; // undefined, as we said, symbols are always unique, so only the [Link] = () => {
original symbol will help us to get the data. figureWhatToDo(topSecret); // we have access to topSecret
};
}
But it's not 100% private; let's break that agent down! We can use the [Link] method to
}
get the object symbols.

In this example as well the data is 100% private and can't be reached outside the class, so our agent is safe.
const secretKeys = [Link](agent);
agent[secretKeys[0]] // 'steal all the ice cream' , we got the secret.
Using naming conventions

Using WeakMaps We will decide that any property who is private will be prefixed with _.

WeakMap is a new type of object that have been added for es6. Note that for this approach the data isn't really private.

As defined on MDN export class SecretAgent{


constructor(secret){
this._topSecret = secret; // it private by convention
The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys [Link] = 'just a simple gardner';
must be objects and the values can be arbitrary values. [Link] = () => {
figureWhatToDo(this_topSecret);
};
Another important feature of WeakMap is, as defined on MDN. }
}

The key in a WeakMap is held weakly. What this means is that, if there are no other strong references to
the key, the entire entry will be removed from the WeakMap by the garbage collector.
Section 22.9: Class Name binding
ClassDeclaration's Name is bound in different ways in different scopes -
The idea is to use the WeakMap, as a static map for the whole class, to hold each instance as key and keep the
1. The scope in which the class is defined - let binding
private data as a value for that instance key.
2. The scope of the class itself - within { and } in class {} - const binding
Thus only inside the class will we have access to the WeakMap collection.
class Foo {
// Foo inside this block is a const binding
Let's give our agent a try, with WeakMap:
}
// Foo here is a let binding
const topSecret = new WeakMap(); // will hold all private data of all instances.
export class SecretAgent{
constructor(secret){
For example,
[Link](this,secret); // we use this, as the key, to set it on our instance private
data class A {
[Link] = 'just a simple gardner'; foo() {
[Link] = () => { A = null; // will throw at runtime as A inside the class is a `const` binding
figureWhatToDo([Link](this)); // we have access to topSecret }
}; }
} A = null; // will NOT throw as A here is a `let` binding
}
This is not the same for a Function -
Because the const topSecret is defined inside our module closure, and since we didn't bind it to our instance
properties, this approach is totally private, and we can't reach the agent topSecret. function A() {
A = null; // works
Define all methods inside the constructor }
[Link] = function foo() {
A = null; // works
The idea here is simply to define all our methods and members inside the constructor and use the closure to access
}
private members without assigning them to this. A = null; // works

export class SecretAgent{

[Link] – JavaScript® Notes for Professionals 197 [Link] – JavaScript® Notes for Professionals 198
Chapter 23: Namespacing Chapter 24: Context (this)
Section 23.1: Namespace by direct assignment Section 24.1: this with simple objects
//Before: antipattern 3 global variables var person = {
var setActivePage = function () {}; name: 'John Doe',
var getPage = function() {}; age: 42,
var redirectPage = function() {}; gender: 'male',
bio: function() {
//After: just 1 global variable, no function collision and more meaningful function names [Link]('My name is ' + [Link]);
var NavigationNs = NavigationNs || {}; }
[Link] = function() {} };
[Link] = function() {} [Link](); // logs "My name is John Doe"
[Link] = function() {} var bio = [Link];
bio(); // logs "My name is undefined"

Section 23.2: Nested Namespaces In the above code, [Link] makes use of the context (this). When the function is called as [Link](), the
When multiple modules are involved, avoid proliferating global names by creating a single global namespace. From context gets passed automatically, and so it correctly logs "My name is John Doe". When assigning the function to a
there, any sub-modules can be added to the global namespace. (Further nesting will slow down performance and variable though, it loses its context.
add unnecessary complexity.) Longer names can be used if name clashes are an issue:
In non-strict mode, the default context is the global object (window). In strict mode it is undefined.

var NavigationNs = NavigationNs || {};


[Link] = {}; Section 24.2: Saving this for use in nested functions / objects
[Link] = {};
[Link] = {}; One common pitfall is to try and use this in a nested function or an object, where the context has been lost.

// The second level start here. [Link]('myAJAXButton').>
[Link] = function(); makeAJAXRequest(function(result){
[Link] = function(); if (result) { // success
[Link] = function(); [Link] = 'success';
}
})
}

Here the context (this) is lost in the inner callback function. To correct this, you can save the value of this in a
variable:

[Link]('myAJAXButton'). > var self = this;
makeAJAXRequest(function(result){
if (result) { // success
[Link] = 'success';
}
})
}
Version ≥ 6

ES6 introduced arrow functions which include lexical this binding. The above example could be written like this:

[Link]('myAJAXButton'). > makeAJAXRequest(result => {
if (result) { // success
[Link] = 'success';
}
})
}

[Link] – JavaScript® Notes for Professionals 199 [Link] – JavaScript® Notes for Professionals 200
Section 24.3: Binding function context //outputs: I'm Stackoverflow

Version ≥ 5.1
[Link](person3);
Every function has a bind method, which will create a wrapped function that will call it with the correct context. See //outputs: I'm Stackoverflow

here for more information.


So, as you can remark in the example above, whatever object you pass to Person, it'll always use person0
object: it's hard binded.
var monitor = {
threshold: 5,
check: function(value) { Section 24.4: this in constructor functions
if (value > [Link]) {
[Link]("Value is too high!"); When using a function as a constructor, it has a special this binding, which refers to the newly created object:
}
},
function Cat(name) {
display(message) {
[Link] = name;
alert(message);
[Link] = "Meow";
}
}
};

var cat = new Cat("Tom"); // is a Cat object


[Link](7); // The value of `this` is implied by the method call syntax.
[Link]; // Returns "Meow"

var cat2 = Cat("Tom"); // is undefined -- function got executed in global context


var badCheck = [Link];
[Link]; // "Tom"
badCheck(15); // The value of `this` is window object and [Link] is undefined, so value >
[Link]; // error! cannot access property of undefined
[Link] is false

var check = [Link](monitor);


check(15); // This value of `this` was explicitly bound, the function works.

var check8 = [Link](monitor, 8);


check8(); // We also bound the argument to `8` here. It can't be re-specified.

Hard binding

The object of hard binding is to "hard" link a reference to this.


Advantage: It's useful when you want to protect particular objects from being lost.
Example:

function Person(){
[Link]("I'm " + [Link]);
}

var person0 = {name: "Stackoverflow"}


var person1 = {name: "John"};
var person2 = {name: "Doe"};
var person3 = {name: "Ala Eddine JEBALI"};

var origin = Person;


Person = function(){
[Link](person0);
}

Person();
//outputs: I'm Stackoverflow

[Link](person1);
//outputs: I'm Stackoverflow

[Link](person2);

[Link] – JavaScript® Notes for Professionals 201 [Link] – JavaScript® Notes for Professionals 202
Chapter 25: Setters and Getters }
this._firstname = firstname;
this._lastname = lastname;

Setters and getters are object properties that call a function when they are set/gotten.
get firstname() {
return this._firstname;
Section 25.1: Defining a Setter/Getter Using }
[Link]fineProperty set firstname(name) {
this._firstname = name;
var setValue; }
var obj = {};
[Link](obj, "objProperty", { get lastname() {
get: function(){ return this._lastname;
return "a value"; }
},
set: function(value){ set lastname(name) {
setValue = value; this._lastname = name;
} }
}); }

Section 25.2: Defining an Setter/Getter in a Newly Created let person = new Person('John', 'Doe');

Object [Link]([Link], [Link]); // John Doe

JavaScript allows us to define getters and setters in the object literal syntax. Here's an example: [Link] = 'Foo';
[Link] = 'Bar';
var date = {
year: '2017', [Link]([Link], [Link]); // Foo Bar
month: '02',
day: '27',
get date() {
// Get the date in YYYY-MM-DD format
return `${[Link]}-${[Link]}-${[Link]}`
},
set date(dateString) {
// Set the date from a YYYY-MM-DD formatted string
var dateRegExp = /(\d{4})-(\d{2})-(\d{2})/;

// Check that the string is correctly formatted


if ([Link](dateString)) {
var parsedDate = [Link](dateString);
[Link] = parsedDate[1];
[Link] = parsedDate[2];
[Link] = parsedDate[3];
}
else {
throw new Error('Date string must be in YYYY-MM-DD format');
}
}
};

Accessing the [Link] property would return the value 2017-02-27. Setting [Link] = '2018-01-02 would call
the setter function, which would then parse the string and set [Link] = '2018', [Link] = '01', and
[Link] = '02'. Trying to pass an incorrectly formatted string (such as "hello") would throw an error.

Section 25.3: Defining getters and setters in ES6 class


class Person {
constructor(firstname, lastname) {

[Link] – JavaScript® Notes for Professionals 203 [Link] – JavaScript® Notes for Professionals 204
Chapter 26: Events Chapter 27: Inheritance
Section 26.1: Page, DOM and Browser loading Section 27.1: Standard function prototype
This is an example to explain the variations of load events. Start by defining a Foo function that we'll use as a constructor.

1. onload event function Foo (){}

<body > By editing [Link], we can define properties and methods that will be shared by all instances of Foo.
<img src="image1" />
<img src="image2" />
</body> [Link] = function() {
return 'I am bar';
<script> };
function someFunction() {
[Link]("Hi! I am loaded"); We can then create an instance using the new keyword, and call the method.
}
</script> var foo = new Foo();

In this case, the message is logged once all the contents of the page including the images and stylesheets(if any) are [Link]([Link]()); // logs `I am bar`
completely loaded.

2. DOMContentLoaded event
Section 27.2: Dierence between [Link] and
[Link]
[Link]("DOMContentLoaded", function(event) { Unlike in languages like Python, static properties of the constructor function are not inherited to instances.
[Link]("Hello! I am loaded");
Instances only inherit from their prototype, which inherits from the parent type's prototype. Static properties are
});
never inherited.

In the above code, the message is logged only after the DOM/document is loaded (ie:once the DOM is constructed). function Foo() {};
[Link] = 'bold';
3. Self-invoking anonymous function
var foo = new Foo();

(function(){ [Link]([Link]); // 'bold'


[Link]("Hi I am an anonymous function! I am loaded"); [Link]([Link]); // undefined
})();
[Link] = 'italic';

Here, the message gets logged as soon as the browser interprets the anonymous function. It means, this function [Link]([Link]); // 'bold'
can get executed even before the DOM is loaded. [Link]([Link]); // 'italic'

Section 27.3: Prototypal inheritance


Suppose we have a plain object called prototype:

var prototype = { foo: 'foo', bar: function () { return [Link]; } };

Now we want another object called obj that inherits from prototype, which is the same as saying that prototype is
the prototype of obj

var obj = [Link](prototype);

Now all the properties and methods from prototype will be available to obj

[Link]([Link]);

[Link] – JavaScript® Notes for Professionals 205 [Link] – JavaScript® Notes for Professionals 206
[Link]([Link]()); [Link]([Link]);

Console output Console output

"foo"
"foo" 1

Prototypal inheritance is made through object references internally and objects are completely mutable. This
foo is an instance of Foo. The JavaScript coding convention says if a function begins with a capital letter case it can
means any change you make on a prototype will immediately affect every other object that prototype is prototype
be called as a constructor (with the new operand).
of.
To add properties or methods to the "class" you have to add them to its prototype, which can be found in the
[Link] = "bar"; prototype property of the constructor.
[Link]([Link]);

[Link] = 'bar';
Console output [Link]([Link]);

"bar" Console output

[Link] is the prototype of every object, so it's strongly recommended you don't mess with it, especially
if you use any third party library, but we can play with it a little bit. bar

[Link] = 'foo';
In fact what Foo is doing as a "constructor" is just creating objects with [Link] as it's prototype.
[Link]([Link]);
[Link]([Link]);
You can find a reference to its constructor on every object

Console output
[Link]([Link]);

"foo"
"foo"
function Foo(id, name) { ...

Fun fact I've used the browser console to make these examples and broken this page by adding that
breakingLibraries property. [Link]({ }.constructor);

function Object() { [native code] }


Section 27.4: Pseudo-classical inheritance
And also check if an object is an instance of a given class with the instanceof operator
It's an emulation of classical inheritance using prototypical inheritance which shows how powerful prototypes are. It
was made to make the language more attractive to programmers coming from other languages.
[Link](foo instanceof Foo);
Version < 6

IMPORTANT NOTE: Since ES6 it doesn't make sense to use pseudo-classical inheritance since the language true
simulates conventional classes. If you're not using ES6, you should. If you still want to use the classical inheritance
pattern and you're in a ECMAScript 5 or lower environment, then pseudo-classical is your best bet.
[Link](foo instanceof Object);

A "class" is just a function that is made to be called with the new operand and it's used as a constructor.
true
function Foo(id, name) {
[Link] = id;
[Link] = name; Section 27.5: Setting an Object's prototype
}
Version ≥ 5
var foo = new Foo(1, 'foo');
With ES5+, the [Link] function can be used to create an Object with any other Object as it's prototype.

[Link] – JavaScript® Notes for Professionals 207 [Link] – JavaScript® Notes for Professionals 208
const anyObj = {
hello() { Chapter 28: Method Chaining
[Link](`[Link] is ${[Link]}`);

};
},
Section 28.1: Chainable object design and chaining
Chaining and Chainable is a design methodology used to design object behaviors so that calls to object functions
let objWithProto = [Link](anyObj);
[Link] = 'bar'; return references to self, or another object, providing access to additional function calls allowing the calling
statement to chain together many calls without the need to reference the variable holding the object/s.
[Link](); // "[Link] is bar"
Objects that can be chained are said to be chainable. If you call an object chainable, you should ensure that all
To explicitly create an Object without a prototype, use null as the prototype. This means the Object will not inherit returned objects / primitives are of the correct type. It only takes one time for your chainable object to not return
from [Link] either and is useful for Objects used for existence checking dictionaries, e.g. the correct reference (easy to forget to add return this) and the person using your API will lose trust and avoid
chaining. Chainable objects should be all or nothing (not a chainable object even if parts are). An object should not
let objInheritingObject = {}; be called chainable if only some of its functions are.
let objInheritingNull = [Link](null);
Object designed to be chainable
'toString' in objInheritingObject; // true
'toString' in objInheritingNull ; // false function Vec(x = 0, y = 0){
this.x = x;
Version ≥ 6
this.y = y;
// the new keyword implicitly implies the return type
From ES6, the prototype of an existing Object can be changed using [Link], for example
// as this and thus is chainable by default.
}
let obj = [Link]({foo: 'foo'}); [Link] = {
obj = [Link](obj, {bar: 'bar'}); add : function(vec){
this.x += vec.x;
[Link]; // undefined this.y += vec.y;
[Link]; // "bar" return this; // return reference to self to allow chaining of function calls
},
This can be done almost anywhere, including on a this object or in a constructor. scale : function(val){
this.x *= val;
Note: This process is very slow in current browsers and should be used sparingly, try to create the Object with the this.y *= val;
return this; // return reference to self to allow chaining of function calls
desired prototype instead.
},
log :function(val){
Version < 5
[Link](this.x + ' : ' + this.y);
return this;
Before ES5, the only way to create an Object with a manually defined prototype was to construct it with new, for
},
example clone : function(){
return new Vec(this.x,this.y);
var proto = {fizz: 'buzz'}; }
}
function ConstructMyObj() {}
Chaining example
[Link] = proto;
var vec = new Vec();
var objWithProto = new ConstructMyObj(); [Link]({x:10,y:10})
[Link]; // "buzz" .add({x:10,y:10})
.log() // console output "20 : 20"
.add({x:10,y:10})
This behaviour is close enough to [Link] that it is possible to write a polyfill.
.scale(1/30)
.log() // console output "1 : 1"
.clone() // returns a new instance of the object
.scale(2) // from which you can continue chaining
.log()

Don't create ambiguity in the return type

Not all function calls return a useful chainable type, nor do they always return a reference to self. This is where
common sense use of naming is important. In the above example the function call .clone() is unambiguous. Other

[Link] – JavaScript® Notes for Professionals 209 [Link] – JavaScript® Notes for Professionals 210
examples are .toString() implies a string is returned. When you assign the results of a chain the last returning call or object reference is assigned.

An example of an ambiguous function name in a chainable object. var vec2 = [Link](2)


.add(x:1,y:10)
// line object represents a line .clone(); // the last returned result is assigned
[Link](1) // vec2 is a clone of vec after the scale and add
.vec(); // ambiguous you don't need to be looking up docs while writing.
In the above example vec2 is assigned the value returned from the last call in the chain. In this case, that would be
[Link](1)
a copy of vec after the scale and add.
.asVec() // unambiguous implies the return type is the line as a vec (vector)
.add({x:10,y:10)
// toVec is just as good as long as the programmer can use the naming
// to infer the return type Summary

The advantage of changing is clearer more maintainable code. Some people prefer it and will make chainable a
Syntax convention
requirement when selecting an API. There is also a performance benefit as it allows you to avoid having to create
variables to hold interim results. With the last word being that chainable objects can be used in a conventional way
There is no formal usage syntax when chaining. The convention is to either chain the calls on a single line if short or
as well so you don't enforce chaining by making an object chainable.
to chain on the new line indented one tab from the referenced object with the dot on the new line. Use of the
semicolon is optional but does help by clearly denoting the end of the chain.
Section 28.2: Method Chaining
[Link](2).add({x:2,y:2}).log(); // for short chains
Method chaining is a programming strategy that simplifies your code and beautifies it. Method chaining is done by
[Link](2) // or alternate syntax ensuring that each method on an object returns the entire object, instead of returning a single element of that
.add({x:2,y:2}) object. For example:
.log(); // semicolon makes it clear the chain ends here

function Door() {
// and sometimes though not necessary
[Link] = '';
[Link](2)
[Link] = '';
.add({x:2,y:2})
[Link] = 'closed';
.clone() // clone adds a new reference to the chain
}
.log(); // indenting to signify the new reference

[Link] = function() {
// for chains in chains
[Link] = 'opened';
[Link](2)
return this;
.add({x:2,y:2})
}
.add([Link]({x:2,y:2}) // a chain as an argument
.add({x:2,y:2}) // is indented
[Link] = function() {
.scale(2))
[Link] = 'closed';
.log();
return this;
}
// or sometimes
[Link] = function(width,height) {
[Link](2)
[Link] = width;
.add({x:2,y:2})
[Link] = height;
.add([Link]({x:2,y:2}) // a chain as an argument
return this;
.add({x:2,y:2}) // is indented
}
.scale(2)
).log(); // the argument list is closed on the new line
[Link] = function() {
A bad syntax [Link]('The',[Link],'x',[Link],'Door is',[Link]);
vec // new line before the first function call return this;
.scale() // can make it unclear what the intention is }
.log();
var smallDoor = new Door();
vec. // the dot on the end of the line [Link](20,100).open().doorStatus().close().doorStatus();
scale(2). // is very difficult to see in a mass of code
scale(1/2); // and will likely frustrate as can easily be missed Note that each method in [Link] returns this, which refers to the entire instance of that Door object.
// when trying to locate bugs

Left hand side of assignment

[Link] – JavaScript® Notes for Professionals 211 [Link] – JavaScript® Notes for Professionals 212
Chapter 29: Callbacks $.getJSON() syntax:

$.getJSON( url, dataObject, successCallback );


Section 29.1: Simple Callback Usage Examples
Example of $.getJSON() code:
Callbacks offer a way to extend the functionality of a function (or method) without changing its code. This approach
is often used in modules (libraries / plugins), the code of which is not supposed to be changed. $.getJSON("[Link]", {}, function(data) {
// data handling code
Suppose we have written the following function, calculating the sum of a given array of values: });

function foo(array) { The following would not work, because the data-handling code would likely be called before the data is actually
var sum = 0; received, because the $.getJSON function takes an unspecified length of time and does not hold up the call stack as
for (var i = 0; i < [Link]; i++) { it waits for the JSON.
sum += array[i];
}
$.getJSON("[Link]", {});
return sum;
// data handling code
}

Now suppose that we want to do something with each value of the array, e.g. display it using alert(). We could Another example of an asynchronous function is jQuery's animate() function. Because it takes a specified time to
make the appropriate changes in the code of foo, like this: run the animation, sometimes it is desirable to run some code directly following the animation.

.animate() syntax:
function foo(array) {
var sum = 0;
for (var i = 0; i < [Link]; i++) { [Link]( properties, duration, callback );
alert(array[i]);
sum += array[i]; For example, to create a fading-out animation after which the element completely disappears, the following code
} can be run. Note the use of the callback.
return sum;
}
[Link]( { opacity: 0 }, 5000, function() {
[Link]();
But what if we decide to use [Link] instead of alert()? Obviously changing the code of foo, whenever we } );
decide to do something else with each value, is not a good idea. It is much better to have the option to change our
mind without changing the code of foo. That's exactly the use case for callbacks. We only have to slightly change This allows the element to be hidden right after the function has finished execution. This differs from:
foo's signature and body:
[Link]( { opacity: 0 }, 5000 );
function foo(array, callback) { [Link]();
var sum = 0;
for (var i = 0; i < [Link]; i++) { because the latter does not wait for animate() (an asynchronous function) to complete, and therefore the element
callback(array[i]);
is hidden right away, producing an undesirable effect.
sum += array[i];
}
return sum; Section 29.2: Continuation (synchronous and asynchronous)
}
Callbacks can be used to provide code to be executed after a method has completed:
And now we are able to change the behaviour of foo just by changing its parameters:
/**
var array = []; * @arg {Function} then continuation callback
foo(array, alert); */
foo(array, function (x) { function doSomething(then) {
[Link](x); [Link]('Doing something');
}); then();
}

Examples with Asynchronous Functions // Do something, then execute callback to log 'done'
doSomething(function () {
In jQuery, the $.getJSON() method to fetch JSON data is asynchronous. Therefore, passing code in a callback [Link]('Done');
makes sure that the code is called after the JSON is fetched. });

[Link] – JavaScript® Notes for Professionals 213 [Link] – JavaScript® Notes for Professionals 214
[Link]('Doing something else'); }, function onRejected(reason) {
[Link]("Rejected with reason " + reason);
// Outputs: });
// "Doing something"
// "Done"
Here then function then accepts two callback functions, onFulfilled and onRejected. Furthermore, only one of
// "Doing something else"
these two callback functions is actually called.

The doSomething() method above executes synchronously with the callback - execution blocks until doSomething() What's more interesting is that the function then returns before either of the callbacks are called. Hence, a callback
returns, ensuring that the callback is executed before the interpreter moves on. function may be called even after the original function has returned.

Callbacks can also be used to execute code asynchronously:


Section 29.4: Callbacks and `this`
doSomethingAsync(then) {
setTimeout(then, 1000); Often when using a callback you want access to a specific context.
[Link]('Doing something asynchronously');
} function SomeClass(msg, elem) {
[Link] = msg;
doSomethingAsync(function() { [Link]('click', function() {
[Link]('Done'); [Link]([Link]); // <= will fail because "this" is undefined
}); });
}
[Link]('Doing something else');
var s = new SomeClass("hello", someElement);
// Outputs:
Solutions
// "Doing something asynchronously"
// "Doing something else" Use bind
// "Done"

The then callbacks are considered continuations of the doSomething() methods. Providing a callback as the last bind effectively generates a new function that sets this to whatever was passed to bind then calls the

instruction in a function is called a tail-call, which is optimized by ES2015 interpreters. original function.

Section 29.3: What is a callback? function SomeClass(msg, elem) {


[Link] = msg;
[Link]('click', function() {
This is a normal function call: [Link]([Link]);
}.bind(this)); // <=- bind the function to `this`
[Link]("Hello World!"); }

When you call a normal function, it does its job and then returns control back to the caller. Use arrow functions

However, sometimes a function needs to return control back to the caller in order to do its job: Arrow functions automatically bind the current this context.

[1,2,3].map(function double(x) { function SomeClass(msg, elem) {


return 2 * x; [Link] = msg;
}); [Link]('click',() => { // <=- arrow function binds `this`
[Link]([Link]);
In the above example, the function double is a callback for the function map because: });
}
1. The function double is given to the function map by the caller.
2. The function map needs to call the function double zero or more times in order to do its job.
Often you'd like to call a member function, ideally passing any arguments that were passed to the event on to the
Thus, the function map is essentially returning control back to the caller every time it calls the function double. function.
Hence, the name “callback”.
Solutions:
Functions may accept more than one callback:
Use bind

[Link](function onFulfilled(value) {
[Link]("Fulfilled with value " + value); function SomeClass(msg, elem) {

[Link] – JavaScript® Notes for Professionals 215 [Link] – JavaScript® Notes for Professionals 216
[Link] = msg; [1,2,3,4,5].forEach(x => [Link](x));
[Link]('click', [Link](this));
}
Here the callback function function(x){[Link](x)} is reduced to x=>[Link](x)
[Link] = function(event) {

};
[Link]([Link], [Link]); Section 29.6: Error handling and control-flow branching
Callbacks are often used to provide error handling. This is a form of control flow branching, where some
Use arrow functions and the rest operator
instructions are executed only when an error occurs:

function SomeClass(msg, elem) { const expected = true;


[Link] = msg;
[Link]('click', (...a) => [Link](...a)); function compare(actual, success, failure) {
} if (actual === expected) {
success();
[Link] = function(event) { } else {
[Link]([Link], [Link]); failure();
}; }
}

For DOM event listeners in particular you can implement the EventListener interface function onSuccess() {
[Link]('Value was expected');
function SomeClass(msg, elem) { }
[Link] = msg;
[Link]('click', this); function onFailure() {
} [Link]('Value was unexpected/exceptional');
}
[Link] = function(event) {
var fn = this[[Link]]; compare(true, onSuccess, onFailure);
if (fn) { compare(false, onSuccess, onFailure);
[Link](this, arguments);
} // Outputs:
}; // "Value was expected"
// "Value was unexpected/exceptional"
[Link] = function(event) {
[Link]([Link]); Code execution in compare() above has two possible branches: success when the expected and actual values are
}; the same, and error when they are different. This is especially useful when control flow should branch after some
asynchronous instruction:

Section 29.5: Callback using Arrow function function compareAsync(actual, success, failure) {
setTimeout(function () {
Using arrow function as callback function can reduce lines of code. compare(actual, success, failure)
}, 1000);
The default syntax for arrow function is }

() => {} compareAsync(true, onSuccess, onFailure);


compareAsync(false, onSuccess, onFailure);
[Link]('Doing something else');
This can be used as callbacks
// Outputs:
For example if we want to print all elements in an array [1,2,3,4,5] // "Doing something else"
// "Value was expected"
without arrow function, the code will look like this // "Value was unexpected/exceptional"

[1,2,3,4,5].forEach(function(x){ It should be noted, multiple callbacks do not have to be mutually exclusive – both methods could be called.
[Link](x);
Similarly, the compare() could be written with callbacks that are optional (by using a noop as the default value - see
}
Null Object pattern).

With arrow function, it can be reduced to

[Link] – JavaScript® Notes for Professionals 217 [Link] – JavaScript® Notes for Professionals 218
Chapter 30: Intervals and Timeouts Section 30.4: Removing intervals
[Link]() returns an IntervalID, which can be used to stop that interval from continuing to run. To
Section 30.1: Recursive setTimeout do this, store the return value of [Link]() in a variable and call clearInterval() with that variable as
the only argument:
To repeat a function indefinitely, setTimeout can be called recursively:
function waitFunc(){
function repeatingFunc() { [Link]("This will be logged every 5 seconds");
[Link]("It's been 5 seconds. Execute the function again."); }
setTimeout(repeatingFunc, 5000);
} var interval = [Link](waitFunc,5000);

setTimeout(repeatingFunc, 5000); [Link](function(){


clearInterval(interval);
Unlike setInterval, this ensures that the function will execute even if the function's running time is longer than the },32000);

specified delay. However, it does not guarantee a regular interval between function executions. This behaviour also
varies because an exception before the recursive call to setTimeout will prevent it from repeating again, while This will log This will be logged every 5 seconds every 5 seconds, but will stop it after 32 seconds. So it will log
setInterval would repeat indefinitely regardless of exceptions. the message 6 times.

Section 30.2: Intervals Section 30.5: Removing timeouts


[Link]() returns a TimeoutID, which can be used to stop that timeout from running. To do this, store
function waitFunc(){
[Link]("This will be logged every 5 seconds"); the return value of [Link]() in a variable and call clearTimeout() with that variable as the only
} argument:

[Link](waitFunc,5000); function waitFunc(){


[Link]("This will not be logged after 5 seconds");

Section 30.3: Intervals }


function stopFunc(){
clearTimeout(timeout);
Standard }

You don't need to create the variable, but it's a good practice as you can use that variable with clearInterval to stop var timeout = [Link](waitFunc,5000);
the currently running interval. [Link](stopFunc,3000);

var int = setInterval("doSomething()", 5000 ); /* 5 seconds */ This will not log the message because the timer is stopped after 3 seconds.
var int = setInterval(doSomething, 5000 ); /* same thing, no quotes, no parens */

Section 30.6: setTimeout, order of operations, clearTimeout


If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond
the first two to setInterval. setTimeout

Without overlapping Executes a function, after waiting a specified number of milliseconds.


used to delay the execution of a function.
setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what. Even if the function
doSomething takes long than 5 seconds to run. That can create issues. If you just want to make sure there is that Syntax : setTimeout(function, milliseconds) or [Link](function, milliseconds)
pause in between runnings of doSomething, you can do this:
Example : This example outputs "hello" to the console after 1 second. The second parameter is in milliseconds, so
(function(){ 1000 = 1 sec, 250 = 0.25 sec, etc.

doSomething(); setTimeout(function() {
[Link]('hello');
setTimeout([Link], 5000); }, 1000);

})()
Problems with setTimeout

if you're using the setTimeout method in a for loop :

[Link] – JavaScript® Notes for Professionals 219 [Link] – JavaScript® Notes for Professionals 220
for (i = 0; i < 3; ++i) {
setTimeout(function(){ Chapter 31: Regular expressions
[Link](i);
}, 500); Flags Details
} g global. All matches (don't return on the first match).
m multi-line. Causes ^ & $ to match the begin/end of each line (not only begin/end of string).
This will output the value 3 three times, which is not correct.
i insensitive. Case insensitive match (ignores case of [a-zA-Z]).
Workaround of this problem : u unicode : Pattern strings are treated as UTF-16. Also causes escape sequences to match Unicode characters.
sticky: matches only from the index indicated by the lastIndex property of this regular expression in the
y
for (i = 0; i < 3; ++i) { target string (and does not attempt to match from any later indexes).
setTimeout(function(j){
[Link](i);
}(i), 1000); Section 31.1: Creating a RegExp Object
}
Standard Creation
It will output the value 0,1,2. Here, we’re passing the i into the function as a parameter(j).
It is recommended to use this form only when creating regex from dynamic variables.
Order of operations
Use when the expression may change or the expression is user generated.
Additionally though, due to the fact that JavaScript is single threaded and uses a global event loop, setTimeout can
var re = new RegExp(".*");
be used to add an item to the end of the execution queue by calling setTimeout with zero delay. For example:

With flags:
setTimeout(function() {
[Link]('world');
}, 0); var re = new RegExp(".*", "gmi");

[Link]('hello'); With a backslash: (this must be escaped because the regex is specified with a string)

Will actually output: var re = new RegExp("\\w*");

hello
Static initialization
world

Use when you know the regular expression will not change, and you know what the expression is before runtime.
Also, zero milliseconds here does not mean the function inside the setTimeout will execute immediately. It will take
slightly more than that depending upon the items to be executed remaining in the execution queue. This one is just var re = /.*/;
pushed to the end of the queue.
With flags:
Cancelling a timeout

var re = /.*/gmi;
clearTimeout() : stops the execution of the function specified in setTimeout()

Syntax : clearTimeout(timeoutVariable) or [Link](timeoutVariable) With a backslash: (this should not be escaped because the regex is specified in a literal)

Example : var re = /\w*/;

var timeout = setTimeout(function() {


[Link]('hello');
Section 31.2: RegExp Flags
}, 1000);
There are several flags you can specify to alter the RegEx behaviour. Flags may be appended to the end of a regex
clearTimeout(timeout); // The timeout will no longer be executed literal, such as specifying gi in /test/gi, or they may be specified as the second argument to the RegExp
constructor, as in new RegExp('test', 'gi').

g - Global. Finds all matches instead of stopping after the first.

i - Ignore case. /[a-z]/i is equivalent to /[a-zA-Z]/.

[Link] – JavaScript® Notes for Professionals 221 [Link] – JavaScript® Notes for Professionals 222
m - Multiline. ^ and $ match the beginning and end of each line respectively treating \n and \r as delimiters instead "string".match(...
of simply the beginning and end of the entire string. "string".replace(...
"string".split(...
Version ≥ 6
"string".search(...
u - Unicode. If this flag is not supported you must match specific Unicode characters with \uXXXX where XXXX is the
Match with RegExp
character's value in hexadecimal.
[Link]("string".match(/[i-n]+/));
[Link]("string".match(/(r)[i-n]+/));
y - Finds all consecutive/adjacent matches.

Expected output

Section 31.3: Check if string contains pattern using .test()


Array ["in"]
var re = /[a-z]+/; Array ["rin", "r"]
if ([Link]("foo")) {
[Link]("Match exists.");
}
Replace with RegExp
[Link]("string".replace(/[i-n]+/, "foo"));
The test method performs a search to see if a regular expression matches a string. The regular expression [a-z]+
will search for one or more lowercase letters. Since the pattern matches the string, “match exists” will be logged to
Expected output
the console.

Section 31.4: Matching With .exec() strfoog

Match Using .exec()


Split with RegExp
[Link](string) returns an array of captures, or null if there was no match. [Link]("stringstring".split(/[i-n]+/));

var re = /([0-9]+)[a-z]+/; Expected output


var match = [Link]("foo123bar");

[Link] is 3, the (zero-based) location of the match. Array ["str", "gstr", "g"]

match[0] is the full match string.


Search with RegExp
match[1] is the text corresponding to the first captured group. match[n] would be the value of the nth captured
.search() returns the index at which a match is found or -1.
group.

[Link]("string".search(/[i-n]+/));
Loop Through Matches Using .exec()
[Link]("string".search(/[o-q]+/));
var re = /a/g;
var result;
Expected output
while ((result = [Link]('barbatbaz')) !== null) {
[Link]("found '" + result[0] + "', next exec starts at index '" + [Link] + "'");
}
3
-1
Expected output

found 'a', next exec starts at index '2' Section 31.6: RegExp Groups
found 'a', next exec starts at index '5'
JavaScript supports several types of group in its Regular Expressions, capture groups, non-capture groups and look-
found 'a', next exec starts at index '8'
aheads. Currently, there is no look-behind support.

Section 31.5: Using RegExp With Strings Capture

Sometimes the desired match relies on its context. This means a simple RegExp will over-find the piece of the String
The String object has the following methods that accept regular expressions as arguments.

[Link] – JavaScript® Notes for Professionals 223 [Link] – JavaScript® Notes for Professionals 224
that is of interest, so the solution is to write a capture group (pattern). The captured data can then be referenced }
});
as...
// will return Start string End

String replacement "$n" where n is the n th capture group (starting from 1)


The n th argument in a callback function One line template library
If the RegExp is not flagged g, the n+1 th item in a returned [Link] Array
let data = {name: 'John', surname: 'Doe'}
If the RegExp is flagged g, [Link] discards captures, use [Link] instead
"My name is {surname}, {name} {surname}".replace(/(?:{(.+?)})/g, x => data[[Link](1,-1)]);

Say there is a String where all + signs need to be replaced with a space, but only if they follow a letter character. This // "My name is Doe, John Doe"
means a simple match would include that letter character and it would also be removed. Capturing it is the solution
as it means the matched letter can be preserved.
Section 31.8: Using [Link]() with parentheses regex to
let str = "aa+b+cc+1+2", extract matches of a string
re = /([a-z])\+/g;
Sometimes you doesn't want to simply replace or remove the string. Sometimes you want to extract and process
// String replacement matches. Here an example of how you manipulate matches.
[Link](re, '$1 '); // "aa b cc 1+2"
// Function replacement What is a match ? When a compatible substring is found for the entire regex in the string, the exec command
[Link](re, (m, $1) => $1 + ' '); // "aa b cc 1+2"
produce a match. A match is an array compose by firstly the whole substring that matched and all the parenthesis
in the match.
Non-Capture
Imagine a html string :
Using the form (?:pattern), these work in a similar way to capture groups, except they do not store the contents
of the group after the match. <html>
<head></head>
They can be particularly useful if other data is being captured which you don't want to move the indices of, but <body>
need to do some advanced pattern matching such as an OR <h1>Example</h1>
<p>Look at this great link : <a href="[Link]
[Link]
let str = "aa+b+cc+1+2",
Copyright <a href="[Link]
re = /(?:\b|c)([a-z])\+/g;
</body>

[Link](re, '$1 '); // "aa+b c 1+2"


You want to extract and get all the links inside an a tag. At first, here the regex you write :

Look-Ahead var re = /<a[^>]*href="https?:\/\/.*"[^>]*>[^<]*<\/a>/g;

If the desired match relies on something which follows it, rather than matching that and capturing it, it is possible to
But now, imagine you want the href and the anchor of each link. And you want it together. You can simply add a
use a look-ahead to test for it but not include it in the match. A positive look-ahead has the form (?=pattern), a
new regex in for each match OR you can use parentheses :
negative look-ahead (where the expression match only happens if the look-ahead pattern did not match) has the
form (?!pattern)
var re = /<a[^>]*href="(https?:\/\/.*)"[^>]*>([^<]*)<\/a>/g;
var str = '<html>\n <head></head>\n <body>\n <h1>Example</h1>\n <p>Look at this
let str = "aa+b+cc+1+2", great link: <a href="[Link] [Link]
re = /\+(?=[a-z])/g; Copyright <a href="[Link] </body>\';\n';
var m;
[Link](re, ' '); // "aa b cc+1+2" var links = [];

Section 31.7: Replacing string match with a callback function while ((m = [Link](str)) !== null) {
if ([Link] === [Link]) {
[Link]++;
String#replace can have a function as its second argument so you can provide a replacement based on some }
logic. [Link](m[0]); // The all substring
[Link](m[1]); // The href subpart
"Some string Some".replace(/Some/g, (match, startIndex, wholeString) => { [Link](m[2]); // The anchor subpart
if(startIndex == 0){
return 'Start'; [Link]({
} else { match : m[0], // the entire match
return 'End'; href : m[1], // the first parenthesis => (https?:\/\/.*)

[Link] – JavaScript® Notes for Professionals 225 [Link] – JavaScript® Notes for Professionals 226
}
anchor : m[2],
});
// the second ([^<]*)
Chapter 32: Cookies
At the end of the loop, you have an array of link with anchor and href and you can use it to write markdown for
Section 32.1: Test if cookies are enabled
example : If you want to make sure cookies are enabled before using them, you can use [Link]:

[Link](function(link) { if ([Link] === false)


[Link]('[%s](%s)', [Link], [Link]); {
}); alert("Error: cookies not enabled!");
}
To go further :
Note that on older browsers [Link] may not exist and be undefined. In those cases you won't
Nested parenthesis detect that cookies are not enabled.

Section 32.2: Adding and Setting Cookies


The following variables set up the below example:

var COOKIE_NAME = "Example Cookie"; /* The cookie's name. */


var COOKIE_VALUE = "Hello, world!"; /* The cookie's value. */
var COOKIE_PATH = "/foo/bar"; /* The cookie's path. */
var COOKIE_EXPIRES; /* The cookie's expiration date (config'd below). */

/* Set the cookie expiration to 1 minute in future (60000ms = 1 minute). */


COOKIE_EXPIRES = (new Date([Link]() + 60000)).toUTCString();

[Link] +=
COOKIE_NAME + "=" + COOKIE_VALUE
+ "; expires=" + COOKIE_EXPIRES
+ "; path=" + COOKIE_PATH;

Section 32.3: Reading cookies


var name = name + "=",
cookie_array = [Link](';'),
cookie_value;
for(var i=0;i<cookie_array.length;i++) {
var cookie=cookie_array[i];
while([Link](0)==' ')
cookie = [Link](1,[Link]);
if([Link](name)==0)
cookie_value = [Link]([Link],[Link]);
}

This will set cookie_value to the value of the cookie, if it exists. If the cookie is not set, it will set cookie_value to
null

Section 32.4: Removing cookies


var expiry = new Date();
[Link]([Link]() - 3600);
[Link] = name + "=; expires=" + [Link]() + "; path=/"

This will remove the cookie with a given name.

[Link] – JavaScript® Notes for Professionals 227 [Link] – JavaScript® Notes for Professionals 228
Chapter 33: Web Storage // Clear storage
[Link]();

Parameter Description Example:


name The key/name of the item
value The value of the item // Store values (Strings, Numbers)
[Link] = "Hello";
[Link] = 2017;
Section 33.1: Using localStorage
// Store complex data (Objects, Arrays)
The localStorage object provides persistent (but not permanent - see limits below) key-value storage of strings. Any var user = {name:"John", surname:"Doe", books:["A","B"]};
[Link] = [Link]( user );
changes are immediately visible in all other windows/frames from the same origin. The stored values persistent
indefinitely unless the user clears saved data or configures an expiration limit. localStorage uses a map-like // Important: Numbers are stored as String
interface for getting and setting values. [Link]( typeof [Link] ); // String

[Link]('name', "John Smith"); // Retrieve values


[Link]([Link]('name')); // "John Smith" var someYear = [Link]; // "2017"

[Link]('name'); // Retrieve complex data


[Link]([Link]('name')); // null var userData = [Link]( [Link] );
var userName = [Link]; // "John"

If you want to store simple structured data, you can use JSON to serialize it to and from strings for storage.
// Remove specific data
delete [Link];
var players = [{name: "Tyler", score: 22}, {name: "Ryan", score: 41}];
[Link]('players', [Link](players)); // Clear (delete) all stored data
[Link]();
[Link]([Link]([Link]('players')));
// [ Object { name: "Tyler", score: 22 }, Object { name: "Ryan", score: 41 } ]

localStorage limits in browsers Section 33.3: Storage events


Mobile browsers: Whenever a value in set in localStorage, a storage event will be dispatched on all other windows from the same
origin. This can be used to synchronize state between different pages without reloading or communicating with a
Browser Google Chrome Android Browser Firefox iOS Safari server. For example, we can reflect the value of an input element as paragraph text in another window:
Version 40 4.3 34 6-8
First Window
Space available 10MB 2MB 10MB 5MB
var input = [Link]('input');
[Link](input);
Desktop browsers:

[Link] = [Link]('user-value');
Browser Google Chrome Opera Firefox Safari Internet Explorer
Version 40 27 34 6-8 9-11 [Link] = function(event) {
Space available 10MB 10MB 10MB 5MB 10MB [Link]('user-value', [Link]);
};

Section 33.2: Simpler way of handling Storage Second Window


var output = [Link]('p');
localStorage, sessionStorage are JavaScript Objects and you can treat them as such. [Link](output);
Instead of using Storage Methods like .getItem(), .setItem(), etc… here's a simpler alternative:
[Link] = [Link]('user-value');

// Set
[Link]('storage', function(event) {
[Link] = "Hi!"; // Same as: [Link]("greet", "Hi!");
if ([Link] === 'user-value') {
[Link] = [Link];
// Get
}
[Link]; // Same as: [Link]("greet");
});

// Remove item
delete [Link]; // Same as: [Link]("greet"); Notes

[Link] – JavaScript® Notes for Professionals 229 [Link] – JavaScript® Notes for Professionals 230
Event is not fired or catchable under Chrome, Edge and Safari if domain was modified through script. Section 33.5: localStorage length
First window [Link] property returns an integer number indicating the number of elements in the localStorage
// page url: [Link]
[Link] = '[Link]'; Example:

var input = [Link]('input'); Set Items


[Link](input);
[Link]('StackOverflow', 'Documentation');
[Link] = [Link]('user-value');
[Link]('font', 'Helvetica');
[Link]('image', '[Link]');
[Link] = function(event) {
[Link]('user-value', [Link]);
}; Get length

Second Window
[Link]; // 3
// page url: [Link]
[Link] = '[Link]';
Section 33.6: Error conditions
var output = [Link]('p');
[Link](output); Most browsers, when configured to block cookies, will also block localStorage. Attempts to use it will result in an
exception. Do not forget to manage these cases.
// Listener will never called under Chrome(53), Edge and Safari(10.0).
[Link]('storage', function(event) {
if ([Link] === 'user-value') { var video = [Link]('video')
[Link] = [Link]; try {
} [Link] = [Link]('volume')
}); } catch (error) {
alert('If you\'d like your volume saved, turn on cookies')
}
Section 33.4: sessionStorage [Link]()

The sessionStorage object implements the same Storage interface as localStorage. However, instead of being If error were not handled, program would stop functioning properly.
shared with all pages from the same origin, sessionStorage data is stored separately for every window/tab. Stored
data persists between pages in that window/tab for as long as it's open, but is visible nowhere else. Section 33.7: Clearing storage
var audio = [Link]('audio'); To clear the storage, simply run

// Maintain the volume if the user clicks a link then navigates back here.
[Link]();
[Link] = Number([Link]('volume') || 1.0);
[Link] = function(event) {

};
[Link]('volume', [Link]); Section 33.8: Remove Storage Item
To remove a specific item from the browser Storage (the opposite of setItem) use removeItem
Save data to sessionStorage
[Link]("greet");
[Link]('key', 'value');
Example:
Get saved data from sessionStorage
[Link]("greet", "hi");
var data = [Link]('key'); [Link]("greet");

Remove saved data from sessionStorage [Link]( [Link]("greet") ); // null

[Link]('key') (Same applies for sessionStorage)

[Link] – JavaScript® Notes for Professionals 231 [Link] – JavaScript® Notes for Professionals 232
Chapter 34: Data attributes Chapter 35: JSON
Section 34.1: Accessing data attributes Parameter Details
[Link] Parse a JSON string
Using the dataset property input(string) JSON string to be parsed.
reviver(function) Prescribes a transformation for the input JSON string.
The new dataset property allows access (for both reading and writing) to all data attributes data-* on any element.
[Link] Serialize a serializable value

<p>Countries:</p>
value(string) Value to be serialized according to the JSON specification.
<ul> replacer(function or String[] or
Selectively includes certain properties of the value object.
<li id="C1" data-id="US" data-dial-code="1">USA</li> Number[])
<li id="C2" data-id="CA" data-dial-code="1">Canada</li> If a number is provided, then space number of whitespaces will be
<li id="C3" data-id="FF" data-dial-code="3">France</li> space(String or Number) inserted of readability. If a string is provided, the string (first 10
</ul> characters) will be used as whitespaces.
<button type="button" Country Details</button>
<script>
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write
function showDetails(item) {
var msg = [Link] and easy for machines to parse and generate. It is important to realize that, in JavaScript, JSON is a string and not an
+ "\r\nISO ID: " + [Link] object.
+ "\r\nDial Code: " + [Link];
alert(msg); A basic overview can be found on the [Link] website which also contains links to implementations of the standard
}
in many different programming languages.
function correctDetails(item) {
var item = [Link]("C3"); Section 35.1: JSON versus JavaScript literals
[Link] = "FR";
[Link] = "33"; JSON stands for "JavaScript Object Notation", but it's not JavaScript. Think of it as just a data serialization format that
} happens to be directly usable as a JavaScript literal. However, it is not advisable to directly run (i.e. through eval())
</script>
JSON that is fetched from an external source. Functionally, JSON isn't very different from XML or YAML – some
confusion can be avoided if JSON is just imagined as some serialization format that looks very much like JavaScript.
Note: The dataset property is only supported in modern browsers and it's slightly slower than the getAttribute
and setAttribute methods which are supported by all browsers. Even though the name implies just objects, and even though the majority of use cases through some kind of API
always happen to be objects and arrays, JSON is not for just objects or arrays. The following primitive types are
Using the getAttribute & setAttribute methods
supported:
If you want to support the older browsers before HTML5, you can use the getAttribute and setAttribute
String (e.g. "Hello World!")
methods which are used to access any attribute including the data attributes. The two functions in the example
Number (e.g. 42)
above can be written this way:
Boolean (e.g. true)
The value null
<script>
function showDetails(item) {
var msg = [Link] undefined is not supported in the sense that an undefined property will be omitted from JSON upon serialization.
+ "\r\nISO ID: " + [Link]("data-id") Therefore, there is no way to deserialize JSON and end up with a property whose value is undefined.
+ "\r\nDial Code: " + [Link]("data-dial-code");
alert(msg); The string "42" is valid JSON. JSON doesn't always have to have an outer envelope of "{...}" or "[...]".
}
While some JSON is also valid JavaScript and some JavaScript is also valid JSON, there are some subtle differences
function correctDetails(item) {
between both languages and neither language is a subset of the other.
var item = [Link]("C3");
[Link]("id", "FR");
Take the following JSON string as an example:
[Link]("data-dial-code", "33");
}
</script> {"color": "blue"}

This can be directly inserted into JavaScript. It will be syntactically valid and will yield the correct value:

const skin = {"color": "blue"};

[Link] – JavaScript® Notes for Professionals 233 [Link] – JavaScript® Notes for Professionals 234
However, we know that "color" is a valid identifier name and the quotes around the property name can be omitted: Version ≥ 6
const jsonString = '[{"name":"John","score":51},{"name":"Jack","score":17}]';
const skin = {color: "blue"};
const data = [Link](jsonString, (key, value) =>
key === 'name' ? [Link]() : value
We also know that we can use single quotes instead of double quotes: );

const skin = {'color': 'blue'};


This produces the following result:

But, if we were to take both of these literals and treat them as JSON, neither will be syntactically valid JSON: [
{
{color: "blue"} 'name': 'JOHN',
{'color': 'blue'} 'score': 51
},
JSON strictly requires all property names to be double quoted and string values to be double quoted as well. {
'name': 'JACK',
'score': 17
It's common for JSON-newcomers to attempt to use code excerpts with JavaScript literals as JSON, and scratch their
}
heads about the syntax errors they are getting from the JSON parser. ]

More confusion starts arising when incorrect terminology is applied in code or in conversation.
This is particularly useful when data must be sent that needs to be serialized/encoded when being transmitted with
A common anti-pattern is to name variables that hold non-JSON values as "json": JSON, but one wants to access it deserialized/decoded. In the following example, a date was encoded to its ISO 8601
representation. We use the reviver function to parse this in a JavaScript Date.
fetch(url).then(function (response) {
Version ≥ 5.1
const json = [Link]([Link]); // Confusion ensues!
var jsonString = '{"date":"2016-01-04T23:00:00.000Z"}';
// We're done with the notion of "JSON" at this point,
// but the concept stuck with the variable name. var data = [Link](jsonString, function (key, value) {
}); return (key === 'date') ? new Date(value) : value;
});
Version ≥ 6
In the above example, [Link] is a JSON string that is returned by some API. JSON stops at the HTTP
const jsonString = '{"date":"2016-01-04T23:00:00.000Z"}';
response domain. The variable with the "json" misnomer holds just a JavaScript value (could be an object, an array,
or even a simple number!) const data = [Link](jsonString, (key, value) =>
key === 'date' ? new Date(value) : value
A less confusing way to write the above is: );

fetch(url).then(function (response) { It is important to make sure the reviver function returns a useful value at the end of each iteration. If the reviver
const value = [Link]([Link]);
function returns undefined, no value or the execution falls off towards the end of the function, the property is
// We're done with the notion of "JSON" at this point. deleted from the object. Otherwise, the property is redefined to be the return value.
// You don't talk about JSON after parsing JSON.
});
Section 35.3: Serializing a value
Developers also tend to throw the phrase "JSON object" around a lot. This also leads to confusion. Because as A JavaScript value can be converted to a JSON string using the [Link] function.
mentioned above, a JSON string doesn't have to hold an object as a value. "JSON string" is a better term. Just like
"XML string" or "YAML string". You get a string, you parse it, and you end up with a value. [Link](value[, replacer[, space]])

Section 35.2: Parsing with a reviver function 1. value The value to convert to a JSON string.

/* Boolean */ [Link](true) // 'true'


A reviver function can be used to filter or transform the value being parsed.
/* Number */ [Link](12) // '12'
/* String */ [Link]('foo') // '"foo"'
Version ≥ 5.1
/* Object */ [Link]({}) // '{}'
var jsonString = '[{"name":"John","score":51},{"name":"Jack","score":17}]'; [Link]({foo: 'baz'}) // '{"foo": "baz"}'
/* Array */ [Link]([1, true, 'foo']) // '[1, true, "foo"]'
var data = [Link](jsonString, function reviver(key, value) { /* Date */ [Link](new Date()) // '"2016-08-06T17:25:23.588Z"'
return key === 'name' ? [Link]() : value; /* Symbol */ [Link]({x:Symbol()}) // '{}'
});

[Link] – JavaScript® Notes for Professionals 235 [Link] – JavaScript® Notes for Professionals 236
2. replacer A function that alters the behaviour of the stringification process or an array of String and Number speed: [Link]
};
objects that serve as a whitelist for filtering the properties of the value object to be included in the JSON
};
string. If this value is null or is not provided, all properties of the object are included in the resulting JSON
string. [Link] = function(data) {
return new Car([Link], [Link]);
// replacer as a function };
function replacer (key, value) { Version ≥ 6
// Filtering out properties
class Car {
if (typeof value === "string") {
constructor(color, speed) {
return
[Link] = color;
}
[Link] = speed;
return value
this.id_ = [Link]();
}
}
var foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7 }
toJSON() {
[Link](foo, replacer)
return {
// -> '{"week": 45, "month": 7}'
$type: '[Link]',
// replacer as an array color: [Link],
[Link](foo, ['foundation', 'week', 'month']) speed: [Link]
// -> '{"foundation": "Mozilla", "week": 45, "month": 7}' };
// only the `foundation`, `week`, and `month` properties are kept }

3. space For readability, the number of spaces used for indentation may be specified as the third parameter. static fromJSON(data) {
return new Car([Link], [Link]);
[Link]({x: 1, y: 1}, null, 2) // 2 space characters will be used for indentation }
/* output: }
{
var userJson = [Link]({
'x': 1,
name: "John",
'y': 1
car: new Car('red', 'fast')
}
});
*/

This produces the a string with the following content:


Alternatively, a string value can be provided to use for indentation. For example, passing '\t' will cause the tab
character to be used for indentation.
{"name":"John","car":{"$type":"[Link]","color":"red","speed":"fast"}}

[Link]({x: 1, y: 1}, null, '\t') var userObject = [Link](userJson, function reviver(key, value) {
/* output: return (value && value.$type === '[Link]') ? [Link](value) : value;
{ });
'x': 1,
'y': 1 This produces the following object:
}
*/
{
name: "John",
Section 35.4: Serializing and restoring class instances car: Car {
color: "red",
speed: "fast",
You can use a custom toJSON method and reviver function to transmit instances of your own class in JSON. If an
id_: 0.19349242527065402
object has a toJSON method, its result will be serialized instead of the object itself. }
}
Version < 6
function Car(color, speed) {
[Link] = color; Section 35.5: Serializing with a replacer function
[Link] = speed;
} A replacer function can be used to filter or transform values being serialized.

[Link] = function() {
const userRecords = [
return {
{name: "Joe", points: 14.9, level: 31.5},
$type: '[Link]',
{name: "Jane", points: 35.5, level: 74.4},
color: [Link],
{name: "Jacob", points: 18.5, level: 41.2},

[Link] – JavaScript® Notes for Professionals 237 [Link] – JavaScript® Notes for Professionals 238
];
{name: "Jessie", points: 15.1, level: 28.1},
Chapter 36: AJAX
// Remove names and round numbers to integers to anonymize records before sharing
AJAX stands for "Asynchronous JavaScript and XML". Although the name includes XML, JSON is more often used due
const anonymousReport = [Link](userRecords, (key, value) =>
key === 'name' to its simpler formatting and lower redundancy. AJAX allows the user to communicate with external resources
? undefined without reloading the webpage.
: (typeof value === 'number' ? [Link](value) : value)
);
Section 36.1: Sending and Receiving JSON Data via POST
This produces the following string: Version ≥ 6

'[{"points":14,"level":31},{"points":35,"level":74},{"points":18,"level":41},{"points":15,"level":2 Fetch request promises initially return Response objects. These will provide response header information, but they
8}]' don't directly include the response body, which may not have even loaded yet. Methods on the Response object
such as .json() can be used to wait for the response body to load, then parse it.

Section 35.6: Parsing a simple JSON string const requestData = {


method : 'getUsers'
The [Link]() method parses a string as JSON and returns a JavaScript primitive, array or object:
};

const array = [Link]('[1, 2, "c", "d", {"e": false}]'); const usersPromise = fetch('/api', {
[Link](array); // logs: [1, 2, "c", "d", {e: false}] method : 'POST',
body : [Link](requestData)

Section 35.7: Cyclic object values }).then(response => {


if (![Link]) {
throw new Error("Got non-2XX response from API server.");
Not all objects can be converted to a JSON string. When an object has cyclic self-references, the conversion will fail. }
return [Link]();
This is typically the case for hierarchical data structures where parent and child both reference each other: }).then(responseData => {
return [Link];
const world = { });
name: 'World',
regions: [] [Link](users => {
}; [Link]("Known users: ", users);
}, error => {
[Link]({ [Link]("Failed to fetch users due to error: ", error);
name: 'North America', });
parent: 'America'
});
[Link]([Link](world)); Section 36.2: Add an AJAX preloader
// {"name":"World","regions":[{"name":"North America","parent":"America"}]}
Here's a way to show a GIF preloader while an AJAX call is executing. We need to prepare our add and remove
[Link]({ preloader functions:
name: 'Asia',
parent: world function addPreloader() {
}); // if the preloader doesn't already exist, add one to the page
if(![Link]('#preloader')) {
[Link]([Link](world)); var preloaderHTML = '<img id="preloader" src="[Link] />';
// Uncaught TypeError: Converting circular structure to JSON [Link]('body').innerHTML += preloaderHTML;
}
As soon as the process detects a cycle, the exception is raised. If there were no cycle detection, the string would be }
infinitely long.
function removePreloader() {
// select the preloader element
var preloader = [Link]('#preloader');
// if it exists, remove it from the page
if(preloader) {
[Link]();
}
}

[Link] – JavaScript® Notes for Professionals 239 [Link] – JavaScript® Notes for Professionals 240
Now we're going to look at where to use these functions. [Link](message);
[Link] = 'red';
var request = new XMLHttpRequest();
[Link] = String(error);
});
Inside the onreadystatechange function you should have an if statement with condition: [Link] == 4
&& [Link] == 200.
Section 36.4: Using GET with parameters
If true: the request is finished and response is ready that's where we'll use removePreloader().
This function runs an AJAX call using GET allowing us to send parameters (object) to a file (string) and launch a
Else if false: the request is still in progress, in this case we'll run the function addPreloader() callback (function) when the request has been ended.

[Link] = function() { function ajax(file, params, callback) {

if([Link] == 4 && [Link] == 200) { var url = file + '?';


// the request has come to an end, remove the preloader
removePreloader(); // loop through object and assemble the url
} else { var notFirst = false;
// the request isn't finished, add the preloader for (var key in params) {
addPreloader() if ([Link](key)) {
} url += (notFirst ? '&' : '') + key + "=" + params[key];
}
}; notFirst = true;
}
[Link]('GET', your_file.php, true);
[Link](); // create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
[Link] = function() {
Section 36.3: Displaying the top JavaScript questions of the if ([Link] == 4 && [Link] == 200) {
month from Stack Overflow's API callback([Link]);
}
};
We can make an AJAX request to Stack Exchange's API to retrieve a list of the top JavaScript questions for the
[Link]('GET', url, true);
month, then present them as a list of links. If the request fails or the returns an API error, our promise error [Link]();
handling displays the error instead. }

Version ≥ 6
Here's how we use it:
View live results on HyperWeb.
const url =
ajax('[Link]', {type:"Volvo", model:"300", color:"purple"}, function(response) {
'[Link] +
// add here the code to be executed when data comes back to this page
'&tagged=javascript&sort=month&filter=unsafe&key=gik4BOCMC7J9doavgYteRw((';
// for example [Link](response) will show the AJAX response in console
});
fetch(url).then(response => [Link]()).then(data => {
if (data.error_message) {
throw new Error(data.error_message); And the following shows how to retrieve the url parameters in [Link]:
}
if(isset($_REQUEST['type'], $_REQUEST['model'], $_REQUEST['color'])) {
const list = [Link]('ol'); // they are set, we can use them !
[Link](list); $response = 'The color of your car is ' . $_REQUEST['color'] . '. ';
$response .= 'It is a ' . $_REQUEST['type'] . ' model ' . $_REQUEST['model'] . '!';
for (const {title, link} of [Link]) { echo $response;
const entry = [Link]('li'); }
const hyperlink = [Link]('a');
[Link](hyperlink);
If you had [Link](response) in callback function the result in console would have been:
[Link](entry);

[Link] = title;
The color of your car is purple. It is a Volvo model 300!
[Link] = link;
}
}).then(null, error => {
const message = [Link]('pre');

[Link] – JavaScript® Notes for Professionals 241 [Link] – JavaScript® Notes for Professionals 242
Section 36.5: Check if a file exists via a HEAD request Chapter 37: Enumerations
This function executes an AJAX request using the HEAD method allowing us to check whether a file exists in the
directory given as an argument. It also enables us to launch a callback for each case (success, failure). Section 37.1: Enum definition using [Link]()
Version ≥ 5.1
function fileExists(dir, successCallback, errorCallback) {
var xhttp = new XMLHttpRequest;
JavaScript does not directly support enumerators but the functionality of an enum can be mimicked.
/* Check the status code of the request */
[Link] = function() { // Prevent the enum from being changed
return ([Link] !== 404) ? successCallback : errorCallback; const TestEnum = [Link]({
}; One:1,
Two:2,
/* Open and send the request */ Three:3
[Link]('head', dir, false); });
[Link](); // Define a variable with a value from the enum
}; var x = [Link];
// Prints a value according to the variable's enum value
switch(x) {
Section 36.6: Using GET and no parameters case [Link]:
[Link]("111");
var xhttp = new XMLHttpRequest(); break;
[Link] = function () {
if ([Link] === [Link] && [Link] === 200) { case [Link]:
//parse the response in [Link]; [Link]("222");
} }
};
[Link]("GET", "ajax_info.txt", true); The above enumeration definition, can also be written as follows:
[Link]();
Version ≥ 6 var TestEnum = { One: 1, Two: 2, Three: 3 }
[Link](TestEnum);
The fetch API is a newer promise-based way to make asynchronous HTTP requests.
After that you can define a variable and print like before.
fetch('/').then(response => [Link]()).then(text => {
[Link]("The home page is " + [Link] + " characters long.");
});
Section 37.2: Alternate definition
Section 36.7: Listening to AJAX events at a global level The [Link]() method is available since version 5.1. For older versions, you can use the following code (note
that it also works in versions 5.1 and later):
// Store a reference to the native method
let open = [Link]; var ColorsEnum = {
WHITE: 0,
// Overwrite the native method GRAY: 1,
[Link] = function() { BLACK: 2
// Assign an event listener }
[Link]("load", event => [Link](XHR), false); // Define a variable with a value from the enum
// Call the stored reference to the native method var currentColor = [Link];
[Link](this, arguments);
};
Section 37.3: Printing an enum variable
After defining an enum using any of the above ways and setting a variable, you can print both the variable's value
as well as the corresponding name from the enum for the value. Here's an example:

// Define the enum


var ColorsEnum = { WHITE: 0, GRAY: 1, BLACK: 2 }
[Link](ColorsEnum);
// Define the variable and assign a value
var color = [Link];

[Link] – JavaScript® Notes for Professionals 243 [Link] – JavaScript® Notes for Professionals 244
if(color == [Link]) { "One",
[Link](color); // This will print "2" "Two",
var ce = ColorsEnum; "Three"
for (var name in ce) { ];
if (ce[name] == [Link]) enumObj = {};
[Link](name); // This will print "BLACK" [Link]((item, index)=>enumObj[item] = index + 1);
}
} // Do not allow the object to be changed
[Link](enumObj);
return enumObj;
Section 37.4: Implementing Enums Using Symbols }();

As ES6 introduced Symbols, which are both unique and immutable primitive values that may be used as the key [Link]([Link]); // 1 will be logged
of an Object property, instead of using strings as possible values for an enum, it's possible to use symbols.
var x = [Link];

// Simple symbol
switch(x) {
const newSymbol = Symbol();
case [Link]:
typeof newSymbol === 'symbol' // true
[Link]("111");
break;
// A symbol with a label
const anotherSymbol = Symbol("label");
case [Link]:
[Link]("222"); // 222 will be logged
// Each symbol is unique
break;
const yetAnotherSymbol = Symbol("label");
}
yetAnotherSymbol === anotherSymbol; // false

const Regnum_Animale = Symbol();


const Regnum_Vegetabile = Symbol();
const Regnum_Lapideum = Symbol();

function describe(kingdom) {

switch(kingdom) {

case Regnum_Animale:
return "Animal kingdom";
case Regnum_Vegetabile:
return "Vegetable kingdom";
case Regnum_Lapideum:
return "Mineral kingdom";
}

describe(Regnum_Vegetabile);
// Vegetable kingdom

The Symbols in ECMAScript 6 article covers this new primitive type more in detail.

Section 37.5: Automatic Enumeration Value


Version ≥ 5.1

This Example demonstrates how to automatically assign a value to each entry in an enum list. This will prevent two
enums from having the same value by mistake. NOTE: [Link] browser support

var testEnum = function() {


// Initializes the enumerations
var enumList = [

[Link] – JavaScript® Notes for Professionals 245 [Link] – JavaScript® Notes for Professionals 246
Chapter 38: Map This method returns true if the element existed and has been removed, otherwise false:

const map = new Map([[1, 2], [3, 4]]);


Parameter Details [Link]([Link](1)); // true
iterable Any iterable object (for example an array) containing [key, value] pairs. [Link]([Link](7)); // false
key The key of an element.
value The value assigned to the key. Section 38.4: Checking if a key exists in a Map
callback Callback function called with three parameters: value, key, and the map.
To check if a key exists in a Map, use the .has() method:
thisArg Value which will be used as this when executing callback.

[Link](key);
Section 38.1: Creating a Map
Example:
A Map is a basic mapping of keys to values. Maps are different from objects in that their keys can be anything
(primitive values as well as objects), not just strings and symbols. Iteration over Maps is also always done in the const map = new Map([[1, 2], [3, 4]]);
order the items were inserted into the Map, whereas the order is undefined when iterating over keys in an object. [Link]([Link](1)); // true
[Link]([Link](2)); // false
To create a Map, use the Map constructor:

const map = new Map();


Section 38.5: Iterating Maps
Map has three methods which returns iterators: .keys(), .values() and .entries(). .entries() is the default
It has an optional parameter, which can be any iterable object (for example an array) which contains arrays of two Map iterator, and contains [key, value] pairs.
elements – first is the key, the seconds is the value. For example:
const map = new Map([[1, 2], [3, 4]]);
const map = new Map([[new Date(), {foo: "bar"}], [[Link], "body"]]);
// ^key ^value ^key ^value for (const [key, value] of map) {
[Link](`key: ${key}, value: ${value}`);

Section 38.2: Clearing a Map


// logs:
// key: 1, value: 2
// key: 3, value: 4
To remove all elements from a Map, use the .clear() method: }

[Link](); for (const key of [Link]()) {


[Link](key); // logs 1 and 3
}
Example:
for (const value of [Link]()) {
const map = new Map([[1, 2], [3, 4]]); [Link](value); // logs 2 and 4
[Link]([Link]); // 2 }
[Link]();
[Link]([Link]); // 0
[Link]([Link](1)); // undefined
Map also has .forEach() method. The first parameter is a callback function, which will be called for each element
in the map, and the second parameter is the value which will be used as this when executing the callback function.

Section 38.3: Removing an element from a Map The callback function has three arguments: value, key, and the map object.

To remove an element from a map use the .delete() method. const map = new Map([[1, 2], [3, 4]]);
[Link]((value, key, theMap) => [Link](`key: ${key}, value: ${value}`));
[Link](key); // logs:
// key: 1, value: 2
// key: 3, value: 4
Example:

const map = new Map([[1, 2], [3, 4]]); Section 38.6: Getting and setting elements
[Link]([Link](3)); // 4
[Link](3); Use .get(key) to get value by key and .set(key, value) to assign a value to a key.
[Link]([Link](3)); // undefined
If the element with the specified key doesn't exist in the map, .get() returns undefined.

[Link] – JavaScript® Notes for Professionals 247 [Link] – JavaScript® Notes for Professionals 248
.set() method returns the map object, so you can chain .set() calls.
Chapter 39: Timestamps
const map = new Map();
[Link]([Link](1)); // undefined
[Link](1, 2).set(3, 4);
Section 39.1: High-resolution timestamps
[Link]([Link](1)); // 2
[Link]() returns a precise timestamp: The number of milliseconds, including microseconds, since the
current web page started to load.
Section 38.7: Getting the number of elements of a Map
More generally, it returns the time elapsed since the [Link] event.
To get the numbers of elements of a Map, use the .size property:
t = [Link]();
const map = new Map([[1, 2], [3, 4]]);
[Link]([Link]); // 2 For example, in a web browser's main context, [Link]() returns 6288.319 if the web page began to load
6288 milliseconds and 319 microseconds ago.

Section 39.2: Get Timestamp in Seconds


To get the timestamp in seconds

[Link]((new Date().getTime()) / 1000)

Section 39.3: Low-resolution timestamps


[Link]() returns the number of whole milliseconds that have elapsed since 1 January 1970 00:00:00 UTC.

t = [Link]();

For example, [Link]() returns 1461069314 if it was called on 19 April 2016 at 12:35:14 GMT.

Section 39.4: Support for legacy browsers


In older browsers where [Link]() is unavailable, use (new Date()).getTime() instead:

t = (new Date()).getTime();

Or, to provide a [Link]() function for use in older browsers, use this polyfill:

if (![Link]) {
[Link] = function now() {
return new Date().getTime();
};
}

[Link] – JavaScript® Notes for Professionals 249 [Link] – JavaScript® Notes for Professionals 250
Chapter 40: Unary Operators typeof "bla";
typeof (typeof 1); // typeof always returns a string

Section 40.1: Overview


// returns 'boolean'
typeof true;
typeof false;
Unary operators are operators with only one operand. Unary operators are more efficient than standard JavaScript
function calls. Additionally, unary operators can not be overridden and therefore their functionality is guaranteed. // returns 'undefined'
typeof undefined;
The following unary operators are available: typeof declaredButUndefinedVariable;
typeof undeclaredVariable;
Operator Operation Example typeof void 0;
typeof [Link] // see above
delete The delete operator deletes a property from an object. example
void The void operator discards an expression's return value. example // returns 'function'
typeof The typeof operator determines the type of a given object. example typeof function(){};
typeof class C {};
+ The unary plus operator converts its operand to Number type. example
typeof [Link];
- The unary negation operator converts its operand to Number, then negates it. example
~ Bitwise NOT operator. example // returns 'object'
typeof { /*<...>*/ };
! Logical NOT operator. example typeof null;
typeof /regex/; // This is also considered an object
Section 40.2: The typeof operator typeof [1, 2, 4];
typeof new Date();
// use [Link] or [Link].

typeof new RegExp();


The typeof operator returns the data type of the unevaluated operand as a string.
typeof new Boolean(true); // Don't use!
typeof new Number(1); // Don't use!
Syntax: typeof new String("abc"); // Don't use!
typeof operand
// returns 'symbol'
Returns:
typeof Symbol();
typeof [Link];
These are the possible return values from typeof:

Type Return value Section 40.3: The delete operator


Undefined "undefined"
Null "object" The delete operator deletes a property from an object.
Boolean "boolean"
Syntax:
Number "number"
delete [Link]
String "string"
Symbol (ES6) "symbol" delete object['property']
Function object "function"
Returns:
[Link] "undefined"
Host object (provided by the JS environment) Implementation-dependent If deletion is successful, or the property did not exist:
Any other object "object"
true

The unusual behavior of [Link] with the typeof operator is from its former usage to detect legacy browsers.
If the property to be deleted is an own non-configurable property (can't be deleted):
For more information, see Why is [Link] defined but typeof [Link] returns "undefined"?
false in non-strict mode.
Examples:
Throws an error in strict mode
// returns 'number'
typeof 3.14; Description
typeof Infinity;
typeof NaN; // "Not-a-Number" is a "number" The delete operator does not directly free memory. It can indirectly free memory if the operation means all
references to the property are gone.
// returns 'string'
typeof "";
delete works on an object's properties. If a property with the same name exists on the object's prototype chain, the

[Link] – JavaScript® Notes for Professionals 251 [Link] – JavaScript® Notes for Professionals 252
property will be inherited from the prototype. +"42" // 42
+true // 1
delete does not work on variables or function names.
+false // 0
+null // 0
Examples:
+undefined // NaN
// Deleting a property +NaN // NaN
foo = 1; // a global variable is a property of `window`: `[Link]` +"foo" // NaN
delete foo; // true +{} // NaN
[Link](foo); // Uncaught ReferenceError: foo is not defined +function(){} // NaN

// Deleting a variable
Note that attempting to convert an array can result in unexpected return values.
var foo = 1;
delete foo; // false In the background, arrays are first converted to their string representations:
[Link](foo); // 1 (Not deleted)
[].toString() === '';
// Deleting a function [1].toString() === '1';
function foo(){ }; [1, 2].toString() === '1,2';
delete foo; // false
[Link](foo); // function foo(){ } (Not deleted) The operator then attempts to convert those strings to numbers:

// Deleting a property
+[] // 0 ( === +'' )
var foo = { bar: "42" };
+[1] // 1 ( === +'1' )
delete [Link]; // true
+[1, 2] // NaN ( === +'1,2' )
[Link](foo); // Object { } (Deleted bar)

// Deleting a property that does not exist


var foo = { };
Section 40.5: The void operator
delete [Link]; // true
The void operator evaluates the given expression and then returns undefined.
[Link](foo); // Object { } (No errors, nothing deleted)

// Deleting a non-configurable property of a predefined object Syntax:


delete [Link]; // false () void expression
[Link]([Link]); // 3.141592653589793 (Not deleted)
Returns:

Section 40.4: The unary plus operator (+) undefined

Description
The unary plus (+) precedes its operand and evaluates to its operand. It attempts to convert the operand to a
number, if it isn't already. The void operator is often used to obtain the undefined primitive value, by means of writing void 0 or void(0).
Note that void is an operator, not a function, so () is not required.
Syntax:
+expression Usually the result of a void expression and undefined can be used interchangeably.
Returns: However, in older versions of ECMAScript, [Link] could be assigned any value, and it is still possible to
use undefined as name for function parameters variables inside functions, thus disrupting other code that relies on
a Number.
the value of undefined.
Description void will always yield the true undefined value though.

The unary plus (+) operator is the fastest (and preferred) method of converting something into a number. void 0 is also commonly used in code minification as a shorter way of writing undefined. In addition, it's probably
safer as some other code could've tampered with [Link].
It can convert:
Examples:
string representations of integers (decimal or hexadecimal) and floats.
booleans: true, false. Returning undefined:
null
function foo(){
Values that can't be converted will evaluate to NaN. return void 0;
}
[Link](foo()); // undefined
Examples:
+42 // 42

[Link] – JavaScript® Notes for Professionals 253 [Link] – JavaScript® Notes for Professionals 254
Changing the value of undefined inside a certain scope: a Number.

(function(undefined){ Description
var str = 'foo';
[Link](str === undefined); // true The truth table for the NOT operation is:
})('foo');
a NOT a
01
Section 40.6: The unary negation operator (-) 10
The unary negation (-) precedes its operand and negates it, after trying to convert it to number. 1337 (base 10) = 0000010100111001 (base 2)
~1337 (base 10) = 1111101011000110 (base 2) = -1338 (base 10)
Syntax:
-expression A bitwise not on a number results in: -(x + 1).

Returns:
Examples:
a Number. value (base 10) value (base 2) return (base 2) return (base 10)
2 00000010 11111100 -3
Description 1 00000001 11111110 -2
0 00000000 11111111 -1
The unary negation (-) can convert the same types / values as the unary plus (+) operator can.
-1 11111111 00000000 0
-2 11111110 00000001 1
Values that can't be converted will evaluate to NaN (there is no -NaN).
-3 11111100 00000010 2
Examples:
-42 // -42 Section 40.8: The logical NOT operator (!)
-"42" // -42
-true // -1 The logical NOT (!) operator performs logical negation on an expression.
-false // -0
-null // -0
Syntax:
-undefined // NaN
-NaN // NaN !expression
-"foo" // NaN Returns:
-{} // NaN
-function(){} // NaN a Boolean.

Note that attempting to convert an array can result in unexpected return values. Description
In the background, arrays are first converted to their string representations:
The logical NOT (!) operator performs logical negation on an expression.
[].toString() === '';
Boolean values simply get inverted: !true === false and !false === true.
[1].toString() === '1';
[1, 2].toString() === '1,2'; Non-boolean values get converted to boolean values first, then are negated.

This means that a double logical NOT (!!) can be used to cast any value to a boolean:
The operator then attempts to convert those strings to numbers:

!!"FooBar" === true


-[] // -0 ( === -'' )
!!1 === true
-[1] // -1 ( === -'1' )
!!0 === false
-[1, 2] // NaN ( === -'1,2' )

These are all equal to !true:


Section 40.7: The bitwise NOT operator (~)
!'true' === !new Boolean('true');
The bitwise NOT (~) performs a NOT operation on each bit in a value. !'false' === !new Boolean('false');
!'FooBar' === !new Boolean('FooBar');
Syntax: ![] === !new Boolean([]);
~expression !{} === !new Boolean({});

Returns:
These are all equal to !false:

[Link] – JavaScript® Notes for Professionals 255 [Link] – JavaScript® Notes for Professionals 256
!0 === !new Boolean(0);
!'' === !new Boolean(''); Chapter 41: Generators
!NaN === !new Boolean(NaN);
!null === !new Boolean(null); Generator functions (defined by the function* keyword) run as coroutines, generating a series of values as they're
!undefined === !new Boolean(undefined);
requested through an iterator.
Examples:
!true // false Section 41.1: Generator Functions
!-1 // false
!"-1" // false A generator function is created with a function* declaration. When it is called, its body is not immediately executed.
!42 // false
Instead, it returns a generator object, which can be used to "step through" the function's execution.
!"42" // false
!"foo" // false
!"true" // false A yield expression inside the function body defines a point at which execution can suspend and resume.
!"false" // false
!{} // false function* nums() {
![] // false [Link]('starting'); // A
!function(){} // false yield 1; // B
[Link]('yielded 1'); // C
!false // true yield 2; // D
!null // true [Link]('yielded 2'); // E
!undefined // true yield 3; // F
!NaN // true [Link]('yielded 3'); // G
!0 // true }
!"" // true var generator = nums(); // Returns the iterator. No code in nums is executed

[Link](); // Executes lines A,B returning { value: 1, done: false }


// console: "starting"
[Link](); // Executes lines C,D returning { value: 2, done: false }
// console: "yielded 1"
[Link](); // Executes lines E,F returning { value: 3, done: false }
// console: "yielded 2"
[Link](); // Executes line G returning { value: undefined, done: true }
// console: "yielded 3"

Early iteration exit


generator = nums();
[Link](); // Executes lines A,B returning { value: 1, done: false }
[Link](); // Executes lines C,D returning { value: 2, done: false }
[Link](3); // no code is executed returns { value: 3, done: true }
// any further calls will return done = true
[Link](); // no code executed returns { value: undefined, done: true }

Throwing an error to generator function


function* nums() {
try {
yield 1; // A
yield 2; // B
yield 3; // C
} catch (e) {
[Link]([Link]); // D
}
}

var generator = nums();

[Link](); // Executes line A returning { value: 1, done: false }


[Link](); // Executes line B returning { value: 2, done: false }
[Link](new Error("Error!!")); // Executes line D returning { value: undefined, done: true}
// console: "Error!!"
[Link](); // no code executed. returns { value: undefined, done: true }

[Link] – JavaScript® Notes for Professionals 257 [Link] – JavaScript® Notes for Professionals 258
Section 41.2: Sending Values to Generator function* range(n) {
for (let i = 0; i < n; ++i) {
It is possible to send a value to the generator by passing it to the next() method. yield i;
}
}
function* summer() {
let sum = 0, value;
// looping
while (true) {
for (let n of range(10)) {
// receive sent value
// n takes on the values 0, 1, ... 9
value = yield;
}
if (value === null) break;
// spread operator
// aggregate values
let nums = [...range(3)]; // [0, 1, 2]
sum += value;
let max = [Link](...range(100)); // 99
}
return sum;
} Here is another example of use generator to custom iterable object in ES6. Here anonymous generator function
let generator = summer(); function * used.

// proceed until the first "yield" expression, ignoring the "value" argument let user = {
[Link](); name: "sam", totalReplies: 17, isBlocked: false
};
// from this point on, the generator aggregates values until we send "null"
[Link](1); user[[Link]] = function *(){
[Link](10);
[Link](100); let properties = [Link](this);
let count = 0;
// close the generator and collect the result let isDone = false;
let sum = [Link](null).value; // 111
for(let p of properties){

Section 41.3: Delegating to other Generator }


yield this[p];

};
From within a generator function, the control can be delegated to another generator function using yield*.
for(let p of user){
function* g1() { [Link]( p );
yield 2; }
yield 3;
yield 4;
} Section 41.5: Async flow with generators
function* g2() { Generators are functions which are able to pause and then resume execution. This allows to emulate async
yield 1; functions using external libraries, mainly q or co. Basically it allows to write functions that wait for async results in
yield* g1();
order to go on:
yield 5;
}
function someAsyncResult() {
var it = g2(); return [Link]('newValue')
}
[Link]([Link]()); // 1
[Link]([Link]()); // 2 [Link](function * () {
[Link]([Link]()); // 3 var result = yield someAsyncResult()
[Link]([Link]()); // 4 [Link](result) // 'newValue'
[Link]([Link]()); // 5 })
[Link]([Link]()); // undefined
This allows to write async code as if it were synchronous. Moreover, try and catch work over several async blocks. If

Section 41.4: Iteration the promise is rejected, the error is caught by the next catch:

A generator is iterable. It can be looped over with a for...of statement, and used in other constructs which depend function asyncError() {
return new Promise(function (resolve, reject) {
on the iteration protocol.
setTimeout(function () {

[Link] – JavaScript® Notes for Professionals 259 [Link] – JavaScript® Notes for Professionals 260
reject(new Error('Something went wrong')) Generators are widely used with spawn (from taskJS or co) function, where the function takes in a generator and
}, 100)
allows us to write asynchronous code in a synchronous fashion. This does NOT mean that async code is converted
})
}
to sync code / executed synchronously. It means that we can write code that looks like sync but internally it is still
async.
[Link](function * () {
try {
var result = yield asyncError() Sync is BLOCKING; Async is WAITING. Writing code that blocks is easy. When PULLing, value appears in
} catch (e) { the assignment position. When PUSHing, value appears in the argument position of the callback.
[Link](e) // Something went wrong
}
}) When you use iterators, you PULL the value from the producer. When you use callbacks, the producer PUSHes the
value to the argument position of the callback.
Using co would work exactly the same but with co(function * (){...}) instead of [Link]
var i = [Link]() // PULL
Section 41.6: Iterator-Observer interface dosomething(..., v => {...}) // PUSH

A generator is a combination of two things - an Iterator and an Observer. Here, you pull the value from [Link]() and in the second, v => {...} is the callback and a value is PUSHed into the
argument position v of the callback function.
Iterator
Using this pull-push mechanism, we can write async programming like this,
An iterator is something when invoked returns an iterable. An iterable is something you can iterate upon. From
ES6/ES2015 onwards, all collections (Array, Map, Set, WeakMap, WeakSet) conform to the Iterable contract. let delay = t => new Promise(r => setTimeout(r, t));
spawn(function*() {
// wait for 100 ms and send 1
A generator(iterator) is a producer. In iteration the consumer PULLs the value from the producer. let x = yield delay(100).then(() => 1);
[Link](x); // 1

Example: // wait for 100 ms and send 2


let y = yield delay(100).then(() => 2);
function *gen() { yield 5; yield 6; } [Link](y); // 2
let a = gen(); });

Whenever you call [Link](), you're essentially pull-ing value from the Iterator and pause the execution at yield. So, looking at the above code, we are writing async code that looks like it's blocking (the yield statements wait for
The next time you call [Link](), the execution resumes from the previously paused state. 100ms and then continue execution), but it's actually waiting. The pause and resume property of generator allows
us to do this amazing trick.
Observer
How does it work ?
A generator is also an observer using which you can send some values back into the generator.
The spawn function uses yield promise to PULL the promise state from the generator, waits till the promise is
function *gen() { resolved, and PUSHes the resolved value back to the generator so it can consume it.
[Link]('<br>observer:', yield 1);
} Use it now
var a = gen();
var i = [Link](); So, with generators and spawn function, you can clean up all your async code in NodeJS to look and feel like it's
while(![Link]) { synchronous. This will make debugging easy. Also the code will look neat.
[Link]('<br>iterator:', [Link]);
i = [Link](100);
This feature is coming to future versions of JavaScript - as async...await. But you can use them today in
}
ES2015/ES6 using the spawn function defined in the libraries - taskjs, co, or bluebird

Here you can see that yield 1 is used like an expression which evaluates to some value. The value it evaluates to is
the value sent as an argument to the [Link] function call.

So, for the first time [Link] will be the first value yielded (1), and when continuing the iteration to the next state,
we send a value back to the generator using [Link](100).

Doing async with Generators

[Link] – JavaScript® Notes for Professionals 261 [Link] – JavaScript® Notes for Professionals 262
Chapter 42: Promises [Link](value => {
// Work has completed successfully,
// promise has been fulfilled with "value"
Section 42.1: Introduction }).catch(reason => {
// Something went wrong,
// promise has been rejected with "reason"
A Promise object represents an operation which has produced or will eventually produce a value. Promises provide a
});
robust way to wrap the (possibly pending) result of asynchronous work, mitigating the problem of deeply nested
callbacks (known as "callback hell"). Note: Calling [Link](...) and [Link](...) on the same promise might result in an Uncaught
exception in Promise if an error occurs, either while executing the promise or inside one of the callbacks, so the
States and control flow
preferred way would be to attach the next listener on the promise returned by the previous then / catch.
A promise can be in one of three states:
Alternatively, both callbacks can be attached in a single call to then:
pending — The underlying operation has not yet completed, and the promise is pending fulfillment.
[Link](onFulfilled, onRejected);
fulfilled — The operation has finished, and the promise is fulfilled with a value. This is analogous to returning a
value from a synchronous function.
Attaching callbacks to a promise that has already been settled will immediately place them in the microtask queue,
rejected — An error has occurred during the operation, and the promise is rejected with a reason. This is
and they will be invoked "as soon as possible" (i.e. immediately after the currently executing script). It is not
analogous to throwing an error in a synchronous function.
necessary to check the state of the promise before attaching callbacks, unlike with many other event-emitting
A promise is said to be settled (or resolved) when it is either fulfilled or rejected. Once a promise is settled, it implementations.
becomes immutable, and its state cannot change. The then and catch methods of a promise can be used to attach
Live demo
callbacks that execute when it is settled. These callbacks are invoked with the fulfillment value and rejection reason,
respectively.
Section 42.2: Promise chaining
The then method of a promise returns a new promise.

const promise = new Promise(resolve => setTimeout(resolve, 5000));

promise
// 5 seconds later
.then(() => 2)
// returning a value from a then callback will cause
// the new promise to resolve with this value
.then(value => { /* value === 2 */ });

Example Returning a Promise from a then callback will append it to the promise chain.
const promise = new Promise((resolve, reject) => {
// Perform some work (possibly asynchronous) function wait(millis) {
// ... return new Promise(resolve => setTimeout(resolve, millis));
}
if (/* Work has successfully finished and produced "value" */) {
resolve(value); const p = wait(5000).then(() => wait(4000)).then(() => wait(1000));
} else { [Link](() => { /* 10 seconds have passed */ });
// Something went wrong because of "reason"
// The reason is traditionally an Error object, although A catch allows a rejected promise to recover, similar to how catch in a try/catch statement works. Any chained
// this is not required or enforced.
then after a catch will execute its resolve handler using the value resolved from the catch.
let reason = new Error(message);
reject(reason);
const p = new Promise(resolve => {throw 'oh no'});
// Throwing an error also rejects the promise. [Link](() => 'oh yes').then([Link](console)); // outputs "oh yes"
throw reason;
} If there are no catch or reject handlers in the middle of the chain, a catch at the end will capture any rejection in
}); the chain:

The then and catch methods can be used to attach fulfillment and rejection callbacks: [Link](() => [Link]('oh yes'))
.then([Link](console)) // won't be called

[Link] – JavaScript® Notes for Professionals 263 [Link] – JavaScript® Notes for Professionals 264
.catch([Link](console)); // outputs "oh yes" .catch(reason => [Link](reason)); // outputs "Error!" after 6 seconds.

On certain occasions, you may want to "branch" the execution of the functions. You can do it by returning different Non-promise values in the iterable are "promisified".
promises from a function depending on the condition. Later in the code, you can merge all of these branches into
one to call other functions on them and/or to handle all errors in one place. [Link]([
resolve(1, 5000),
resolve(2, 6000),
promise
{ hello: 3 }
.then(result => {
])
if ([Link]) {
.then(values => [Link](values)); // outputs "[1, 2, { hello: 3 }]" after 6 seconds
return handlerFn1()
.then(handlerFn2);
} else if (result.condition2) { Destructuring assignment can help to retrieve results from multiple promises.
return handlerFn3()
.then(handlerFn4); [Link]([
} else { resolve(1, 5000),
throw new Error("Invalid result"); resolve(2, 6000),
} resolve(3, 7000)
}) ])
.then(handlerFn5) .then(([result1, result2, result3]) => {
.catch(err => { [Link](result1);
[Link](err); [Link](result2);
}); [Link](result3);
});
Thus, the execution order of the functions looks like:

promise --> handlerFn1 -> handlerFn2 --> handlerFn5 ~~> .catch()


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.
V |
-> handlerFn3 -> handlerFn4 -^
There are two variants :

The single catch will get the error on whichever branch it may occur.
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.
Section 42.3: Waiting for multiple concurrent promises
The "then" reduction
The [Link]() 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 This variant of the pattern builds a .then() chain, and might be used for chaining animations, or making a
have rejected. sequence of dependent HTTP requests.

// wait "millis" ms, then resolve with "value" [1, 3, 5, 7, 9].reduce((seq, n) => {
function resolve(value, milliseconds) { return [Link](() => {
return new Promise(resolve => setTimeout(() => resolve(value), milliseconds)); [Link](n);
} return new Promise(res => setTimeout(res, 1000));
});
// wait "millis" ms, then reject with "reason" }, [Link]()).then(
function reject(reason, milliseconds) { () => [Link]('done'),
return new Promise((_, reject) => setTimeout(() => reject(reason), milliseconds)); (e) => [Link](e)
} );
// will log 1, 3, 5, 7, 9, 'done' in 1s intervals
[Link]([
resolve(1, 5000), Explanation:
resolve(2, 6000),
resolve(3, 7000)
1. We call .reduce() on a source array, and provide [Link]() as an initial value.
]).then(values => [Link](values)); // outputs "[1, 2, 3]" after 7 seconds.
2. Every element reduced will add a .then() to the initial value.
[Link]([ 3. reduce()'s product will be [Link]().then(...).then(...).
resolve(1, 5000), 4. We manually append a .then(successHandler, errorHandler) after the reduce, to execute successHandler
reject('Error!', 6000), once all the previous steps have resolved. If any step was to fail, then errorHandler would execute.
resolve(2, 7000)
]).then(values => [Link](values)) // does not output anything

[Link] – JavaScript® Notes for Professionals 265 [Link] – JavaScript® Notes for Professionals 266
Note: The "then" reduction is a sequential counterpart of [Link](). [Link]([
reject(new Error('bad things!'), 1000),
The "catch" reduction resolve(2, 2000)
])
.then(value => [Link](value)) // does not output anything
This variant of the pattern builds a .catch() chain and might be used for sequentially probing a set of web servers
.catch(error => [Link]([Link])); // outputs "bad things!" after 1 second
for some mirrored resource until a working server is found.

var working_resource = 5; // one of the values from the source array Section 42.6: "Promisifying" functions with callbacks
[1, 3, 5, 7, 9].reduce((seq, n) => {
return [Link](() => { Given a function that accepts a Node-style callback,
[Link](n);
if(n === working_resource) { // 5 is working fooFn(options, function callback(err, result) { ... });
return new Promise((resolve, reject) => setTimeout(() => resolve(n), 1000));
} else { // all other values are not working
return new Promise((resolve, reject) => setTimeout(reject, 1000)); you can promisify it (convert it to a promise-based function) like this:
}
}); function promiseFooFn(options) {
}, [Link]()).then( return new Promise((resolve, reject) =>
(n) => [Link]('success at: ' + n), fooFn(options, (err, result) =>
() => [Link]('total failure') // If there's an error, reject; otherwise resolve
); err ? reject(err) : resolve(result)
// will log 1, 3, 5, 'success at 5' at 1s intervals )
);
}
Explanation:

1. We call .reduce() on a source array, and provide [Link]() as an initial value. This function can then be used as follows:
2. Every element reduced will add a .catch() to the initial value.
promiseFooFn(options).then(result => {
3. reduce()'s product will be [Link]().catch(...).catch(...).
// success!
4. We manually append .then(successHandler, errorHandler) after the reduce, to execute successHandler
}).catch(err => {
once any of the previous steps has resolved. If all steps were to fail, then errorHandler would execute. // error!
});
Note: The "catch" reduction is a sequential counterpart of [Link]() (as implemented in [Link], but not
currently in native ECMAScript). In a more generic way, here's how to promisify any given callback-style function:

Section 42.5: Waiting for the first of multiple concurrent function promisify(func) {
promises return function(...args) {
return new Promise((resolve, reject) => {
func(...args, (err, result) => err ? reject(err) : resolve(result));
The [Link]() 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) { This can be used like this:
return new Promise(resolve => setTimeout(() => resolve(value), milliseconds));
}
const fs = require('fs');
const promisedStat = promisify([Link](fs));
// wait "milliseconds" milliseconds, then reject with "reason"
function reject(reason, milliseconds) {
promisedStat('/foo/bar')
return new Promise((_, reject) => setTimeout(() => reject(reason), milliseconds));
.then(stat => [Link]('STATE', stat))
}
.catch(err => [Link]('ERROR', err));
[Link]([
resolve(1,
resolve(2,
5000),
3000),
Section 42.7: Error Handling
resolve(3, 1000)
Errors thrown from promises are handled by the second parameter (reject) passed to then or by the handler
])
.then(value => [Link](value)); // outputs "3" after 1 second. passed to catch:

throwErrorAsync()

[Link] – JavaScript® Notes for Professionals 267 [Link] – JavaScript® Notes for Professionals 268
.then(null, error => { /* handle error here */ }); throwErrorAsync()
// or .then(() => { /* will not be called */ })
throwErrorAsync() .catch(error => { /* handle error*/ });
.catch(error => { /* handle error here */ }); // or
throwErrorAsync()
.then(() => { /* will not be called */ }, error => { /* handle error*/ });
Chaining

If you have a promise chain then an error will cause resolve handlers to be skipped: Alternatively, subscribe to the unhandledrejection event to catch any unhandled rejected promises:

throwErrorAsync() [Link]('unhandledrejection', event => {});


.then(() => { /* never called */ })
.catch(error => { /* handle error here */ }); Some promises can handle their rejection later than their creation time. The rejectionhandled event gets fired
whenever such a promise is handled:
The same applies to your then functions. If a resolve handler throws an exception then the next reject handler
will be invoked: [Link]('unhandledrejection', event => [Link]('unhandled'));
[Link]('rejectionhandled', event => [Link]('handled'));
doSomethingAsync() var p = [Link]('test');
.then(result => { throwErrorSync(); })
.then(() => { /* never called */ }) setTimeout(() => [Link]([Link]), 1000);
.catch(error => { /* handle error from throwErrorSync() */ });
// Will print 'unhandled', and after one second 'test' and 'handled'

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: The event argument contains information about the rejection. [Link] is the error object and [Link]
is the promise object that caused the event.
throwErrorAsync()
.catch(error => { /* handle error here */; return result; }) In Nodejs the rejectionhandled and unhandledrejection events are called rejectionHandled and
.then(result => { /* handle result here */ }); unhandledRejection on process, respectively, and have a different signature:

You can let an error cascade down a promise chain by re-throwing the error: [Link]('rejectionHandled', (reason, promise) => {});
[Link]('unhandledRejection', (reason, promise) => {});

throwErrorAsync()
.catch(error => { The reason argument is the error object and the promise argument is a reference to the promise object that caused
/* handle error from throwErrorAsync() */ the event to fire.
throw error;
}) Usage of these unhandledrejection and rejectionhandled events should be considered for debugging purposes
.then(() => { /* will not be called if there's an error */ })
only. Typically, all promises should handle their rejections.
.catch(error => { /* will get called with the same error */ });

Note: Currently, only Chrome 49+ and [Link] support unhandledrejection and rejectionhandled events.
It is possible to throw an exception that is not handled by the promise by wrapping the throw statement inside a
setTimeout callback: Caveats
Chaining with fulfill and reject
new Promise((resolve, reject) => {
setTimeout(() => { throw new Error(); }); The then(fulfill, reject) function (with both parameters not null) has unique and complex behavior, and
});
shouldn't be used unless you know exactly how it works.

This works because promises cannot handle exceptions thrown asynchronously. The function works as expected if given null for one of the inputs:

Unhandled rejections
// the following calls are equivalent
[Link](fulfill, null)
An error will be silently ignored if a promise doesn't have a catch block or reject handler: [Link](fulfill)

throwErrorAsync() // the following calls are also equivalent


.then(() => { /* will not be called */ }); [Link](null, reject)
// error silently ignored [Link](reject)

To prevent this, always use a catch block: However, it adopts unique behavior when both inputs are given:

[Link] – JavaScript® Notes for Professionals 269 [Link] – JavaScript® Notes for Professionals 270
// the following calls are not equivalent! Instead of throwing, do as follows:
[Link](fulfill, reject)
[Link](fulfill).catch(reject) function foo(arg) {
if (arg === 'unexepectedValue') {
// the following calls are not equivalent! return [Link](new Error('UnexpectedValue'))
[Link](fulfill, reject) }
[Link](reject).then(fulfill)
return new Promise(resolve =>
The then(fulfill, reject) function looks like it is a shortcut for then(fulfill).catch(reject), but it is not, and setTimeout(() => resolve(arg), 1000)
)
will cause problems if used interchangeably. One such problem is that the reject handler does not handle errors
}
from the fulfill handler. Here is what will happen:
Wrap your function into a promise chain
[Link]() // previous promise is fulfilled
.then(() => { throw new Error(); }, // error in the fulfill handler Your throw statement will be properly caught when it is already inside a promise chain:
error => { /* this is not called! */ });
function foo(arg) {
return [Link]()
The above code will result in a rejected promise because the error is propagated. Compare it to the following code,
.then(() => {
which results in a fulfilled promise: if (arg === 'unexepectedValue') {
throw new Error('UnexpectedValue')
[Link]() // previous promise is fulfilled }
.then(() => { throw new Error(); }) // error in the fulfill handler
.catch(error => { /* handle error */ }); return new Promise(resolve =>
setTimeout(() => resolve(arg), 1000)
A similar problem exists when using then(fulfill, reject) interchangeably with catch(reject).then(fulfill), )
})
except with propagating fulfilled promises instead of rejected promises.
}

Synchronously throwing from function that should return a promise


Section 42.8: Reconciling synchronous and asynchronous
Imagine a function like this: operations
function foo(arg) { In some cases you may want to wrap a synchronous operation inside a promise to prevent repetition in code
if (arg === 'unexepectedValue') {
branches. Take this example:
throw new Error('UnexpectedValue')
}
if (result) { // if we already have a result
return new Promise(resolve => processResult(result); // process it
setTimeout(() => resolve(arg), 1000) } else {
) fetchResult().then(processResult);
} }

If such function is used in the middle of a promise chain, then apparently there is no problem: The synchronous and asynchronous branches of the above code can be reconciled by redundantly wrapping the
synchronous operation inside a promise:
makeSomethingAsync().
.then(() => foo('unexpectedValue')) var fetch = result
.catch(err => [Link](err)) // <-- Error: UnexpectedValue will be caught here ? [Link](result)
: fetchResult();

However, if the same function is called outside of a promise chain, then the error will not be handled by it and will
[Link](processResult);
be thrown to the application:

When caching the result of an asynchronous call, it is preferable to cache the promise rather than the result itself.
foo('unexpectedValue') // <-- error will be thrown, so the application will crash
.then(makeSomethingAsync) // <-- will not run
This ensures that only one asynchronous operation is required to resolve multiple parallel requests.
.catch(err => [Link](err)) // <-- will not catch
Care should be taken to invalidate cached values when error conditions are encountered.

There are 2 possible workarounds:


// A resource that is not expected to change frequently
var planets = '[Link]
Return a rejected promise with the error
// The cached promise, or null

[Link] – JavaScript® Notes for Professionals 271 [Link] – JavaScript® Notes for Professionals 272
var cachedPromise; // immediately invoked
// value === 2
function fetchResult() { });
if (!cachedPromise) {
cachedPromise = fetch(planets)
The [Link] static method returns a promise which immediately rejects with the given reason.
.catch(function (e) {
// Invalidate the current result to retry on the next fetch
cachedPromise = null; let rejected = [Link]("Oops!");
// re-raise the error to propagate it to callers [Link](reason => {
throw e; // immediately invoked
}); // reason === "Oops!"
} });
return cachedPromise;
}
Section 42.11: Using ES2017 async/await
Section 42.9: Delay function call The same example above, Image loading, can be written using async functions. This also allows using the common
try/catch method for exception handling.
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. It is
also a trivial way to achieve an asynchronous operation. Note: as of April 2017, the current releases of all browsers but Internet Explorer supports async functions.

In this example calling the wait function resolves the promise after the time specified as first argument: function loadImage(url) {
return new Promise((resolve, reject) => {
function wait(ms) { const img = new Image();
return new Promise(resolve => setTimeout(resolve, ms)); [Link]('load', () => resolve(img));
} [Link]('error', () => {
reject(new Error(`Failed to load ${url}`));
wait(5000).then(() => { });
[Link]('5 seconds have passed...'); [Link] = url;
}); });
}

Section 42.10: "Promisifying" values (async () => {

The [Link] static method can be used to wrap values into promises. // load /[Link] and append to #image-holder, otherwise throw error
try {
let img = await loadImage('[Link]
let resolved = [Link](2);
[Link]('image-holder').appendChild(img);
[Link](value => {
}
// immediately invoked
catch (error) {
// value === 2
[Link](error);
});
}

If value is already a promise, [Link] simply recasts it. })();

let Promise(resolve => setTimeout(() => resolve(2), 1000));


let two = [Link](one);
Section 42.12: Performing cleanup with finally()
[Link](value => {
// 1 second has passed There is currently a proposal (not yet part of the ECMAScript standard) to add a finally callback to promises that
// value === 2 will be executed regardless of whether the promise is fulfilled or rejected. Semantically, this is similar to the
}); finally clause of the try block.

In fact, value can be any "thenable" (object defining a then method that works sufficiently like a spec-compliant You would usually use this functionality for cleanup:
promise). This allows [Link] to convert untrusted 3rd-party objects into trusted 1st-party Promises.
var loadingData = true;
let resolved = [Link]({
then(onResolved) { fetch('/data')
onResolved(2); .then(result => processData([Link]))
} .catch(error => [Link](error))
}); .finally(() => {
[Link](value => { loadingData = false;

[Link] – JavaScript® Notes for Professionals 273 [Link] – JavaScript® Notes for Professionals 274
}); return new Promise(function(resolve, reject) {
let request = new XMLHttpRequest();
[Link]('GET', path);
It is important to note that the finally callback doesn't affect the state of the promise. It doesn't matter what value
[Link] = resolve;
it returns, the promise stays in the fulfilled/rejected state that it had before. So in the example above the promise [Link] = reject;
will be resolved with the return value of processData([Link]) even though the finally callback returned [Link]();
undefined. });
};
With the standardization process still being in progress, your promises implementation most likely won't support
finally callbacks out of the box. For synchronous callbacks you can add this functionality with a polyfill however: More robust error handling can be done using the following onload and onerror functions.

if (![Link]) { [Link] = function() {


[Link] = function(callback) { if ([Link] >= 200 && [Link] < 300) {
return [Link](result => { if([Link]) {
callback(); // Assuming a successful call returns JSON
return result; resolve([Link]([Link]));
}, error => { } else {
callback(); resolve();
throw error; } else {
}); reject({
}; 'status': [Link],
} 'message': [Link]
});
}
Section 42.13: forEach with promises };

It is possible to effectively apply a function (cb) which returns a promise to each element of an array, with each [Link] = function() {
element waiting to be processed until the previous element is processed. reject({
'status': [Link],
'message': [Link]
function promiseForEach(arr, cb) {
});
var i = 0;
};

var nextPromise = function () {


if (i >= [Link]) {
// Processing finished.
return;
}

// Process next function. Wrap in `[Link]` in case


// the function does not return a promise
var newPromise = [Link](cb(arr[i], i));
i++;
// Chain to finish processing.
return [Link](nextPromise);
};

// Kick off the chain.


return [Link]().then(nextPromise);
};

This can be helpful if you need to efficiently process thousands of items, one at a time. Using a regular for loop to
create the promises will create them all at once and take up a significant amount of RAM.

Section 42.14: Asynchronous API request


This is an example of a simple GET API call wrapped in a promise to take advantage of its asynchronous
functionality.

var get = function(path) {

[Link] – JavaScript® Notes for Professionals 275 [Link] – JavaScript® Notes for Professionals 276
Chapter 43: Set [Link](some_val);

This function will return true if the value existed in the set and was removed, or false otherwise.
Parameter Details
If an iterable object is passed, all of its elements will be added to the new Set. null is treated as
iterable
undefined. Section 43.4: Checking if a value exist in a set
value The value of the element to add to the Set object.
To check if a given value exists in a set, use .has() method:
callback Function to execute for each element.
thisArg Optional. Value to use as this when executing callback. [Link](someVal);

The Set object lets you store unique values of any type, whether primitive values or object references. Will return true if someVal appears in the set, false otherwise.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the
Set may only occur ONCE; it is unique in the Set's collection. Distinct values are discriminated using the
Section 43.5: Clearing a Set
SameValueZero comparison algorithm. You can remove all the elements in a set using the .clear() method:

Standard Specification About Set [Link]();

Section 43.1: Creating a Set Section 43.6: Getting set length


The Set object lets you store unique values of any type, whether primitive values or object references.
You can get the number of elements inside the set using the .size property
You can push items into a set and iterate them similar to a plain JavaScript array, but unlike array, you cannot add a
const mySet = new Set([1, 2, 2, 3]);
value to a Set if the value already exist in it.
[Link](4);
[Link]; // 4
To create a new set:

This property, unlike [Link], is read-only, which means that you can't change it by assigning
const mySet = new Set();
something to it:

Or you can create a set from any iterable object to give it starting values:
[Link] = 5;
[Link]; // 4
const arr = [1,2,3,4,4,5];
const mySet = new Set(arr);
In strict mode it even throws an error:

In the example above the set content would be {1, 2, 3, 4, 5}. Note that the value 4 appears only once, unlike in
TypeError: Cannot set property size of #<Set> which has only a getter
the original array used to create it.

Section 43.2: Adding a value to a Set Section 43.7: Converting Sets to arrays
To add a value to a Set, use the .add() method: Sometimes you may need to convert a Set to an array, for example to be able to use [Link] methods like
.filter(). In order to do so, use [Link]() or destructuring-assignment:
[Link](5);
var mySet = new Set([1, 2, 3, 4]);
//use [Link]
If the value already exist in the set it will not be added again, as Sets contain unique values.
const myArray = [Link](mySet);
//use destructuring-assignment
Note that the .add() method returns the set itself, so you can chain add calls together: const myArray = [...mySet];

[Link](1).add(2).add(3);
Now you can filter the array to contain only even numbers and convert it back to Set using Set constructor:

Section 43.3: Removing value from a set mySet = new Set([Link](x => x % 2 === 0));

To remove a value from a set, use .delete() method: mySet now contains only even numbers:

[Link] – JavaScript® Notes for Professionals 277 [Link] – JavaScript® Notes for Professionals 278
[Link](mySet); // Set {2, 4}
Chapter 44: Modals - Prompts
Section 43.8: Intersection and dierence in Sets Section 44.1: About User Prompts
There are no build-in methods for intersection and difference in Sets, but you can still achieve that but converting
User Prompts are methods part of the Web Application API used to invoke Browser modals requesting a user action
them to arrays, filtering, and converting back to Sets:
such as confirmation or input.

var set1 = new Set([1, 2, 3, 4]), [Link](message)


set2 = new Set([3, 4, 5, 6]);
Show a modal popup with a message to the user.
const intersection = new Set([Link](set1).filter(x => [Link](x)));//Set {3, 4}
const difference = new Set([Link](set1).filter(x => ![Link](x))); //Set {1, 2}
Requires the user to click [OK] to dismiss.

alert("Hello World");
Section 43.9: Iterating Sets
More information below in "Using alert()".
You can use a simple for-of loop to iterate a Set:
boolean = [Link](message)
const mySet = new Set([1, 2, 3]);
Show a modal popup with the provided message.
for (const value of mySet) { Provides [OK] and [Cancel] buttons which will respond with a boolean value true / false respectively.
[Link](value); // logs 1, 2 and 3
}
confirm("Delete this comment?");

When iterating over a set, it will always return values in the order they were first added to the set. For example:
result = [Link](message, defaultValue)
const set = new Set([4, 5, 6])
[Link](10)
Show a modal popup with the provided message and an input field with an optional pre-filled value.
[Link](5) //5 already exists in the set
[Link](set) //[4, 5, 6, 10]
Returns as result the user provided input value.

prompt("Enter your website address", "[Link]


There's also a .forEach() method, similar to [Link](). It has two parameters, callback, which
will be executed for each element, and optional thisArg, which will be used as this when executing callback.
More information below in "Usage of prompt()".
callback has three arguments. The first two arguments are both the current element of Set (for consistency with
[Link]() and [Link]()) and the third argument is the Set itself.
[Link]()
[Link]((value, value2, set) => [Link](value)); // logs 1, 2 and 3
Opens a modal with document print options.

print();

Section 44.2: Persistent Prompt Modal


When using prompt a user can always click Cancel and no value will be returned.
To prevent empty values and make it more persistent:

<h2>Welcome <span id="name"></span>!</h2>

<script>
// Persistent Prompt modal
var userName;
while(!userName) {
userName = prompt("Enter your name", "");
if(!userName) {
alert("Please, we need your name!");
} else {

[Link] – JavaScript® Notes for Professionals 279 [Link] – JavaScript® Notes for Professionals 280
[Link]("name").innerHTML = userName;
}
}
</script>

jsFiddle demo

Section 44.3: Confirm to Delete element


A way to use confirm() is when some UI action does some destructive changes to the page and is better An alert box is often used if you want to make sure information comes through to the user.
accompanied by a notification and a user confirmation - like i.e. before deleting a post message:
Note: The alert box takes the focus away from the current window, and forces the browser to read the message.

<div id="post-102">
Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.
<p>I like Confirm modals.</p> Also it stops the further code execution, until user clicks OK . (in particular, the timers which were set with
<a data-deletepost="post-102">Delete post</a> setInterval() or setTimeout() don't tick either). The alert box only works in browsers, and its design cannot be
</div> modified.
<div id="post-103">
<p>That's way too cool!</p> Parameter Description
<a data-deletepost="post-103">Delete post</a>
Required. Specifies the text to display in the alert box, or an object converted into a string and
</div> message
displayed.
// Collect all buttons
var deleteBtn = [Link]("[data-deletepost]"); Return value

function deleteParentPost(event) { alert function doesn't return any value


[Link](); // Prevent page scroll jump on anchor click

if( confirm("Really Delete this post?") ) { Section 44.5: Usage of prompt()


var post = [Link]( [Link] );
[Link](post); Prompt will display a dialog to the user requesting their input. You can provide a message that will be placed above
// TODO: remove that post from database the text field. The return value is a string representing the input provided by the user.
} // else, do nothing

var name = prompt("What's your name?");


}
[Link]("Hello, " + name);
// Assign click event to buttons
[].[Link](deleteBtn, function(btn) { You can also pass prompt() a second parameter, which will be displayed as the default text in the prompt's text
[Link]("click", deleteParentPost, false); field.
});
var name = prompt('What\'s your name?', ' Name...');
jsFiddle demo [Link]('Hello, ' + name);
Parameter Description
Section 44.4: Usage of alert() message Required. Text to display above the text field of the prompt.
default Optional. Default text to display in the text field when the prompt is displayed.
The alert() method of the window object displays an alert box with a specified message and an OK or Cancel
button. The text of that button depends on the browser and can't be modified.

Syntax

alert("Hello world!");
// Or, alternatively...
[Link]("Hello world!");

Produces

[Link] – JavaScript® Notes for Professionals 281 [Link] – JavaScript® Notes for Professionals 282
Chapter 45: execCommand and Section 45.1: Listening to Changes of contenteditable
contenteditable Events that work with most form elements (e.g., change, keydown, keyup, keypress) do not work with
contenteditable.

commandId value
Instead, you can listen to changes of contenteditable contents with the input event. Assuming
⋮ Inline formatting commands
contenteditableHtmlElement is a JS DOM object that is contenteditable:
backColor Color value String
bold [Link]("input", function() {
createLink URL String [Link]("contenteditable element changed");
});
fontName Font family name
fontSize "1", "2", "3", "4", "5", "6", "7"
foreColor Color value String Section 45.2: Getting started
strikeThrough The HTML attribute contenteditable provides a simple way to turn a HTML element into a user-editable area
superscript
unlink <div contenteditable>You can <b>edit</b> me!</div>
⋮ Block formatting commands
delete Native Rich-Text editing

formatBlock "address", "dd", "div", "dt", "h1", "h2", "h3", "h4", "h5", "h6", "p", "pre"
Using JavaScript and execCommandW3C you can additionally pass more editing features to the currently focused
forwardDelete contenteditable element (specifically at the caret position or selection).
insertHorizontalRule
insertHTML HTML String The execCommand function method accepts 3 arguments

insertImage URL String


[Link](commandId, showUI, value)
insertLineBreak
insertOrderedList commandId String. from the list of available **commandId**s
insertParagraph (see: Parameters→commandId)
insertText Text string showUI Boolean (not implemented. Use false)

insertUnorderedList value String If a command expects a command-related String value, otherwise "".
(see: Parameters→value)
justifyCenter
justifyFull Example using the "bold" command and "formatBlock" (where a value is expected):
justifyLeft
justifyRight [Link]("bold", false, ""); // Make selected text bold
[Link]("formatBlock", false, "H2"); // Make selected text Block-level <h2>
outdent
⋮ Clipboard commands
Quick Start Example:
copy Currently Selected String
cut Currently Selected String <button data-edit="bold"><b>B</b></button>
paste <button data-edit="italic"><i>I</i></button>
<button data-edit="formatBlock:p">P</button>
⋮ Miscellaneous commands
<button data-edit="formatBlock:H1">H1</button>
defaultParagraphSeparator <button data-edit="insertUnorderedList">UL</button>
redo <button data-edit="justifyLeft">&#8676;</button>
<button data-edit="justifyRight">&#8677;</button>
selectAll <button data-edit="removeFormat">&times;</button>
styleWithCSS
undo <div contenteditable><p>Edit me!</p></div>

useCSS <script>
[].[Link]([Link]("[data-edit]"), function(btn) {
[Link]("click", edit, false);
});

[Link] – JavaScript® Notes for Professionals 283 [Link] – JavaScript® Notes for Professionals 284
function edit(event) { [Link]('underline', false, null); // toggles underline
[Link]();
var cmd_val = [Link](":");
[Link](cmd_val[0], false, cmd_val[1]);
}
<script>

jsFiddle demo
Basic Rich-Text editor example (Modern browsers)

Final thoughts
Even being present for a long time (IE6), implementations and behaviors of execCommand vary from browser to
browser making "building a Fully-featured and cross-browser compatible WYSIWYG editor" a hard task to any
experienced JavaScript developer.
Even if not yet fully standardized you can expect pretty decent results on the newer browsers like Chrome, Firefox,
Edge. If you need better support for other browsers and more features like HTMLTable editing etc. a rule of thumbs
is to look for an already existent and robust Rich-Text editor.

Section 45.3: Copy to clipboard from textarea using


execCommand("copy")
Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<textarea id="content"></textarea>
<input type="button" id="copyID" value="Copy" />
<script type="text/javascript">
var button = [Link]("copyID"),
input = [Link]("content");

[Link]("click", function(event) {
[Link]();
[Link]();
[Link]("copy");
});
</script>
</body>
</html>

[Link]("copy") copies the current selection to the clipboard

Section 45.4: Formatting


Users can add formatting to contenteditable documents or elements using their browser's features, such as
common keyboard shortcuts for formatting ( Ctrl-B for bold, Ctrl-I for italic, etc.) or by dragging and
dropping images, links, or markup from the clipboard.

Additionally, developers can use JavaScript to apply formatting to the current selection (highlighted text).

[Link]('bold', false, null); // toggles bold formatting


[Link]('italic', false, null); // toggles italic formatting

[Link] – JavaScript® Notes for Professionals 285 [Link] – JavaScript® Notes for Professionals 286
Chapter 46: History [Link](number|URL)

Parameter Details Example


domain The domain you want to update to
title The title to update to
Click on the button to go back two pages:
path The path to update to
<html>
Section 46.1: [Link]() <head>
<script type="text/javascript">
Syntax : function goBack()
{
[Link](-2)
[Link](state object, title, url)
}
</script>
This method allows to ADD histories entries. For more reference, Please have a look on this document : pushState() </head>
method <body>
<input type="button" value="Go back 2 pages" />
Example : </body>
</html>

[Link]("[Link] "Sample Title", "/example/[Link]");

This example inserts a new record into the history, address bar, and page title.

Note this is different from the [Link](). Which updates the current history entry, rather than
adding a new one.

Section 46.2: [Link]()


Syntax :

[Link](data, title [, url ])

This method modifies the current history entry instead of creating a new one. Mainly used when we want to update
URL of the current history entry.

[Link]("[Link] "Sample Title", "/example/[Link]");

This example replaces the current history, address bar, and page title.

Note this is different from the [Link](). Which inserts a new history entry, rather than replacing the
current one.

Section 46.3: Load a specific URL from the history list


go() method

The go() method loads a specific URL from the history list. The parameter can either be a number which goes to the
URL within the specific position (-1 goes back one page, 1 goes forward one page), or a string. The string must be a
partial or full URL, and the function will go to the first URL that matches the string.

Syntax

[Link] – JavaScript® Notes for Professionals 287 [Link] – JavaScript® Notes for Professionals 288
Chapter 47: Navigator Object Chapter 48: BOM (Browser Object Model)
Section 47.1: Get some basic browser data and return it as a Section 48.1: Introduction
JSON object
The BOM (Browser Object Model) contains objects that represent the current browser window and components;
The following function can be used to get some basic information about the current browser and return it in JSON objects that model things like history, device's screen, etc
format.
The topmost object in BOM is the window object, which represents the current browser window or tab.
function getBrowserInfo() {
var
json = "[{",

/* The array containing the browser info */


info = [
[Link], // Get the User-agent
[Link], // Checks whether cookies are enabled in browser
[Link], // Get the Name of Browser
[Link], // Get the Language of Browser
[Link], // Get the Version of Browser
[Link] // Get the platform for which browser is compiled
],

/* The array containing the browser info names */


infoNames = [
"userAgent",
"cookiesEnabled",
"browserName",
"browserLang",
"browserVersion",
"browserPlatform"
];

/* Creating the JSON object */


for (var i = 0; i < [Link]; i++) {
if (i === [Link] - 1) {
json += '"' + infoNames[i] + '": "' + info[i] + '"';
}
else {
json += '"' + infoNames[i] + '": "' + info[i] + '",';
}
};

return json + "}]";


};

Document: represents current web page.


History: represents pages in browser history.
Location: represents URL of current page.
Navigator: represents information about browser.
Screen: represents device's display information.

Section 48.2: Window Object Properties


The Window Object contains the following properties.

Property Description
[Link] Whether the window has been closed

[Link] – JavaScript® Notes for Professionals 289 [Link] – JavaScript® Notes for Professionals 290
[Link]
[Link]
Number of <iframe> elements in window
Gets or sets the name of the window
Chapter 49: The Event Loop
[Link] Height of window
[Link] Width of window
Section 49.1: The event loop in a web browser
[Link] X-coordinate of pointer, relative to top left corner of screen The vast majority of modern JavaScript environments work according to an event loop. This is a common concept in
[Link] Y-coordinate of pointer, relative to top left corner of screen computer programming which essentially means that your program continually waits for new things to happen,
[Link] Current URL of window object (or local file path) and when they do, reacts to them. The host environment calls into your program, spawning a "turn" or "tick" or
[Link] Reference to history object for browser window or tab. "task" in the event loop, which then runs to completion. When that turn has finished, the host environment waits for
[Link] Reference to screen object something else to happen, before all this starts.
[Link]ffset Distance document has been scrolled horizontally
A simple example of this is in the browser. Consider the following example:
[Link]ffset Distance document has been scrolled vertically
<!DOCTYPE html>
Section 48.3: Window Object Methods <title>Event loop example</title>

<script>
The most important object in the Browser Object Model is the window object. It helps in accessing information
[Link]("this a script entry point");
about the browser and its components. To access these features, it has various methods and properties.
[Link] = () => {
Method Description [Link]("onclick");
[Link]() Creates dialog box with message and an OK button };
[Link]() Remove focus from window
setTimeout(() => {
[Link]() Closes a browser window [Link]("setTimeout callback log 1");
[Link]firm() Creates dialog box with message, an OK button and a cancel button [Link]("setTimeout callback log 2");
[Link]() Get CSS styles applied to an element }, 100);
</script>
[Link](x,y) Move a window's left and top edge to supplied coordinates
[Link]() Opens new browser window with URL specified as parameter In this example, the host environment is the web browser.
[Link]() Tells browser that user wants to print contents of current page
[Link]() Creates dialog box for retrieving user input 1. The HTML parser will first execute the <script>. It will run to completion.
2. The call to setTimeout tells the browser that, after 100 milliseconds, it should enqueue a task to perform the
[Link]() Scrolls the document by the specified number of pixels
given action.
[Link]() Scrolls the document to the specified coordinates
3. In the meantime, the event loop is then responsible for continually checking if there's something else to do:
[Link]() Do something repeatedly at specified intervals
for example, rendering the web page.
[Link]() Do something after a specified amount of time 4. After 100 milliseconds, if the event loop is not busy for some other reason, it will see the task that
[Link]() Stop window from loading setTimeout enqueues, and run the function, logging those two statements.
5. At any time, if someone clicks on the body, the browser will post a task to the event loop to run the click
handler function. The event loop, as it goes around continually checking what to do, will see this, and run that
function.

You can see how in this example there are several different types of entry points into JavaScript code, which the
event loop invokes:

The <script> element is invoked immediately


The setTimeout task is posted to the event loop and run once
The click handler task can be posted many times and run each time

Each turn of the event loop is responsible for many things; only some of them will invoke these JavaScript tasks. For
full details, see the HTML specification

One last thing: what do we mean by saying that each event loop task "runs to completion"? We mean that it is not
generally possible to interrupt a block of code that is queued to run as a task, and it is never possible to run code
interleaved with another block of code. For example, even if you clicked at the perfect time, you could never get the

[Link] – JavaScript® Notes for Professionals 291 [Link] – JavaScript® Notes for Professionals 292
above code to log "onclick" in between the two setTimeout callback log 1/2"s. This is due to the way the task-
posting works; it is cooperative and queue-based, instead of preemptive. Chapter 50: Strict mode
Section 49.2: Asynchronous operations and the event loop Section 50.1: For entire scripts
Many interesting operations in common JavaScript programming environments are asynchronous. For example, in Strict mode can be applied on entire scripts by placing the statement "use strict"; before any other statements.
the browser we see things like
"use strict";
// strict mode now applies for the rest of the script
[Link](() => {
[Link]("this happens later");
}, 100); Strict mode is only enabled in scripts where you define "use strict". You can combine scripts with and without
strict mode, because the strict state is not shared among different scripts.
and in [Link] we see things like
Version ≥ 6

[Link]("[Link]", (err, data) => {


Note: All code written inside ES2015+ modules and classes are strict by default.
[Link]("data");
});

How does this fit with the event loop?


Section 50.2: For functions
Strict mode can also be applied to single functions by prepending the "use strict"; statement at the beginning of
How this works is that when these statements execute, they tell the host environment (i.e., the browser or [Link]
the function declaration.
runtime, respectively) to go off and do something, probably in another thread. When the host environment is done
doing that thing (respectively, waiting 100 milliseconds or reading the file [Link]) it will post a task to the event
function strict() {
loop, saying "call the callback I was given earlier with these arguments". "use strict";
// strict mode now applies to the rest of this function
The event loop is then busy doing its thing: rendering the webpage, listening for user input, and continually looking var innerFunction = function () {
for posted tasks. When it sees these posted tasks to call the callbacks, it will call back into JavaScript. That's how you // strict mode also applies here
get asynchronous behavior! };
}

function notStrict() {
// but not here
}

Strict mode will also apply to any inner scoped functions.

Section 50.3: Changes to properties


Strict mode also prevents you from deleting undeletable properties.

"use strict";
delete [Link]; // throws a TypeError

The above statement would simply be ignored if you don't use strict mode, however now you know why it does not
execute as expected.

It also prevents you from extending a non-extensible property.

var myObject = {name: "My Name"}


[Link](myObject);

function setAge() {
[Link] = 25; // No errors
}

function setAge() {

[Link] – JavaScript® Notes for Professionals 293 [Link] – JavaScript® Notes for Professionals 294
"use strict"; function strict_scope() {
[Link] = 25; // TypeError: can't define property "age": Object is not extensible "use strict";
} a = "bar"; // variable is global
}

Section 50.4: Changes to global properties var a;


strict_scope();
[Link](a); // >> bar
In a non-strict-mode scope, when a variable is assigned without being initialized with the var, const or the let
keyword, it is automatically declared in the global scope:
Section 50.5: Duplicate Parameters
a = 12;
[Link](a); // 12 Strict mode does not allow you to use duplicate function parameter names.

In strict mode however, any access to an undeclared variable will throw a reference error: function foo(bar, bar) {} // No error. bar is set to the final argument when called

"use strict";
"use strict";
function foo(bar, bar) {}; // SyntaxError: duplicate formal argument bar
a = 12; // ReferenceError: a is not defined
[Link](a);
Section 50.6: Function scoping in strict mode
This is useful because JavaScript has a number of possible events that are sometimes unexpected. In non-strict-
mode, these events often lead developers to believe they are bugs or unexpected behavior, thus by enabling strict- In Strict Mode, functions declared in a local block are inaccessible outside the block.
mode, any errors that are thrown enforces them to know exactly what is being done.
"use strict";
{
f(); // 'hi'
"use strict";
function f() {[Link]('hi');}
// Assuming a global variable mistypedVariable exists
}
mistypedVaraible = 17; // this line throws a ReferenceError due to the
f(); // ReferenceError: f is not defined
// misspelling of variable

Scope-wise, function declarations in Strict Mode have the same kind of binding as let or const.
This code in strict mode displays one possible scenario: it throws a reference error which points to the assignment's
line number, allowing the developer to immediately detect the mistype in the variable's name.
Section 50.7: Behaviour of a function's arguments list
In non-strict-mode, besides the fact that no error is thrown and the assignment is successfully made, the
arguments object behave different in strict and non strict mode. In non-strict mode, the argument object will reflect
mistypedVaraible will be automatically declared in the global scope as a global variable. This implies that the
the changes in the value of the parameters which are present, however in strict mode any changes to the value of
developer needs to look up manually this specific assignment in the code.
the parameter will not be reflected in the argument object.
Furthermore, by forcing declaration of variables, the developer cannot accidentally declare global variables inside
functions. In non-strict-mode: function add(a, b){
[Link](arguments[0], arguments[1]); // Prints : 1,2

function foo() {
a = 5, b = 10;
a = "bar"; // variable is automatically declared in the global scope
}
[Link](arguments[0], arguments[1]); // Prints : 5,10
foo();
}
[Link](a); // >> bar
add(1, 2);
In strict mode, it is necessary to explicitly declare the variable:
For the above code, the arguments object is changed when we change the value of the parameters. However, for
function strict_scope() { strict mode, the same will not be reflected.
"use strict";
var a = "bar"; // variable is local
function add(a, b) {
}
'use strict';
strict_scope();
[Link](a); // >> "ReferenceError: a is not defined"
[Link](arguments[0], arguments[1]); // Prints : 1,2

The variable can also be declared outside and after a function, allowing it to be used, for instance, in the global a = 5, b = 10;
scope:
[Link](arguments[0], arguments[1]); // Prints : 1,2

[Link] – JavaScript® Notes for Professionals 295 [Link] – JavaScript® Notes for Professionals 296
} }

It's worth noting that, if any one of the parameters is undefined, and we try to change the value of the parameter in Destructuring
both strict-mode or non-strict mode the arguments object remains unchanged.
function a({ x }) {
"use strict";
Strict mode
}

function add(a, b) { Rest params


'use strict';
function a(...args) {
[Link](arguments[0], arguments[1]); // undefined,undefined "use strict";
// 1,undefined }
a = 5, b = 10;

[Link](arguments[0], arguments[1]); // undefined,undefined


// 1, undefined
}
add();
// undefined,undefined
// undefined,undefined

add(1)
// 1, undefined
// 1, undefined

Non-Strict Mode

function add(a,b) {

[Link](arguments[0],arguments[1]);

a = 5, b = 10;

[Link](arguments[0],arguments[1]);
}
add();
// undefined,undefined
// undefined,undefined

add(1);
// 1, undefined
// 5, undefined

Section 50.8: Non-Simple parameter lists


function a(x = 5) {
"use strict";
}

is invalid JavaScript and will throw a SyntaxError because you cannot use the directive "use strict" in a function
with Non-Simple Parameter list like the one above - default assignment x = 5

Non-Simple parameters include -

Default assignment

function a(x = 1) {
"use strict";

[Link] – JavaScript® Notes for Professionals 297 [Link] – JavaScript® Notes for Professionals 298
Chapter 51: Custom Elements Chapter 52: Data Manipulation
Parameter Details Section 52.1: Format numbers as money
name The name of the new custom element.
[Link] The name of the native element being extended, if any. Fast and short way to format value of type Number as money, e.g. 1234567.89 => "1,234,567.89":
[Link] The custom prototype to use for the custom element, if any.
var num = 1234567.89,
formatted;
Section 51.1: Extending Native Elements
formatted = [Link](2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // "1,234,567.89"
It's possible to extent native elements, but their descendants don't get to have their own tag names. Instead, the is
attribute is used to specify which subclass an element is supposed to use. For example, here's an extension of the More advanced variant with support of any number of decimals [0 .. n], variable size of number groups [0 .. x]
<img> element which logs a message to the console when it's loaded. and different delimiter types:

const prototype = [Link]([Link]); /**


[Link] = function() { * [Link](n, x, s, c)
[Link]('load', event => { *
[Link]("Image loaded successfully."); * @param integer n: length of decimal
}); * @param integer x: length of whole part
}; * @param mixed s: sections delimiter
* @param mixed c: decimal delimiter
[Link]('ex-image', { extends: 'img', prototype: prototype }); */
[Link] = function(n, x, s, c) {
<img is="ex-image" src="[Link] />
var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
num = [Link]([Link](0, ~~n));
Section 51.2: Registering New Elements return (c ? [Link]('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};
Defines an <initially-hidden> custom element which hides its contents until a specified number of seconds have
elapsed. [Link](2, 3, '.', ','); // "12.345.678,90"
[Link](4, 4, ' ', ':'); // "12 3456:7890"
const InitiallyHiddenElement = [Link]('initially-hidden', class extends [Link](0, 3, '-'); // "12-345-679"
HTMLElement { 123456789..format(2); // "123,456,789.00"
createdCallback() {
[Link] = null;
} Section 52.2: Extract extension from file name
attachedCallback() { Fast and short way to extract extension from file name in JavaScript will be:
const seconds = Number([Link]('for'));
[Link] = 'none'; function get_extension(filename) {
[Link] = setTimeout(() => { return [Link](([Link]('.') - 1 >>> 0) + 2);
[Link] = 'block'; }
}, seconds * 1000);
}
It works correctly both with names having no extension (e.g. myfile) or starting with . dot (e.g. .htaccess):
detachedCallback() {
if ([Link]) { get_extension('') // ""
clearTimeout([Link]); get_extension('name') // ""
[Link] = null; get_extension('[Link]') // "txt"
} get_extension('.htpasswd') // ""
} get_extension('[Link]') // "myext"
});

<initially-hidden for="2">Hello</initially-hidden> The following solution may extract file extensions from full path:
<initially-hidden for="5">World</initially-hidden>
function get_extension(path) {
var basename = [Link](/[\\/]/).pop(), // extract file name from full path ...
// (supports `\\` and `/` separators)
pos = [Link]('.'); // get last position of `.`

[Link] – JavaScript® Notes for Professionals 299 [Link] – JavaScript® Notes for Professionals 300
if (basename === '' || pos < 1)
return "";
// if file name is empty or ...
// `.` not found (-1) or comes first (0) Chapter 53: Binary Data
Section 53.1: Getting binary representation of an image file
return [Link](pos + 1); // extract extension ignoring `.`
}

get_extension('/path/to/[Link]'); // "ext" This example is inspired by this question.

We'll assume you know how to load a file using the File API.
Section 52.3: Set object property given its string name
// preliminary code to handle getting local file and finally printing to console
function assign(obj, prop, value) { // the results of our function ArrayBufferToBinary().
if (typeof prop === 'string') var file = // get handle to local file.
prop = [Link]('.'); var reader = new FileReader();
[Link] = function(event) {
if ([Link] > 1) { var data = [Link];
var e = [Link](); [Link](ArrayBufferToBinary(data));
assign(obj[e] = };
[Link](obj[e]) === '[object Object]' [Link](file); //gets an ArrayBuffer of the file
? obj[e]
: {},
Now we perform the actual conversion of the file data into 1's and 0's using a DataView:
prop,
value);
} else function ArrayBufferToBinary(buffer) {
obj[prop[0]] = value; // Convert an array buffer to a string bit-representation: 0 1 1 0 0 0...
} var dataView = new DataView(buffer);
var response = "", offset = (8/8);
var obj = {}, for(var i = 0; i < [Link]; i += offset) {
propName = '[Link]'; response += dataView.getInt8(i).toString(2);
}
assign(obj, propName, 'Value'); return response;
}
// obj == {
// foo : { DataViews let you read/write numeric data; getInt8 converts the data from the byte position - here 0, the value
// bar : {
passed in - in the ArrayBuffer to signed 8-bit integer representation, and toString(2) converts the 8-bit integer to
// foobar : 'Value'
// } binary representation format (i.e. a string of 1's and 0's).
// }
// } Files are saved as bytes. The 'magic' offset value is obtained by noting we are taking files stored as bytes i.e. as 8-bit
integers and reading it in 8-bit integer representation. If we were trying to read our byte-saved (i.e. 8 bits) files to
32-bit integers, we would note that 32/8 = 4 is the number of byte spaces, which is our byte offset value.

For this task, DataViews are overkill. They are typically used in cases where endianness or heterogeneity of data are
encountered (e.g. in reading PDF files, which have headers encoded in different bases and we would like to
meaningfully extract that value). Because we just want a textual representation, we do not care about
heterogeneity as there is never a need to

A much better - and shorter - solution can be found using an UInt8Array typed array, which treats the entire
ArrayBuffer as composed of unsigned 8-bit integers:

function ArrayBufferToBinary(buffer) {
var uint8 = new Uint8Array(buffer);
return [Link]((binary, uint8) => binary + [Link](2), "");
}

Section 53.2: Converting between Blobs and ArrayBuers


JavaScript has two primary ways to represent binary data in the browser. ArrayBuffers/TypedArrays contain
mutable (though still fixed-length) binary data which you can directly manipulate. Blobs contain immutable binary

[Link] – JavaScript® Notes for Professionals 301 [Link] – JavaScript® Notes for Professionals 302
data which can only be accessed through the asynchronous File interface. var characters = atob(data);

Convert a Blob to an ArrayBuffer (asynchronous) var array = new Uint8Array([Link]);

var blob = new Blob(["\x01\x02\x03\x04"]), for (var i = 0; i < [Link]; i++) {


fileReader = new FileReader(), array[i] = [Link](i);
array; }

[Link] = function() {
array = [Link]; Section 53.5: Using TypedArrays
[Link]("Array contains", [Link], "bytes.");
}; TypedArrays are a set of types providing different views into fixed-length mutable binary ArrayBuffers. For the most
part, they act like Arrays that coerce all assigned values to a given numeric type. You can pass an ArrayBuffer
[Link](blob);
instance to a TypedArray constructor to create a new view of its data.
Version ≥ 6
Convert a Blob to an ArrayBuffer using a Promise (asynchronous)
var buffer = new ArrayBuffer(8);
var blob = new Blob(["\x01\x02\x03\x04"]); var byteView = new Uint8Array(buffer);
var floatView = new Float64Array(buffer);
var arrayPromise = new Promise(function(resolve) {
var reader = new FileReader(); [Link](byteView); // [0, 0, 0, 0, 0, 0, 0, 0]
[Link](floatView); // [0]
[Link] = function() { byteView[0] = 0x01;
resolve([Link]); byteView[1] = 0x02;
}; byteView[2] = 0x04;
byteView[3] = 0x08;
[Link](blob); [Link](floatView); // [6.64421383e-316]
});

[Link](function(array) { ArrayBuffers can be copied using the .slice(...) method, either directly or through a TypedArray view.
[Link]("Array contains", [Link], "bytes.");
}); var byteView2 = [Link]();
var floatView2 = new Float64Array([Link]);
Convert an ArrayBuffer or typed array to a Blob
byteView2[6] = 0xFF;
var array = new Uint8Array([0x04, 0x06, 0x07, 0x08]); [Link](floatView); // [6.64421383e-316]
[Link](floatView2); // [7.06327456e-304]
var blob = new Blob([array]);

Section 53.6: Iterating through an arrayBuer


Section 53.3: Manipulating ArrayBuers with DataViews
For a convenient way to iterate through an arrayBuffer, you can create a simple iterator that implements the
DataViews provide methods to read and write individual values from an ArrayBuffer, instead of viewing the entire DataView methods under the hood:
thing as an array of a single type. Here we set two bytes individually then interpret them together as a 16-bit
unsigned integer, first big-endian then little-endian. var ArrayBufferCursor = function() {
var ArrayBufferCursor = function(arrayBuffer) {
var buffer = new ArrayBuffer(2); [Link] = new DataView(arrayBuffer, 0);
var view = new DataView(buffer); [Link] = [Link];
[Link] = 0;
view.setUint8(0, 0xFF); }
view.setUint8(1, 0x01);
[Link] = function(type) {
[Link](view.getUint16(0, false)); // 65281 switch(type) {
[Link](view.getUint16(0, true)); // 511 case 'Uint8':
var result = [Link].getUint8([Link]);
[Link] += 1;
Section 53.4: Creating a TypedArray from a Base64 string return result;
case 'Int16':
var data = var result = [Link].getInt16([Link], true);
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACN' + [Link] += 2;
'byblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHx' + return result;
'gljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; case 'Uint16':
var result = [Link].getUint16([Link], true);

[Link] – JavaScript® Notes for Professionals 303 [Link] – JavaScript® Notes for Professionals 304
[Link] += 2;
return result;
case 'Int32':
Chapter 54: Template Literals
var result = [Link].getInt32([Link], true);
Template literals are a type of string literal that allows values to be interpolated, and optionally the interpolation
[Link] += 4;
return result; and construction behaviour to be controlled using a "tag" function.
case 'Uint32':
var result = [Link].getUint32([Link], true);
[Link] += 4;
Section 54.1: Basic interpolation and multiline strings
return result;
Template literals are a special type of string literal that can be used instead of the standard '...' or "...". They
case 'Float':
case 'Float32': are declared by quoting the string with backticks instead of the standard single or double quotes: `...`.
var result = [Link].getFloat32([Link], true);
[Link] += 4; Template literals can contain line breaks and arbitrary expressions can be embedded using the ${ expression }
return result; substitution syntax. By default, the values of these substitution expressions are concatenated directly into the
case 'Double': string where they appear.
case 'Float64':
var result = [Link].getFloat64([Link], true);
const name = "John";
[Link] += 8;
const score = 74;
return result;
default:
[Link](`Game Over!
throw new Error("Unknown datatype");
}
${name}'s score was ${score * 10}.`);
};
Game Over!
[Link] = function() {
return [Link] < [Link]; John's score was 740.
}

return ArrayBufferCursor; Section 54.2: Tagged strings


});
A function identified immediately before a template literal is used to interpret it, in what is called a tagged
You can then create an iterator like this: template literal. The tag function can return a string, but it can also return any other type of value.

var cursor = new ArrayBufferCursor(arrayBuffer); The first argument to the tag function, strings, is an Array of each constant piece of the literal. The remaining
arguments, ...substitutions, contain the evaluated values of each ${} substitution expression.
You can use the hasNext to check if there's still items
function settings(strings, ...substitutions) {
for(;[Link]();) { const result = new Map();
// There's still items to process for (let i = 0; i < [Link]; i++) {
} [Link](strings[i].trim(), substitutions[i]);
}
return result;
You can use the next method to take the next value: }

var nextValue = [Link]('Float'); const remoteConfiguration = settings`


label ${'Content'}
With such an iterator, writing your own parser to process binary data becomes pretty easy. servers ${2 * 8 + 1}
hostname ${[Link]}
`;

Map {"label" => "Content", "servers" => 17, "hostname" => "[Link]"}

The strings Array has a special .raw property referencing a parallel Array of the same constant pieces of the
template literal but exactly as they appear in the source code, without any backslash-escapes being replaced.

function example(strings, ...substitutions) {


[Link]('strings:', strings);
[Link]('...substitutions:', substitutions);
}

[Link] – JavaScript® Notes for Professionals 305 [Link] – JavaScript® Notes for Professionals 306
example`Hello ${'world'}.\n\nHow are you?`; <ul> ${[Link](name => HTML`
<li>${name}</li>
strings: ["Hello ", ".\n\nHow are you?", raw: ["Hello ", ".\\n\\nHow are you?"]]
`)} </ul>
substitutions: ["world"]
`;

Section 54.3: Raw strings Section 54.5: Introduction


The [Link] tag function can be used with template literals to access a version of their contents without Template Literals act like strings with special features. They are enclosed by by the back-tick `` and can be spanned
interpreting any backslash escape sequences. across multiple lines.

[Link]`\n` will contain a backslash and the lowercase letter n, while `\n` or '\n' would contain a single
Template Literals can contain embedded expressions too. These expressions are indicated by a $ sign and curly
newline character instead. braces {}

const patternString = [Link]`Welcome, (\w+)!`;


//A single line Template Literal
const pattern = new RegExp(patternString);
var aLiteral = `single line string data`;

const message = "Welcome, John!";


[Link](message);
//Template Literal that spans across lines
["Welcome, John!", "John"] var anotherLiteral = `string data that spans
across multiple lines of code`;

Section 54.4: Templating HTML With Template Strings //Template Literal with an embedded expression
var x = 2;
You can create an HTML`...` template string tag function to automatically encodes interpolated values. (This var y = 3;
var theTotal = `The total is ${x + y}`; // Contains "The total is 5"
requires that interpolated values are only used as text, and may not be safe if interpolated values are used in
code such as scripts or styles.)

class HTMLString extends String { //Comparison of a string and a template literal


static escape(text) { var aString = "single line string data"
if (text instanceof HTMLString) { [Link](aString === aLiteral) //Returns true
return text;
}
There are many other features of String Literals such as Tagged Template Literals and Raw property. These are
return new HTMLString(
String(text)
demonstrated in other examples.
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/\\/g, '&#39;'));
}
}

function HTML(strings, ...substitutions) {


const escapedFlattenedSubstitutions =
[Link](s => [].concat(s).map([Link]).join(''));
const pieces = [];
for (const i of [Link]()) {
[Link](strings[i], escapedFlattenedSubstitutions [i] || '');
}
return new HTMLString([Link](''));
}

const title = "Hello World";


const iconSrc = "/images/[Link]";
const names = ["John", "Jane", "Joe", "Jill"];

[Link] = HTML`
<h1><img src="${iconSrc}" /> ${title}</h1>

[Link] – JavaScript® Notes for Professionals 307 [Link] – JavaScript® Notes for Professionals 308
Chapter 55: Fetch Section 55.4: Send cookies
The fetch function does not send cookies by default. There are two possible ways to send cookies:
Options Details
method The HTTP method to use for the request. ex: GET, POST, PUT, DELETE, HEAD. Defaults to GET. 1. Only send cookies if the URL is on the same origin as the calling script.
headers A Headers object containing additional HTTP headers to include in the request.
fetch('/login', {
body The request payload, can be a string or a FormData object. Defaults to undefined
credentials: 'same-origin'
cache The caching mode. default, reload, no-cache })
referrer The referrer of the request.
2. Always send cookies, even for cross-origin calls.
mode cors, no-cors, same-origin. Defaults to no-cors.
credentials omit, same-origin, include. Defaults to omit. fetch('[Link] {
redirect follow, error, manual. Defaults to follow. credentials: 'include'
})
integrity Associated integrity metadata. Defaults to empty string.

Section 55.1: Getting JSON data Section 55.5: GlobalFetch


The GlobalFetch interface exposes the fetch function, which can be used to request resources.
// get some data from stackoverflow
fetch("[Link]
fetch('/path/to/[Link]')
flow")
.then(response => {
.then(resp => [Link]())
if (![Link]()) {
.then(json => [Link](json))
throw new Error("Request failed!");
.catch(err => [Link](err));
}

Section 55.2: Set Request Headers return [Link]();


})
.then(json => {
fetch('/[Link]', {
[Link](json);
headers: new Headers({
});
'Accept': 'text/plain',
'X-Your-Custom-Header': 'example value'
}) The resolved value is a Response Object. This Object contains the body of the response, as well as its status and
}); headers.

Section 55.3: POST Data Section 55.6: Using Fetch to Display Questions from the Stack
Overflow API
Posting form data
const url =
fetch(`/example/submit`, { '[Link]
method: 'POST',
body: new FormData([Link]('example-form')) const questionList = [Link]('ul');
}); [Link](questionList);

const responseData = fetch(url).then(response => [Link]());


Posting JSON data
[Link](({items, has_more, quota_max, quota_remaining}) => {
for (const {title, score, owner, link, answer_count} of items) {
fetch(`/example/[Link]`, { const listItem = [Link]('li');
method: 'POST', [Link](listItem);
body: [Link]({ const a = [Link]('a');
email: [Link]('example-email').value, [Link](a);
comment: [Link]('example-comment').value [Link] = link;
}) [Link] = `[${score}] ${title} (by ${owner.display_name || 'somebody'})`
}); }
});

[Link] – JavaScript® Notes for Professionals 309 [Link] – JavaScript® Notes for Professionals 310
Chapter 56: Scope },
increment: function () {
counter++;

Section 56.1: Closures


}
};
}
When a function is declared, variables in the context of its declaration are captured in its scope. For example, in the
code below, the variable x is bound to a value in the outer scope, and then the reference to x is captured in the var a = makeCounter();
context of bar: var b = makeCounter();

[Link]();
var x = 4; // declaration in outer scope
[Link]([Link]());
function bar() {
[Link]([Link]());
[Link](x); // outer scope is captured on declaration
}

bar(); // prints 4 to console Sample output:

10
Sample output: 4
When makeCounter() is called, a snapshot of the context of that function is saved. All code inside makeCounter()
will use that snapshot in their execution. Two calls of makeCounter() will thus create two different snapshots, with
This concept of "capturing" scope is interesting because we can use and modify variables from an outer scope even their own copy of counter.
after the outer scope exits. For example, consider the following:
Immediately-invoked function expressions (IIFE)
function foo() {
var x = 4; // declaration in outer scope Closures are also used to prevent global namespace pollution, often through the use of immediately-invoked
function expressions.
function bar() {
[Link](x); // outer scope is captured on declaration Immediately-invoked function expressions (or, perhaps more intuitively, self-executing anonymous functions) are
}
essentially closures that are called right after declaration. The general idea with IIFE's is to invoke the side-effect of
return bar; creating a separate context that is accessible only to the code within the IIFE.

// x goes out of scope after foo returns Suppose we want to be able to reference jQuery with $. Consider the naive method, without using an IIFE:
}
var $ = jQuery;
var barWithX = foo(); // we've just polluted the global namespace by assigning window.$ to jQuery
barWithX(); // we can still access x
In the following example, an IIFE is used to ensure that the $ is bound to jQuery only in the context created by the
closure:
Sample output: 4

(function ($) {
// $ is assigned to jQuery here
In the above example, when foo is called, its context is captured in the function bar. So even after it returns, bar
})(jQuery);
can still access and modify the variable x. The function foo, whose context is captured in another function, is said to // but window.$ binding doesn't exist, so no pollution
be a closure.
See the canonical answer on Stackoverflow for more information on closures.
Private data

This lets us do some interesting things, such as defining "private" variables that are visible only to a specific function Section 56.2: Hoisting
or set of functions. A contrived (but popular) example:
What is hoisting?
function makeCounter() {
var counter = 0; Hoisting is a mechanism which moves all variable and function declarations to the top of their scope. However,
variable assignments still happen where they originally were.
return {
value: function () { For example, consider the following code:
return counter;

[Link] – JavaScript® Notes for Professionals 311 [Link] – JavaScript® Notes for Professionals 312
var bar = function () {};
[Link](foo); // → undefined
var foo = 42;
[Link](foo); // → 42
// Valid code:
foo();
The above code is the same as: function foo() {
bar();
var foo; // → Hoisted variable declaration }
function bar() {}
[Link](foo); // → undefined
foo = 42; // → variable assignment remains in the same place
[Link](foo); // → 42
// Invalid code:
foo();
Note that due to hoisting the above undefined is not the same as the not defined resulting from running: function foo() {
bar(); // → TypeError: bar is not a function
[Link](foo); // → foo is not defined }
var bar = function () {};

A similar principle applies to functions. When functions are assigned to a variable (i.e. a function expression), the
variable declaration is hoisted while the assignment remains in the same place. The following two code snippets are // (E) valid:
equivalent. function foo() {
bar();
}
[Link](foo(2, 3)); // → foo is not a function
var bar = function(){};
foo();
var foo = function(a, b) {
return a * b; Limitations of Hoisting
}
Initializing a variable can not be Hoisted or In simple JavaScript Hoists declarations not initialization.
var foo;
[Link](foo(2, 3)); // → foo is not a function
For example: The below scripts will give different outputs.
foo = function(a, b) {
return a * b;
} var x = 2;
var y = 4;
alert(x + y);
When declaring function statements, a different scenario occurs. Unlike function statements, function declarations
are hoisted to the top of their scope. Consider the following code:
This will give you an output of 6. But this...

[Link](foo(2, 3)); // → 6
var x = 2;
function foo(a, b) {
alert(x + y);
return a * b;
var y = 4;
}

This will give you an output of NaN. Since we are initializing the value of y, the JavaScript Hoisting is not happening,
The above code is the same as the next code snippet due to hoisting:
so the y value will be undefined. The JavaScript will consider that y is not yet declared.
function foo(a, b) {
So the second example is same as of below.
return a * b;
}
var x = 2;
[Link](foo(2, 3)); // → 6 var y;
alert(x + y);
y = 4;
Here are some examples of what is and what isn't hoisting:

This will give you an output of NaN.


// Valid code:
foo();

function foo() {}

// Invalid code:
bar(); // → TypeError: bar is not a function

[Link] – JavaScript® Notes for Professionals 313 [Link] – JavaScript® Notes for Professionals 314
let j = 10;
}
[Link](i); // >> "ReferenceError: i is not defined"
[Link](j); // >> "ReferenceError: j is not defined"

Note that i and j are only declared in the for loop and are therefore undeclared outside of it.

There are several other crucial differences:

Global variable declaration

In the top scope (outside any functions and blocks), var declarations put an element in the global object. let does
not:
Section 56.3: Dierence between var and let
var x = 4;
(Note: All examples using let are also valid for const) let y = 7;

var is available in all versions of JavaScript, while let and const are part of ECMAScript 6 and only available in some [Link](this.x); // >> 4
newer browsers. [Link](this.y); // >> undefined

Re-declaration
var is scoped to the containing function or the global space, depending when it is declared:
Declaring a variable twice using var doesn't produce an error (even though it's equivalent to declaring it once):
var x = 4; // global scope
var x = 4;
function DoThings() { var x = 7;
var x = 7; // function scope
[Link](x);
With let, this produces an error:
}

[Link](x); // >> 4 let x = 4;


DoThings(); // >> 7 let x = 7;
[Link](x); // >> 4

That means it "escapes" if statements and all similar block constructs: TypeError: Identifier x has already been declared

var x = 4;
The same is true when y is declared with var:
if (true) {
var x = 7;
} var y = 4;
[Link](x); // >> 7 let y = 7;

for (var i = 0; i < 4; i++) {


var j = 10; TypeError: Identifier y has already been declared
}
[Link](i); // >> 4
[Link](j); // >> 10 However variables declared with let can be reused (not re-declared) in a nested block

By comparison, let is block scoped: let i = 5;


{
let x = 4; let i = 6;
[Link](i); // >> 6
if (true) { }
let x = 7; [Link](i); // >> 5
[Link](x); // >> 7
} Within the block the outer i can be accessed, but if the within block has a let declaration for i, the outer i can not
be accessed and will throw a ReferenceError if used before the second is declared.
[Link](x); // >> 4

let i = 5;
for (let i = 0; i < 4; i++) {

[Link] – JavaScript® Notes for Professionals 315 [Link] – JavaScript® Notes for Professionals 316
{ Notice that apply allows you to pass an Array or the arguments object (array-like) as the list of arguments, whereas,
i = 6; // outer i is unavailable within the Temporal Dead Zone
call needs you to pass each argument separately.
let i;
}
These two methods give you the freedom to get as fancy as you want, like implementing a poor version of the
ECMAScript's native bind to create a function that will always be called as a method of an object from an original
ReferenceError: i is not defined function.

function bind (func, obj) {


Hoisting return function () {
return [Link](obj, [Link](arguments, 1));
Variables declared both with var and let are hoisted. The difference is that a variable declared with var can be }
}
referenced before its own assignment, since it gets automatically assigned (with undefined as its value), but let
cannot–it specifically requires the variable to be declared before being invoked: var obj = { name: "Foo" };

[Link](x); // >> undefined function print() {


[Link](y); // >> "ReferenceError: `y` is not defined" [Link]([Link]);
//OR >> "ReferenceError: can't access lexical declaration `y` before initialization" }
var x = 4;
let y = 7; printObj = bind(print, obj);

printObj();
The area between the start of a block and a let or const declaration is known as the Temporal Dead Zone, and any
references to the variable in this area will cause a ReferenceError. This happens even if the variable is assigned
This will log
before being declared:

y=7; // >> "ReferenceError: `y` is not defined" "Foo"


let y;

In non-strict-mode, assigning a value to a variable without any declaration, automatically declares the variable in
the global scope. In this case, instead of y being automatically declared in the global scope, let reserves the
variable's name (y) and does not allow any access or assignment to it before the line where it is declared/initialized. The bind function has a lot going on

1. obj will be used as the value of this


Section 56.4: Apply and Call syntax and invocation 2. forward the arguments to the function
3. and then return the value
The apply and call methods in every function allow it to provide a custom value for this.

function print() { Section 56.5: Arrow function invocation


[Link]([Link]);
} Version ≥ 6

[Link]({ toPrint: "Foo" }); // >> "Foo" When using arrow functions this takes the value from the enclosing execution context's this (that is, this in arrow
[Link]({ toPrint: "Foo" }); // >> "Foo" functions has lexical scope rather than the usual dynamic scope). In global code (code that doesn't belong to any
function) it would be the global object. And it keeps that way, even if you invoke the function declared with the
You might notice that the syntax for both the invocations used above are the same. i.e. The signature looks similar. arrow notation from any of the others methods here described.

But there is a small difference in their usage, since we are dealing with functions and changing their scopes, we still var globalThis = this; //"window" in a browser, or "global" in [Link]
need to maintain the original arguments passed to the function. Both apply and call support passing arguments
to the target function as follows: var foo = (() => this);

[Link](foo() === globalThis); //true


function speak() {
var sentences = [Link](arguments);
var obj = { name: "Foo" };
[Link]([Link]+": "+sentences);
[Link]([Link](obj) === globalThis); //true
}
var person = { name: "Sunny" };
[Link](person, ["I", "Code", "Startups"]); // >> "Sunny: I Code Startups" See how this inherits the context rather than referring to the object the method was called on.
[Link](person, "I", "<3", "Javascript"); // >> "Sunny: I <3 Javascript"
var globalThis = this;

[Link] – JavaScript® Notes for Professionals 317 [Link] – JavaScript® Notes for Professionals 318
var obj = {
withoutArrow: function() {
Section 56.8: Anonymous invocation
return this;
Invoking a function as an anonymous function, this will be the global object (self in the browser).
},
withArrow: () => this
}; function func() {
return this;
[Link]([Link]() === obj); //true }
[Link]([Link]() === globalThis); //true
func() === window; // true
var fn = [Link]; //no longer calling withoutArrow as a method Version = 5
var fn2 = [Link];
[Link](fn() === globalThis); //true In ECMAScript 5's strict mode, this will be undefined if the function is invoked anonymously.
[Link](fn2() === globalThis); //true
(function () {

Section 56.6: Bound invocation "use strict";


func();
}())
The bind method of every function allows you to create new version of that function with the context strictly bound
to a specific object. It is especially useful to force a function to be called as a method of an object.
This will output

var obj = { foo: 'bar' };


undefined
function foo() {
return [Link];
}

fooObj = [Link](obj);
Section 56.9: Constructor invocation
fooObj(); When a function is invoked as a constructor with the new keyword this takes the value of the object being
constructed
This will log:
function Obj(name) {
[Link] = name;
bar }

var obj = new Obj("Foo");

Section 56.7: Method invocation [Link](obj);

Invoking a function as a method of an object the value of this will be that object.
This will log

var obj = {
name: "Foo", { name: "Foo" }
print: function () {
[Link]([Link])

Section 56.10: Using let in loops instead of var (click handlers


}
}
example)
We can now invoke print as a method of obj. this will be obj
Let's say we need to add a button for each piece of loadedData array (for instance, each button should be a slider
[Link](); showing the data; for the sake of simplicity, we'll just alert a message). One may try something like this:

for(var i = 0; i < [Link]; i++)


This will thus log:
jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
.children().last() // now let's attach a handler to the button which is a child
.on("click",function() { alert(loadedData[i].content); });
Foo

But instead of alerting, each button will cause the

[Link] – JavaScript® Notes for Professionals 319 [Link] – JavaScript® Notes for Professionals 320
TypeError: loadedData[i] is undefined
Chapter 57: Modules
error. This is because the scope of i is the global scope (or a function scope) and after the loop, i == 3. What we
need is not to "remember the state of i". This can be done using let:
Section 57.1: Defining a module
In ECMAScript 6, when using the module syntax (import/export), each file becomes its own module with a private
for(let i = 0; i < [Link]; i++)
namespace. Top-level functions and variables do not pollute the global namespace. To expose functions, classes,
jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
.children().last() // now let's attach a handler to the button which is a child and variables for other modules to import, you can use the export keyword.
.on("click",function() { alert(loadedData[i].content); });
// not exported
function somethingPrivate() {
An example of loadedData to be tested with this code:
[Link]('TOP SECRET')
}
var loadedData = [
{ label:"apple", content:"green and round" },
{ label:"blackberry", content:"small black or blue" }, export const PI = 3.14;
{ label:"pineapple", content:"weird stuff.. difficult to explain the shape" }
]; export function doSomething() {
[Link]('Hello from a module!')
A fiddle to illustrate this }

function doSomethingElse(){
[Link]("Something else")
}

export {doSomethingElse}

export class MyClass {


test() {}
}

Note: ES5 JavaScript files loaded via <script> tags will remain the same when not using import/export.

Only the values which are explicitly exported will be available outside of the module. Everything else can be
considered private or inaccessible.

Importing this module would yield (assuming the previous code block is in [Link]):

import * as myModule from './[Link]';

[Link]; // 3.14
[Link](); // 'Hello from a module!'
[Link](); // 'Something else'
new [Link](); // an instance of MyClass
[Link](); // This would fail since somethingPrivate was not exported

Section 57.2: Default exports


In addition to named imports, you can provide a default export.

// [Link]
export const PI = 3.14;
export default function area(radius) {
return PI * radius * radius;
}

You can use a simplified syntax to import the default export.

[Link] – JavaScript® Notes for Professionals 321 [Link] – JavaScript® Notes for Professionals 322
import circleArea from './circle'; Section 57.5: Importing named members with aliases
[Link](circleArea(4));
Sometimes you may encounter members that have really long member names, such as
Note that a default export is implicitly equivalent to a named export with the name default, and the imported thisIsWayTooLongOfAName(). In this case, you can import the member and give it a shorter name to use in your
binding (circleArea above) is simply an alias. The previous module can be written like current module:

import { default as circleArea } from './circle'; import {thisIsWayTooLongOfAName as shortName} from 'module'
[Link](circleArea(4));
shortName()
You can only have one default export per module. The name of the default export can be omitted.
You can import multiple long member names like this:
// named export: must have a name
export const PI = 3.14; import {thisIsWayTooLongOfAName as shortName, thisIsAnotherLongNameThatShouldNotBeUsed as
otherName} from 'module'
// default export: name is not required
export default function (radius) { shortName()
return PI * radius * radius; [Link](otherName)
}

And finally, you can mix import aliases with the normal member import:
Section 57.3: Importing named members from another
module import {thisIsWayTooLongOfAName as shortName, PI} from 'module'

shortName()
Given that the module from the Defining a Module section exists in the file [Link], you can import from that
[Link](PI)
module and use its exported members:

import {doSomething, MyClass, PI} from './test' Section 57.6: Importing with side eects
doSomething() Sometimes you have a module that you only want to import so its top-level code gets run. This is useful for polyfills,
other globals, or configuration that only runs once when your module is imported.
const mine = new MyClass()
[Link]() Given a file named [Link]:

[Link](PI)
[Link]('Initializing...')

The somethingPrivate() method was not exported from the test module, so attempting to import it will fail:
You can use it like this:

import {somethingPrivate} from './test'


import './test'
somethingPrivate()
This example will print Initializing... to the console.

Section 57.4: Importing an entire module Section 57.7: Exporting multiple named members
In addition to importing named members from a module or a module's default export, you can also import all
const namedMember1 = ...
members into a namespace binding.
const namedMember2 = ...
const namedMember3 = ...
import * as test from './test'
export { namedMember1, namedMember2, namedMember3 }
[Link]()

All exported members are now available on the test variable. Non-exported members are not available, just as
they are not available with named member imports.

Note: The path to the module './test' is resolved by the loader and is not covered by the ECMAScript specification
- this could be a string to any resource (a path - relative or absolute - on a filesystem, a URL to a network resource,
or any other string identifier).

[Link] – JavaScript® Notes for Professionals 323 [Link] – JavaScript® Notes for Professionals 324
Chapter 58: Screen Chapter 59: Variable coercion/conversion
Section 58.1: Getting the screen resolution Section 59.1: Double Negation (!!x)
To get the physical size of the screen (including window chrome and menubar/launcher): The double-negation !! is not a distinct JavaScript operator nor a special syntax but rather just a sequence of two
negations. It is used to convert the value of any type to its appropriate true or false Boolean value depending on
var width = [Link], whether it is truthy or falsy.
height = [Link];
!!1 // true
Section 58.2: Getting the “available” area of the screen !!0
!!undefined
//
//
false
false
!!{} // true
To get the “available” area of the screen (i.e. not including any bars on the edges of the screen, but including
!![] // true
window chrome and other windows:
The first negation converts any value to false if it is truthy and to true if is falsy. The second negation then operates
var availableArea = {
on a normal Boolean value. Together they convert any truthy value to true and any falsy value to false.
pos: {
x: [Link],
y: [Link] However, many professionals consider the practice of using such syntax unacceptable and recommend simpler to
}, read alternatives, even if they're longer to write:
size: {
width: [Link], x !== 0 // instead of !!x in case x is a number
height: [Link] x != null // instead of !!x in case x is an object, a string, or an undefined
}
};
Usage of !!x is considered poor practice due to the following reasons:

Section 58.3: Page width and height 1. Stylistically it may look like a distinct special syntax whereas in fact it is not doing anything other than two
consecutive negations with implicit type conversion.
To get current page width and height (for any browser), e.g. when programming responsiveness: 2. It is better to provide information about types of values stored in variables and properties through the code.
For example, x !== 0 says that x is probably a number, whereas !!x does not convey any such advantage to
function pageWidth() { readers of the code.
return [Link] != null? [Link] : [Link] &&
3. Usage of Boolean(x) allows for similar functionality, and is a more explicit conversion of type.
[Link] ? [Link] : [Link] != null
? [Link] : null;
} Section 59.2: Implicit conversion
function pageHeight() { JavaScript will try to automatically convert variables to more appropriate types upon use. It's usually advised to do
return [Link] != null? [Link] : [Link] &&
conversions explicitly (see other examples), but it's still worth knowing what conversions take place implicitly.
[Link] ? [Link] : [Link] !=
null? [Link] : null;
} "1" + 5 === "15" // 5 got converted to string.
1 + "5" === "15" // 1 got converted to string.
1 - "5" === -4 // "5" got converted to a number.
Section 58.4: Window innerWidth and innerHeight Properties alert({}) // alerts "[object Object]", {} got converted to string.
!0 === true // 0 got converted to boolean
Get the window height and width if ("hello") {} // runs, "hello" got converted to boolean.
new Array(3) === ",,"; // Return true. The array is converted to string - [Link]();

var width = [Link]


var height = [Link] Some of the trickier parts:

Section 58.5: Getting color information about the screen !"0" === false // "0" got converted to true, then reversed.
!"false" === false // "false" converted to true, then reversed.

To determine the color and pixel depths of the screen:


Section 59.3: Converting to boolean
var pixelDepth = [Link],
colorDepth = [Link]; Boolean(...) will convert any data type into either true or false.

[Link] – JavaScript® Notes for Professionals 325 [Link] – JavaScript® Notes for Professionals 326
Boolean("true") === true parseInt('0', 10) will convert the string ('0') into a number (0), don't forget the second argument, which is radix.
Boolean("false") === true If not given, parseInt could convert string to wrong number.
Boolean(-1) === true
Boolean(1) === true
Boolean(0) === false Section 59.5: Converting a number to a string
Boolean("") === false
Boolean("1") === true String(0) === '0'
Boolean("0") === true
Boolean({}) === true String(0) will convert the number (0) into a string ('0').
Boolean([]) === true

A shorter, but less clear, form:


Empty strings and the number 0 will be converted to false, and all others will be converted to true.
'' + 0 === '0'
A shorter, but less clear, form:

!!"true" === true Section 59.6: Primitive to Primitive conversion table


!!"false" === true
!!-1 === true Value Converted To String Converted To Number Converted To Boolean
!!1 === true undefinded "undefined" NaN false
!!0 === false 0
null "null" false
!!"" === false
!!"1" === true true "true" 1
!!"0" === true false "false" 0
!!{} === true
NaN "NaN" false
!![] === true
"" empty string 0 false
This shorter form takes advantage of implicit type conversion using the logical NOT operator twice, as described in "" 0 true
[Link] "2.4" (numeric) 2.4 true
"test" (non numeric NaN true
Here is the complete list of boolean conversions from the ECMAScript specification
"0" 0 true
if myArg of type undefined or null then Boolean(myArg) === false "1" 1 true
if myArg of type boolean then Boolean(myArg) === myArg -0 "0" false
if myArg of type number then Boolean(myArg) === false if myArg is +0, ‑0, or NaN; otherwise true 0 "0" false
if myArg of type string then Boolean(myArg) === false if myArg is the empty String (its length is zero); 1 "1" true
otherwise true Infinity "Infinity" true
if myArg of type symbol or object then Boolean(myArg) === true
-Infinity "-Infinity" true

Values that get converted to false as booleans are called falsy (and all others are called truthy). See Comparison [] "" 0 true
Operations. [3] "3" 3 true
['a'] "a" NaN true
Section 59.4: Converting a string to a number ['a','b'] "a,b" NaN true
{} "[object Object]" NaN true
Number('0') === 0
function(){} "function(){}" NaN true

Number('0') will convert the string ('0') into a number (0) Bold values highlight conversion that programmers may find surprising

A shorter, but less clear, form: To convert explicitly values you can use String() Number() Boolean()

+'0' === 0
Section 59.7: Convert an array to a string
The unary + operator does nothing to numbers, but converts anything else to a number.
[Link](separator) can be used to output an array as a string, with a configurable separator.
Interestingly, +(-12) === -12.
Default (separator = ","):
parseInt('0', 10) === 0
["a", "b", "c"].join() === "a,b,c"

[Link] – JavaScript® Notes for Professionals 327 [Link] – JavaScript® Notes for Professionals 328
With a string separator: all that must be done to convert it.

[1, 2, 3, 4].join(" + ") === "1 + 2 + 3 + 4" Section 59.12: Float to Integer
With a blank separator: To convert a float to an integer, JavaScript provides multiple methods.

["B", "o", "b"].join("") === "Bob" The floor function returns the first integer less than or equal to the float.

Section 59.8: Array to String using array methods [Link](5.7); // 5

This way may seem to be useless because you are using anonymous function to accomplish something that you The ceil function returns the first integer greater than or equal to the float.
can do it with join(); But if you need to make something to the strings while you are converting the Array to String,
[Link](5.3); // 6
this can be useful.

The round function rounds the float.


var arr = ['a', 'á', 'b', 'c']

function upper_lower (a, b, i) { [Link](3.2); // 3


//...do something here [Link](3.6); // 4
b = i & 1 ? [Link]() : [Link](); Version ≥ 6
return a + ',' + b
} Truncation (trunc) removes the decimals from the float.
arr = [Link](upper_lower); // "a,Á,b,C"
[Link](3.7); // 3

Section 59.9: Converting a number to a boolean Notice the difference between truncation (trunc) and floor:

Boolean(0) === false


[Link](-3.1); // -4
[Link](-3.1); // -3
Boolean(0) will convert the number 0 into a boolean false.

A shorter, but less clear, form: Section 59.13: Convert string to float
!!0 === false parseFloat accepts a string as an argument which it converts to a float/

Section 59.10: Converting a string to a boolean


parseFloat("10.01") // = 10.01

To convert a string to boolean use

Boolean(myString)

or the shorter but less clear form

!!myString

All strings except the empty string (of length zero) are evaluated to true as booleans.

Boolean('') === false // is true


Boolean("") === false // is true
Boolean('0') === false // is false
Boolean('any_nonempty_string') === true // is true

Section 59.11: Integer to Float


In JavaScript, all numbers are internally represented as floats. This means that simply using your integer as a float is

[Link] – JavaScript® Notes for Professionals 329 [Link] – JavaScript® Notes for Professionals 330
Chapter 60: Destructuring assignment // Is equivalent to
let p = [Link]('phone') ? [Link] : '123-456-789'; // '123-456-789'

Destructuring is a pattern matching technique that is added to JavaScript recently in ECMAScript 6. Section 60.2: Destructuring function arguments
It allows you to bind a group of variables to a corresponding set of values when their pattern matches to the right Pull properties from an object passed into a function. This pattern simulates named parameters instead of relying
hand-side and the left hand-side of the expression. on argument position.

Section 60.1: Destructuring Objects let user = {


name: 'Jill',
Destructuring is a convenient way to extract properties from objects into variables. age: 33,
profession: 'Pilot'
Basic syntax: }

function greeting ({name, profession}) {


let person = {
[Link](`Hello, ${name} the ${profession}`)
name: 'Bob',
}
age: 25
};
greeting(user)

let { name, age } = person;


This also works for arrays:
// Is equivalent to
let name = [Link]; // 'Bob' let parts = ["Hello", "World!"];
let age = [Link]; // 25
function greeting([first, second]) {
Destructuring and renaming: [Link](`${first} ${second}`);
}

let person = {
name: 'Bob',
age: 25
Section 60.3: Nested Destructuring
};
We are not limited to destructuring an object/array, we can destructure a nested object/array.
let { name: firstName } = person;
Nested Object Destructuring
// Is equivalent to
let firstName = [Link]; // 'Bob' var obj = {
a: {
c: 1,
Destructuring with default values:
d: 3
},
let person = { b: 2
name: 'Bob', };
age: 25
}; var {
a: {
let { phone = '123-456-789' } = person; c: x,
d: y
// Is equivalent to },
let phone = [Link]('phone') ? [Link] : '123-456-789'; // '123-456-789' b: z
} = obj;
Destructuring and renaming with default values
[Link](x, y, z); // 1,3,2
let person = {
name: 'Bob', Nested Array Destructuring
age: 25
}; var arr = [1, 2, [3, 4], 5];

let { phone: p = '123-456-789' } = person; var [a, , [b, c], d] = arr;

[Link] – JavaScript® Notes for Professionals 331 [Link] – JavaScript® Notes for Professionals 332
[Link](a, b, c, d); // 1 3 4 5 let { name, age, location } = person;

[Link]('I am ' + name + ', aged ' + age + ' and living in ' + location + '.');
Destructuring is not just limited to a single pattern, we can have arrays in it, with n-levels of nesting. Similarly we
// -> "I am John Doe aged 45 and living in Paris, France."
can destructure arrays with objects and vice-versa.

Arrays Within Object As you can see, three new variables were created: name, age and location and their values were grabbed from the
object person if they matched key names.
var obj = {
a: 1, Section 60.6: Default Value While Destructuring
b: [2, 3]
}; We often encounter a situation where a property we're trying to extract doesn't exist in the object/array, resulting
in a TypeError (while destructuring nested objects) or being set to undefined. While destructuring we can set a
var {
a: x1, default value, which it will fallback to, in case of it not being found in the object.
b: [x2, x3]
} = obj; var obj = {a : 1};
var {a : x , b : x1 = 10} = obj;
[Link](x1, x2, x3); // 1 2 3 [Link](x, x1); // 1, 10

var arr = [];


Objects Within Arrays
var [a = 5, b = 10, c] = arr;
[Link](a, b, c); // 5, 10, undefined
var arr = [1, 2 , {a : 3}, 4];

var [x1, x2 , {a : x3}, x4] = arr; Section 60.7: Renaming Variables While Destructuring
[Link](x1, x2, x3, x4); Destructuring allows us to refer to one key in an object, but declare it as a variable with a different name. The
syntax looks like the key-value syntax for a normal JavaScript object.
Section 60.4: Destructuring Arrays
let user = {
const myArr = ['one', 'two', 'three'] name: 'John Smith',
const [ a, b, c ] = myArr id: 10,
email: 'johns@[Link]',
// a = 'one', b = 'two, c = 'three' };

let {user: userName, id: userId} = user;


We can set default value in destructuring array, see the example of Default Value While Destructuring.
[Link](userName) // John Smith
With destructuring array, we can swap the values of 2 variables easily: [Link](userId) // 10

var a = 1;
var b = 3;

[a, b] = [b, a];


// a = 3, b = 1

We can specify empty slots to skip unneeded values:

[a, , b] = [1, 2, 3] // a = 1, b = 3

Section 60.5: Destructuring inside variables


Aside from destructuring objects into function arguments, you can use them inside variable declarations as follows:

const person = {
name: 'John Doe',
age: 45,
location: 'Paris, France',
};

[Link] – JavaScript® Notes for Professionals 333 [Link] – JavaScript® Notes for Professionals 334
Chapter 61: WebSockets };
[Link]('Uint8:', view.getUint8(4), 'Float32:', view.getFloat32(0))

[Link] = function() {
Parameter Details
[Link](buffer);
url The server url supporting this web socket connection.
};
data The content to send to the host.
message The message received from the host.
Section 61.4: Making a secure web socket connection
WebSocket is protocol, which enables two-way communication between a client and server:
var sck = "[Link]
var wss = new WebSocket(sck);
The goal WebSocket is to provide a mechanism for browser-based applications that need two-way communication
with servers that does not rely on opening multiple HTTP connections. (RFC 6455)
This uses the wss instead of ws to make a secure web socket connection which make use of HTTPS instead of HTTP
WebSocket works over HTTP protocol.

Section 61.1: Working with string messages


var wsHost = "[Link]
var ws = new WebSocket(wsHost);
var value = "an example message";

//onmessage : Event Listener - Triggered when we receive message form server


[Link] = function(message) {
if (message === value) {
[Link]("The echo host sent the correct message.");
} else {
[Link]("Expected: " + value);
[Link]("Received: " + message);
}
};

//onopen : Event Listener - event is triggered when websockets readyState changes to open which means
now we are ready to send and receives messages from server
[Link] = function() {
//send is used to send the message to server
[Link](value);
};

Section 61.2: Establish a web socket connection


var wsHost = "[Link]
var ws = new WebSocket(wsHost);

Section 61.3: Working with binary messages


var wsHost = "[Link]
var ws = new WebSocket(wsHost);
var buffer = new ArrayBuffer(5); // 5 byte buffer
var bufferView = new DataView(buffer);

bufferView.setFloat32(0, [Link]);
bufferView.setUint8(4, 127);

[Link] = 'arraybuffer';

[Link] = function(message) {
var view = new DataView([Link]);

[Link] – JavaScript® Notes for Professionals 335 [Link] – JavaScript® Notes for Professionals 336
Chapter 62: Arrow Functions after 1 second.

class Cow {
Arrow functions are a concise way of writing anonymous, lexically scoped functions in ECMAScript 2015 (ES6).
constructor() {

Section 62.1: Introduction }


[Link] = "moo";

In JavaScript, functions may be anonymously defined using the "arrow" (=>) syntax, which is sometimes referred to makeSoundLater() {
as a lambda expression due to Common Lisp similarities. setTimeout(() => [Link]([Link]), 1000);
}
The simplest form of an arrow function has its arguments on the left side of => and the return value on the right }
side:
const betsy = new Cow();

item => item + 1 // -> function(item){return item + 1}


[Link]();

This function can be immediately invoked by providing an argument to the expression: In the makeSoundLater() method, the this context refers to the current instance of the Cow object, so in the case
where I call [Link](), the this context refers to betsy.
(item => item + 1)(41) // -> 42

By using the arrow function, I preserve the this context so that I can make reference to [Link] when it comes
If an arrow function takes a single parameter, the parentheses around that parameter are optional. For example, time to print it out, which will properly print out "moo".
the following expressions assign the same type of function into constant variables:
If you had used a regular function in place of the arrow function, you would lose the context of being within the
const foo = bar => bar + 1; class, and not be able to directly access the sound property.
const bar = (baz) => baz + 1;

However, if the arrow function takes no parameters, or more than one parameter, a new set of parentheses must
Section 62.3: Arguments Object
encase all the arguments: Arrow functions do not expose an arguments object; therefore, arguments would simply refer to a variable in the
current scope.
(() => "foo")() // -> "foo"

const arguments = [true];


((bow, arrow) => bow + arrow)('I took an arrow ', 'to the knee...')
const foo = x => [Link](arguments[0]);
// -> "I took an arrow to the knee..."

foo(false); // -> true


If the function body doesn't consist of a single expression, it must be surrounded by brackets and use an explicit
return statement for providing a result: Due to this, arrow functions are also not aware of their caller/callee.

(bar => { While the lack of an arguments object can be a limitation in some edge cases, rest parameters are generally a
const baz = 41;
suitable alternative.
return bar + baz;
})(1); // -> 42
const arguments = [true];
const foo = (...arguments) => [Link](arguments[0]);
If the arrow function's body consists only of an object literal, this object literal has to be enclosed in parentheses:
foo(false); // -> false
(bar => ({ baz: 1 }))(); // -> Object {baz: 1}

The extra parentheses indicate that the opening and closing brackets are part of the object literal, i.e. they are not
Section 62.4: Implicit Return
delimiters of the function body.
Arrow functions may implicitly return values by simply omitting the curly braces that traditionally wrap a function's
body if their body only contains a single expression.
Section 62.2: Lexical Scoping & Binding (Value of "this")
const foo = x => x + 1;
Arrow functions are lexically scoped; this means that their this Binding is bound to the context of the surrounding foo(1); // -> 2
scope. That is to say, whatever this refers to can be preserved by using an arrow function.
When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not
Take a look at the following example. The class Cow has a method that allows for it to print out the sound it makes
mistaken for the opening of the function's body.

[Link] – JavaScript® Notes for Professionals 337 [Link] – JavaScript® Notes for Professionals 338
const foo = () => { bar: 1 } // foo() returns undefined
const foo = () => ({ bar: 1 }) // foo() returns {bar: 1} Chapter 63: Workers
Section 62.5: Arrow functions as a constructor Section 63.1: Web Worker
Arrow functions will throw a TypeError when used with the new keyword. A web worker is a simple way to run scripts in background threads as the worker thread can perform tasks
(including I/O tasks using XMLHttpRequest) without interfering with the user interface. Once created, a worker can
const foo = function () { send messages which can be different data types (except functions) to the JavaScript code that created it by posting
return 'foo'; messages to an event handler specified by that code (and vice versa.)
}
Workers can be created in a few ways.
const a = new foo();
The most common is from a simple URL:
const bar = () => {
return 'bar';
var webworker = new Worker("./path/to/[Link]");
}

const b = new bar(); // -> Uncaught TypeError: bar is not a constructor... It's also possible to create a Worker dynamically from a string using [Link]():

Section 62.6: Explicit Return var workerData = "function someFunction() {}; [Link]('More code');";

var blobURL = [Link](new Blob(["(" + workerData + ")"], { type: "text/javascript" }));


Arrow functions can behave very similar to classic functions in that you may explicitly return a value from them
using the return keyword; simply wrap your function's body in curly braces, and return a value: var webworker = new Worker(blobURL);

const foo = x => { The same method can be combined with [Link]() to create a worker from an existing function:
return x + 1;
} var workerFn = function() {
[Link]("I was run");
foo(1); // -> 2 };

var blobURL = [Link](new Blob(["(" + [Link]() + ")"], { type:


"text/javascript" }));

var webworker = new Worker(blobURL);

Section 63.2: A simple service worker


[Link]

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a
JavaScript file that can control the web page/site it is associated with, intercepting and modifying
navigation and resource requests, and caching resources in a very granular fashion to give you complete
control over how your app behaves in certain situations (the most obvious one being when the network is
not available.)

Source: MDN

Few Things:

1. It's a JavaScript Worker, so it can't access the DOM directly


2. It's a programmable network proxy
3. It will be terminated when not in use and restarted when it's next needed
4. A service worker has a lifecycle which is completely separate from your web page
5. HTTPS is Needed

[Link] – JavaScript® Notes for Professionals 339 [Link] – JavaScript® Notes for Professionals 340
This code that will be executed in the Document context, (or) this JavaScript will be included in your page via a var webworker = new Worker("./path/to/[Link]");
<script> tag.
// Send information to worker
[Link]("Sample message");
// we check if the browser supports ServiceWorkers
if ('serviceWorker' in navigator) { // Listen for messages from the worker
navigator [Link]("message", function(event) {
.serviceWorker // `[Link]` contains the value or object sent from the worker
.register( [Link]("Message from worker:", [Link]); // ["foo", "bar", "baz"]
// path to the service worker file });
'[Link]'
)
// the registration is async and it returns a promise From the worker, in [Link]:
.then(function (reg) {
[Link]('Registration Successful'); // Send information to the main thread (parent window)
}); [Link](["foo", "bar", "baz"]);
}
// Listen for messages from the main thread
[Link]
[Link]("message", function(event) {
// `[Link]` contains the value or object sent from main
This is the service worker code and is executed in the ServiceWorker Global Scope. [Link]("Message from parent:", [Link]); // "Sample message"
});
[Link]('fetch', function (event) {
// do nothing here, just log all the network requests
Alternatively, you can also add event listeners using onmessage:
[Link]([Link]);
});
From the main thread (parent window):

Section 63.3: Register a service worker [Link] = function(event) {


[Link]("Message from worker:", [Link]); // ["foo", "bar", "baz"]
// Check if service worker is available. }
if ('serviceWorker' in navigator) {
[Link]('/[Link]').then(function(registration) { From the worker, in [Link]:
[Link]('SW registration succeeded with scope:', [Link]);
}).catch(function(e) {
[Link] = function(event) {
[Link]('SW registration failed with error:', e);
[Link]("Message from parent:", [Link]); // "Sample message"
});
}
}

You can call register() on every page load. If the SW is already registered, the browser provides you with Section 63.5: Terminate a worker
instance that is already running
The SW file can be any name. [Link] is common. Once you are done with a worker you should terminate it. This helps to free up resources for other applications on
The location of the SW file is important because it defines the SW's scope. For example, an SW file at the user’s computer.
/js/[Link] can only intercept fetch requests for files that begin with /js/. For this reason you usually see the
Main Thread:
SW file at the top-level directory of the project.

// Terminate a worker from your application.


Section 63.4: Communicating with a Web Worker [Link]();

Since workers run in a separate thread from the one that created them, communication needs to happen via
Note: The terminate method is not available for service workers. It will be terminated when not in use, and
postMessage.
restarted when it's next needed.

Note: Because of the different export prefixes, some browsers have webkitPostMessage instead of postMessage. Worker Thread:
You should override postMessage to make sure workers "work" (no pun intended) in the most places possible:
// Have a worker terminate itself.
[Link] = ([Link] || [Link]); [Link]();

From the main thread (parent window):

// Create a worker

[Link] – JavaScript® Notes for Professionals 341 [Link] – JavaScript® Notes for Professionals 342
Section 63.6: Populating your cache an explicit port has to be opened so multiple scripts can use it to communicate with the shared worker. (Note that
dedicated workers do this implicitly)
After your service worker is registered, the browser will try to install & later activate the service worker.
Main application
Install event listener
var myWorker = new SharedWorker('[Link]');
[Link]('install', function(event) { [Link](); // open the port connection
[Link]('installed');
}); [Link]([2,3]);

Caching [Link]

One can use this install event returned to cache the assets needed to run the app offline. Below example uses the [Link](); open the port connection to enable two-way communication
cache api to do the same.
[Link] = function(e) {
var port = [Link][0]; // get the port
[Link]('install', function(event) {
[Link](
[Link] = function(e) {
[Link]('v1').then(function(cache) {
[Link]('Worker received arguments:', [Link]);
return [Link]([
[Link]([Link][0] + [Link][1]);
/* Array of all the assets that needs to be cached */
}
'/css/[Link]',
}
'/js/[Link]',
'/images/[Link]'
]); Note that setting up this message handler in the worker thread also implicitly opens the port connection back to
}) the parent thread, so the call to [Link]() is not actually needed, as noted above.
);
});

Section 63.7: Dedicated Workers and Shared Workers


Dedicated Workers

A dedicated web worker is only accessible by the script that called it.

Main application:

var worker = new Worker('[Link]');


[Link]('message', function(msg) {
[Link]('Result from the worker:', [Link]);
});
[Link]([2,3]);

[Link]:

[Link]('message', function(msg) {
[Link]('Worker received arguments:', [Link]);
[Link]([Link][0] + [Link][1]);
});

Shared Workers

A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or
even workers.

Creating a shared worker is very similar to how to create a dedicated one, but instead of the straight-forward
communication between the main thread and the worker thread, you'll have to communicate via a port object, i.e.,

[Link] – JavaScript® Notes for Professionals 343 [Link] – JavaScript® Notes for Professionals 344
Chapter 64: requestAnimationFrame // start the animation
[Link](eachFrame);
</script>
Parameter Details
</body>
"A parameter specifying a function to call when it's time to update your animation for the next
callback </html>
repaint." ([Link]

Section 64.1: Use requestAnimationFrame to fade in element Section 64.2: Keeping Compatibility
Of course, just like most things in browser JavaScript, you just can't count on the fact that everything will be the
View jsFiddle: [Link]
same everywhere. In this case, requestAnimationFrame might have a prefix on some platforms and are named
Copy + Pasteable code below:
differently, such as webkitRequestAnimationFrame. Fortunately, there's a really easy way to group all the known
<html> differences that could exist down to 1 function:
<body>
<h1>This will fade in at 60 frames per second (or as close to possible as your hardware [Link] = (function(){
allows)</h1> return [Link] ||
[Link] ||
<script> [Link] ||
// Fade in over 2000 ms = 2 seconds. function(callback){
var FADE_DURATION = 2.0 * 1000; [Link](callback, 1000 / 60);
};
// -1 is simply a flag to indicate if we are rendering the very 1st frame })();
var startTime=-1.0;

Note that the last option (which fills in when no existing support was found) will not return an id to be used in
// Function to render current frame (whatever frame that may be)
function render(currTime) { cancelAnimationFrame. There is, however an efficient polyfill that was written which fixes this.
var head1 = [Link]('h1')[0];

// How opaque should head1 be? Its fade started at currTime=0.


Section 64.3: Cancelling an Animation
// Over FADE_DURATION ms, opacity goes from 0 to 1
To cancel a call to requestAnimationFrame, you need the id it returned from when it was last called. This is the
var opacity = (currTime/FADE_DURATION);
[Link] = opacity; parameter you use for cancelAnimationFrame. The following example starts some hypothetical animation then
} pauses it after one second.

// Function to // stores the id returned from each call to requestAnimationFrame


function eachFrame() { var requestId;
// Time that animation has been running (in ms)
// Uncomment the [Link] function to view how quickly // draw something
// the timeRunning updates its value (may affect performance) function draw(timestamp) {
var timeRunning = (new Date()).getTime() - startTime; // do some animation
//[Link]('var timeRunning = '+timeRunning+'ms'); // request next frame
if (startTime < 0) { start();
// This branch: executes for the first frame only. }
// it sets the startTime, then renders at currTime = 0.0
startTime = (new Date()).getTime(); // pauses the animation
render(0.0); function pause() {
} else if (timeRunning < FADE_DURATION) { // pass in the id returned from the last call to requestAnimationFrame
// This branch: renders every frame, other than the 1st frame, cancelAnimationFrame(requestId);
// with the new timeRunning value. }
render(timeRunning);
} else { // begin the animation
return; function start() {
} // store the id returned from requestAnimationFrame
requestId = requestAnimationFrame(draw);
// Now we are done rendering one frame. }
// So we make a request to the browser to execute the next
// animation frame, and the browser optimizes the rest. // begin now
// This happens very rapidly, as you can see in the [Link](); start();
[Link](eachFrame);
}; // after a second, pause the animation

[Link] – JavaScript® Notes for Professionals 345 [Link] – JavaScript® Notes for Professionals 346
setTimeout(pause,1000);
Chapter 65: Creational Design Patterns
Design patterns are a good way to keep your code readable and DRY. DRY stands for don't repeat yourself.
Below you could find more examples about the most important design patterns.

Section 65.1: Factory Functions


A factory function is simply a function that returns an object.

Factory functions do not require the use of the new keyword, but can still be used to initialize an object, like a
constructor.

Often, factory functions are used as API wrappers, like in the cases of jQuery and [Link], so users do not need
to use new.

The following is the simplest form of factory function; taking arguments and using them to craft a new object with
the object literal:

function cowFactory(name) {
return {
name: name,
talk: function () {
[Link]('Moo, my name is ' + [Link]);
},
};
}

var daisy = cowFactory('Daisy'); // create a cow named Daisy


[Link](); // "Moo, my name is Daisy"

It is easy to define private properties and methods in a factory, by including them outside of the returned object.
This keeps your implementation details encapsulated, so you can only expose the public interface to your object.

function cowFactory(name) {
function formalName() {
return name + ' the cow';
}

return {
talk: function () {
[Link]('Moo, my name is ' + formalName());
},
};
}

var daisy = cowFactory('Daisy');


[Link](); // "Moo, my name is Daisy the cow"
[Link](); // ERROR: [Link] is not a function

The last line will give an error because the function formalName is closed inside the cowFactory function. This is a
closure.

Factories are also a great way of applying functional programming practices in JavaScript, because they are
functions.

[Link] – JavaScript® Notes for Professionals 347 [Link] – JavaScript® Notes for Professionals 348
Section 65.2: Factory with Composition [Link]();
[Link]();
// outputs: Fred says Hello
// outputs: Fred is moving slowly

'Prefer composition over inheritance' is an important and popular programming principle, used to assign behaviors to
var snowy = rabbit('Snowy', 'white');
objects, as opposed to inheriting many often unneeded behaviors. [Link](); // outputs: Snowy is moving slowly
[Link](); // outputs: Snowy is moving quickly
Behaviour factories [Link](); // ERROR: [Link] is not a function

var speaker = function (state) {


var noise = [Link] || 'grunt';
Section 65.3: Module and Revealing Module Patterns
return { Module Pattern
speak: function () {
[Link]([Link] + ' says ' + noise); The Module pattern is a creational and structural design pattern which provides a way of encapsulating private
} members while producing a public API. This is accomplished by creating an IIFE which allows us to define variables
}; only available in its scope (through closure) while returning an object which contains the public API.
};

This gives us a clean solution for hiding the main logic and only exposing an interface we wish other parts of our
var mover = function (state) {
return { application to use.
moveSlowly: function () {
[Link]([Link] + ' is moving slowly'); var Module = (function(/* pass initialization data if necessary */) {
}, // Private data is stored within the closure
moveQuickly: function () { var privateData = 1;
[Link]([Link] + ' is moving quickly');
} // Because the function is immediately invoked,
}; // the return value becomes the public API
}; var api = {
getPrivateData: function() {
return privateData;
Object factories
},
Version ≥ 6
getDoublePrivateData: function() {
var person = function (name, age) {
return [Link]() * 2;
var state = {
}
name: name,
};
age: age,
return api;
noise: 'Hello'
})(/* pass initialization data if necessary */);
};
Revealing Module Pattern
return [Link]( // Merge our 'behaviour' objects
{}, The Revealing Module pattern is a variant in the Module pattern. The key differences are that all members (private
speaker(state), and public) are defined within the closure, the return value is an object literal containing no function definitions,
mover(state)
and all references to member data are done through direct references rather than through the returned object.
);
};
var Module = (function(/* pass initialization data if necessary */) {
var rabbit = function (name, colour) { // Private data is stored just like before
var state = { var privateData = 1;
name: name,
colour: colour // All functions must be declared outside of the returned object
}; var getPrivateData = function() {
return privateData;
return [Link]( };
{},
mover(state) var getDoublePrivateData = function() {
); // Refer directly to enclosed members rather than through the returned object
}; return getPrivateData() * 2;
};

Usage // Return an object literal with no function definitions


return {
var fred = person('Fred', 42); getPrivateData: getPrivateData,

[Link] – JavaScript® Notes for Professionals 349 [Link] – JavaScript® Notes for Professionals 350
};
getDoublePrivateData: getDoublePrivateData
Section 65.4: Prototype Pattern
})(/* pass initialization data if necessary */);
The prototype pattern focuses on creating an object that can be used as a blueprint for other objects through
Revealing Prototype Pattern prototypal inheritance. This pattern is inherently easy to work with in JavaScript because of the native support for
prototypal inheritance in JS which means we don't need to spend time or effort imitating this topology.
This variation of the revealing pattern is used to separate the constructor to the methods. This pattern allow us to
use the javascript language like a objected oriented language: Creating methods on the prototype

//Namespace setting function Welcome(name) {


var NavigationNs = NavigationNs || {}; [Link] = name;
}
// This is used as a class constructor [Link] = function() {
[Link] = function(current, length) { return 'Hello, ' + [Link] + '!';
[Link] = current; }
[Link] = length;
} var welcome = new Welcome('John');

// The prototype is used to separate the construct and the methods [Link]();
[Link] = function() { // => Hello, John!
// It is an example of a public method because is revealed in the return statement
var setCurrent = function() {
//Here the variables current and length are used as private class properties Prototypal Inheritance
for (var i = 0; i < [Link]; i++) {
$([Link]).addClass('active'); Inheriting from a 'parent object' is relatively easy via the following pattern
}
} [Link] = [Link]([Link]);
return { setCurrent: setCurrent }; [Link] = ChildObject;
}();

Where ParentObject is the object you wish to inherit the prototyped functions from, and ChildObject is the new
// Example of parameterless constructor
[Link] = function() {} Object you wish to put them on.

[Link] = function() { If the parent object has values it initializes in its constructor you need to call the parents constructor when
// It is a example of an private method because is not revealed in the return statement initializing the child.
var reload = function(data) {
// do something You do that using the following pattern in the ChildObject constructor.
},
// It the only public method, because it the only function referenced in the return statement
function ChildObject(value) {
getPage = function(link) {
[Link](this, value);
var a = $(link);
}

var options = {url: [Link]('href'), type: 'get'}


$.ajax(options).done(function(data) { A complete example where the above is implemented
// after the ajax call is done, it calls private method
reload(data); function RoomService(name, order) {
}); // [Link] will be set and made available on the scope of this function
[Link](this, name);
return false; [Link] = order;
} }
return {getPage : getPage}
}(); // Inherit 'sayHello()' methods from 'Welcome' prototype
[Link] = [Link]([Link]);
This code above should be in a separated file .js to be referenced in any page that is needed. It can be used like this:
// By default prototype object has 'constructor' property.
// But as we created new object without this property - we have to set it manually,
var menuActive = new [Link]('[Link]-menu li', 5);
// otherwise 'constructor' property will point to 'Welcome' class
[Link]();
[Link] = RoomService;

[Link] = function() {
return 'Your ' + [Link] + ' has arrived!';
}

[Link] – JavaScript® Notes for Professionals 351 [Link] – JavaScript® Notes for Professionals 352
[Link] = function() {
return [Link]() + ' ' + [Link]();
Section 65.6: Abstract Factory Pattern
}
The Abstract Factory Pattern is a creational design pattern that can be used to define specific instances or classes
var delivery = new RoomService('John', 'pizza'); without having to specify the exact object that is being created.

[Link](); function Car() { [Link] = "Car"; [Link] = 4; }


// => Hello, John!, function Truck() { [Link] = "Truck"; [Link] = 6; }
function Bike() { [Link] = "Bike"; [Link] = 2; }
[Link]();
// Your pizza has arrived! const vehicleFactory = {
createVehicle: function (type) {
[Link](); switch ([Link]()) {
// => Hello, John! Your pizza has arrived! case "car":
return new Car();
case "truck":
Section 65.5: Singleton Pattern return new Truck();
case "bike":
The Singleton pattern is a design pattern that restricts the instantiation of a class to one object. After the first object return new Bike();
is created, it will return the reference to the same one whenever called for an object. default:
return null;
}
var Singleton = (function () {
}
// instance stores a reference to the Singleton
};
var instance;

const car = [Link]("Car"); // Car { name: "Car", wheels: 4 }


function createInstance() {
const truck = [Link]("Truck"); // Truck { name: "Truck", wheels: 6 }
// private variables and methods
const bike = [Link]("Bike"); // Bike { name: "Bike", wheels: 2 }
var _privateVariable = 'I am a private variable';
const unknown = [Link]("Boat"); // null ( Vehicle not known )
function _privateMethod() {
[Link]('I am a private method');
}

return {
// public methods and variables
publicMethod: function() {
[Link]('I am a public method');
},
publicVariable: 'I am a public variable'
};
}

return {
// Get the Singleton instance if it exists
// or create one if doesn't
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();

Usage:

// there is no existing instance of Singleton, so it will create one


var instance1 = [Link]();
// there is an instance of Singleton, so it will return the reference to this one
var instance2 = [Link]();
[Link](instance1 === instance2); // true

[Link] – JavaScript® Notes for Professionals 353 [Link] – JavaScript® Notes for Professionals 354
Chapter 66: Detecting browser [Link]= (function(){
var ua= [Link], tem,
M= [Link](/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
Browsers, as they have evolved, offered more features to JavaScript. But often these features are not available in all if(/trident/[Link](M[1])){
tem= /\brv[ :]+(\d+)/[Link](ua) || [];
browsers. Sometimes they may be available in one browser, but yet to be released on other browsers. Other times,
return 'IE '+(tem[1] || '');
these features are implemented differently by different browsers. Browser detection becomes important to ensure }
that the application you develop runs smoothly across different browsers and devices. if(M[1]=== 'Chrome'){
tem= [Link](/\b(OPR|Edge)\/(\d+)/);
Section 66.1: Feature Detection Method }
if(tem!= null) return [Link](1).join(' ').replace('OPR', 'Opera');

M= M[2]? [M[1], M[2]]: [[Link], [Link], '-?'];


This method looks for the existence of browser specific things. This would be more difficult to spoof, but is not
if((tem= [Link](/version\/(\d+)/i))!= null) [Link](1, 1, tem[1]);
guaranteed to be future proof. return [Link](' ');
})();
// Opera 8.0+
var isOpera = (!![Link] && !![Link]) || !![Link] || [Link](' Credit to kennebec
OPR/') >= 0;

// Firefox 1.0+ Section 66.3: Library Method


var isFirefox = typeof InstallTrigger !== 'undefined';
An easier approach for some would be to use an existing JavaScript library. This is because it can be tricky to
// At least Safari 3+: "[object HTMLElementConstructor]" guarantee browser detection is correct, so it can make sense to use a working solution if one is available.
var isSafari = [Link]([Link]).indexOf('Constructor') > 0;
One popular browser-detection library is Bowser.
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !![Link];
Usage example:
// Edge 20+
var isEdge = !isIE && !![Link]; if ([Link] && [Link] >= 6) {
alert('IE version 6 or newer');
// Chrome 1+ }
var isChrome = !![Link] && !![Link]; else if ([Link]) {
alert('Firefox');
// Blink engine detection }
var isBlink = (isChrome || isOpera) && !![Link]; else if ([Link]) {
alert('Chrome');
}
Successfully tested in:
else if ([Link]) {
alert('Safari');
Firefox 0.8 - 44 }
Chrome 1.0 - 48 else if ([Link] || [Link]) {
Opera 8.0 - 34 alert('iPhone or Android');
}
Safari 3.0 - 9.0.3
IE 6 - 11
Edge - 20-25

Credit to Rob W

Section 66.2: User Agent Detection


This method gets the user agent and parses it to find the browser. The browser name and version are extracted
from the user agent through a regex. Based on these two, the <browser name> <version> is returned.

The four conditional blocks following the user agent matching code are meant to account for differences in the user
agents of different browsers. For example, in case of opera, since it uses Chrome rendering engine, there is an
additional step of ignoring that part.

Note that this method can be easily spoofed by a user.

[Link] – JavaScript® Notes for Professionals 355 [Link] – JavaScript® Notes for Professionals 356
Chapter 67: Symbols of the symbol that can be used in a debug message) using the toString method or the String constructor.

const APPLE = Symbol('Apple');


Section 67.1: Basics of symbol primitive type let str1 = [Link](); // "Symbol(Apple)"
let str2 = String(APPLE); // "Symbol(Apple)"

Symbol is a new primitive type in ES6. Symbols are used mainly as property keys, and one of its main
characteristics is that they are unique, even if they have the same description. This means they will never have a
name clash with any other property key that is a symbol or string.

const MY_PROP_KEY = Symbol();


const obj = {};

obj[MY_PROP_KEY] = "ABC";
[Link](obj[MY_PROP_KEY]);

In this example, the result of [Link] would be ABC.

You can also have named Symbols like:

const APPLE = Symbol('Apple');


const BANANA = Symbol('Banana');
const GRAPE = Symbol('Grape');

Each of these values are unique and cannot be overridden.

Providing an optional parameter (description) when creating primitive symbols can be used for debugging but
not to access the symbol itself (but see the [Link]() example for a way to register/lookup global shared
symbols).

Section 67.2: Using [Link]() to create global, shared


symbols
The [Link] method allows you to register and look up global symbols by name. The first time it is called with a
given key, it creates a new symbol and adds it to the registry.

let a = [Link]('A');

The next time you call [Link]('A'), the same symbol will be returned instead of a new one (in contrast to
Symbol('A') which would create a new, unique symbol that happens to have the same description).

a === [Link]('A') // true

but

a === Symbol('A') // false

Section 67.3: Converting a symbol into a string


Unlike most other JavaScript objects, symbols are not automatically converted into a string when performing
concatenation.

let apple = Symbol('Apple') + ''; // throws TypeError!

Instead, they have to be explicitly converted into a string when necessary, (for example, to get a textual description

[Link] – JavaScript® Notes for Professionals 357 [Link] – JavaScript® Notes for Professionals 358
Chapter 68: Transpiling Section 68.2: Start using ES6/7 with Babel
Browser support for ES6 is growing, but to be sure your code will work on environments that don't fully support it,
Transpiling is the process of interpreting certain programming languages and translating it to a specific target you can use Babel, the ES6/7 to ES5 transpiler, try it out!
language. In this context, transpiling will take compile-to-JS languages and translate them into the target language
of JavaScript. If you would like to use ES6/7 in your projects without having to worry about compatibility, you can use Node and
Babel CLI
Section 68.1: Introduction to Transpiling
Examples Quick setup of a project with Babel for ES6/7 support

1. Download and install Node


ES6/ES2015 to ES5 (via Babel):
2. Go to a folder and create a project using your favourite command line tool
This ES2015 syntax
~ npm init

// ES2015 arrow function syntax


3. Install Babel CLI
[1,2,3].map(n => n + 1);

~ npm install --save-dev babel-cli


is interpreted and translated to this ES5 syntax: ~ npm install --save-dev babel-preset-es2015

// Conventional ES5 anonymous function syntax 4. Create a scripts folder to store your .js files, and then a dist/scripts folder where the transpiled fully
[1,2,3].map(function(n) { compatible files will be stored.
return n + 1;
5. Create a .babelrc file in the root folder of your project, and write this on it
});

{
CoffeeScript to JavaScript (via built-in CoffeeScript compiler): "presets": ["es2015"]
}
This CoffeeScript
6. Edit your [Link] file (created when you ran npm init) and add the build script to the scripts
# Existence: property:
alert "I knew it!" if elvis?
{
is interpreted and translated to JavaScript: ...
"scripts": {
... ,
if (typeof elvis !== "undefined" && elvis !== null) {
"build": "babel scripts --out-dir dist/scripts"
alert("I knew it!");
},
}
...
}
How do I transpile?
7. Enjoy programming in ES6/7
Most compile-to-JavaScript languages have a transpiler built-in (like in CoffeeScript or TypeScript). In this case, you 8. Run the following to transpile all your files to ES5
may just need to enable the language's transpiler via config settings or a checkbox. Advanced settings can also be
set in relation to the transpiler. ~ npm run build

For ES6/ES2016-to-ES5 transpiling, the most prominent transpiler being used is Babel. For more complex projects you might want to take a look at Gulp or Webpack

Why should I transpile?

The most cited benefits include:

The ability to use newer syntax reliably


Compatibility among most, if not all browsers
Usage of missing/not yet native features to JavaScript via languages like CoffeeScript or TypeScript

[Link] – JavaScript® Notes for Professionals 359 [Link] – JavaScript® Notes for Professionals 360
Chapter 69: Automatic Semicolon Insertion 1. When, as the program is parsed from left to right, a token (called the offending token) is
encountered that is not allowed by any production of the grammar, then a semicolon is
- ASI automatically inserted before the offending token if one or more of the following conditions is true:

The offending token is separated from the previous token by at least one LineTerminator.
Section 69.1: Avoid semicolon insertion on return statements The offending token is }.

The JavaScript coding convention is to place the starting bracket of blocks on the same line of their declaration: 2. When, as the program is parsed from left to right, the end of the input stream of tokens is
encountered and the parser is unable to parse the input token stream as a single complete
if (...) { ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
3. When, as the program is parsed from left to right, a token is encountered that is allowed by some
}
production of the grammar, but the production is a restricted production and the token would be
function (a, b, ...) { the first token for a terminal or nonterminal immediately following the annotation "[no
LineTerminator here]" within the restricted production (and therefore such a token is called a
} restricted token), and the restricted token is separated from the previous token by at least one
LineTerminator, then a semicolon is automatically inserted before the restricted token.
Instead of in the next line:
However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted
if (...) automatically if the semicolon would then be parsed as an empty statement or if that semicolon would
{ become one of the two semicolons in the header of a for statement (see 12.6.3).

}
Source: ECMA-262, Fifth Edition ECMAScript Specification:
function (a, b, ...)
{
Section 69.3: Statements aected by automatic semicolon
} insertion
This has been adopted to avoid semicolon insertion in return statements that return objects: empty statement
var statement
function foo() expression statement
{
do-while statement
return // A semicolon will be inserted here, making the function return nothing
continue statement
{
foo: 'foo' break statement
}; return statement
} throw statement

foo(); // undefined
Examples:
function properFoo() {
When the end of the input stream of tokens is encountered and the parser is unable to parse the input token
return {
foo: 'foo' stream as a single complete Program, then a semicolon is automatically inserted at the end of the input stream.
};
} a = b
++c
properFoo(); // { foo: 'foo' } // is transformed to:
a = b;
In most languages the placement of the starting bracket is just a matter of personal preference, as it has no real ++c;

impact on the execution of the code. In JavaScript, as you've seen, placing the initial bracket in the next line can lead x
to silent errors. ++
y

Section 69.2: Rules of Automatic Semicolon Insertion


// is transformed to:
x;
++y;

There are three basic rules of semicolon insertion:


Array indexing/literals

[Link] – JavaScript® Notes for Professionals 361 [Link] – JavaScript® Notes for Professionals 362
[Link]("Hello, World")
[1,2,3].join() Chapter 70: Localization
// is transformed to:
[Link]("Hello, World")[(1, 2, 3)].join(); Paramater Details
weekday "narrow", "short", "long"
Return statement: era "narrow", "short", "long"
year "numeric", "2-digit"
return
"something"; month "numeric", "2-digit", "narrow", "short", "long"
// is transformed to day "numeric", "2-digit"
return;
hour "numeric", "2-digit"
"something";
minute "numeric", "2-digit"
second "numeric", "2-digit"
timeZoneName "short", "long"

Section 70.1: Number formatting


Number formatting, grouping digits according to the localization.

const usNumberFormat = new [Link]('en-US');


const esNumberFormat = new [Link]('es-ES');

const usNumber = [Link](99999999.99); // "99,999,999.99"


const esNumber = [Link](99999999.99); // "99.999.999,99"

Section 70.2: Currency formatting


Currency formatting, grouping digits and placing the currency symbol according to the localization.

const usCurrencyFormat = new [Link]('en-US', {style: 'currency', currency: 'USD'})


const esCurrencyFormat = new [Link]('es-ES', {style: 'currency', currency: 'EUR'})

const usCurrency = [Link](100.10); // "$100.10"


const esCurrency = [Link](100.10); // "100.10 €"

Section 70.3: Date and time formatting


Date time formatting, according to the localization.

const usDateTimeFormatting = new [Link]('en-US');


const esDateTimeFormatting = new [Link]('es-ES');

const usDate = [Link](new Date('2016-07-21')); // "7/21/2016"


const esDate = [Link](new Date('2016-07-21')); // "21/7/2016"

[Link] – JavaScript® Notes for Professionals 363 [Link] – JavaScript® Notes for Professionals 364
Chapter 71: Geolocation }
default:
return "UNKNOWN_ERROR";

Section 71.1: Get updates when a user's location changes


};

It can be used in geolocationFailure() like so:


You can also receive regular updates of the user's location; for example, as they move around while using a mobile
device. Location tracking over time can be very sensitive, so be sure to explain to the user ahead of time why you're
var geolocationFailure = function(err) {
requesting this permission and how you'll use the data. [Link]("ERROR (" + getErrorCode(err) + "): " + [Link]);
};
if ([Link]) {
//after the user indicates that they want to turn on continuous location-tracking
var watchId = [Link](updateLocation, geolocationFailure);
} else {
[Link]("Geolocation is not supported by this browser.");
}

var updateLocation = function(position) {


[Link]("New position at: " + [Link] + ", " + [Link]);
};

To turn off continuous updates:

[Link](watchId);

Section 71.2: Get a user's latitude and longitude


if ([Link]) {
[Link](geolocationSuccess, geolocationFailure);
} else {
[Link]("Geolocation is not supported by this browser.");
}

// Function that will be called if the query succeeds


var geolocationSuccess = function(pos) {
[Link]("Your location is " + [Link] + "°, " + [Link] + "°.");
};

// Function that will be called if the query fails


var geolocationFailure = function(err) {
[Link]("ERROR (" + [Link] + "): " + [Link]);
};

Section 71.3: More descriptive error codes


In the event that geolocation fails, your callback function will receive a PositionError object. The object will include
an attribute named code that will have a value of 1, 2, or 3. Each of these numbers signifies a different kind of error;
the getErrorCode() function below takes the [Link] as its only argument and returns a string with
the name of the error that occurred.

var getErrorCode = function(err) {


switch ([Link]) {
case err.PERMISSION_DENIED:
return "PERMISSION_DENIED";
case err.POSITION_UNAVAILABLE:
return "POSITION_UNAVAILABLE";
case [Link]:
return "TIMEOUT";

[Link] – JavaScript® Notes for Professionals 365 [Link] – JavaScript® Notes for Professionals 366
Chapter 72: IndexedDB // Transactions use events, just like database open requests. Let's listen for success
[Link] = function() {
[Link]("All done!");

Section 72.1: Opening a database


};

// And make sure we handle errors


Opening a database is an asynchronous operation. We need to send a request to open our database and then [Link] = function() {
listen for events so we know when it's ready. [Link]("Something went wrong with our transaction: ", [Link]);
};
We'll open a DemoDB database. If it doesn't exist yet, it will get created when we send the request.
// Now that our event handlers are set up, let's get our things store and add some objects!
var store = [Link]("things");
The 2 below says that we're asking for version 2 of our database. Only one version exists at any time, but we can
use the version number to upgrade old data, as you'll see.
// Transactions can do a few things at a time. Let's start with a simple insertion
var db = null, // We'll use this once we have our database var request = [Link]({
request = [Link]("DemoDB", 2); // "things" uses auto-incrementing keys, so we don't need one, but we can set it anyway
key: "coffee_cup",
// Listen for success. This will be called after onupgradeneeded runs, if it does at all name: "Coffee Cup",
[Link] = function() { contents: ["coffee", "cream"]
db = [Link]; // We have a database! });

doThingsWithDB(db); // Let's listen so we can see if everything went well


}; [Link] = function(event) {
// Done! Here, `[Link]` will be the object's key, "coffee_cup"
// If our database didn't exist before, or it was an older version than what we requested, };
// the `onupgradeneeded` event will be fired.
//
// We can use this to setup a new database and upgrade an old one with new data stores // We can also add a bunch of things from an array. We'll use auto-generated keys
[Link] = function(event) { var thingsToAdd = [{ name: "Example object" }, { value: "I don't have a name" }];
db = [Link];
// Let's use more compact code this time and ignore the results of our insertions
// If the oldVersion is less than 1, then the database didn't exist. Let's set it up [Link](e => [Link](e));
if ([Link] < 1) {
// We'll create a new "things" store with `autoIncrement`ing keys
var store = [Link]("things", { autoIncrement: true }); Section 72.3: Retrieving data
}
Anything that needs to happen with data in an IndexedDB database happens in a transaction. There are a few
// In version 2 of our database, we added a new index by the name of each thing things to note about transactions that are mentioned in the Remarks section at the bottom of this page.
if ([Link] < 2) {
// Let's load the things store and create an index
We'll use the database we set up in Opening a database.
var store = [Link]("things");

[Link]("by_name", "name"); // Create a new transaction, we'll use the default "readonly" mode and the things store
} var transaction = [Link](["things"]);
};
// Transactions use events, just like database open requests. Let's listen for success
// Handle any errors [Link] = function() {
[Link] = function() { [Link]("All done!");
[Link]("Something went wrong when we tried to request the database!"); };
};
// And make sure we handle errors
[Link] = function() {
Section 72.2: Adding objects [Link]("Something went wrong with our transaction: ", [Link]);
};
Anything that needs to happen with data in an IndexedDB database happens in a transaction. There are a few
// Now that everything is set up, let's get our things store and load some objects!
things to note about transactions that are mentioned in the Remarks section at the bottom of this page.
var store = [Link]("things");

We'll use the database we set up in Opening a database.


// We'll load the coffee_cup object we added in Adding objects
// Create a new readwrite (since we want to change things) transaction for the things store var request = [Link]("coffee_cup");
var transaction = [Link](["things"], "readwrite");

[Link] – JavaScript® Notes for Professionals 367 [Link] – JavaScript® Notes for Professionals 368
// Let's listen so we can see if everything went well
[Link] = function(event) {
// All done, let's log our object to the console
Chapter 73: Modularization Techniques
Section 73.1: ES6 Modules
[Link]([Link]);
};

Version ≥ 6

// That was pretty long for a basic retrieval. If we just want to get just
// the one object and don't care about errors, we can shorten things a lot In ECMAScript 6, when using the module syntax (import/export), each file becomes its own module with a private
[Link]("things").objectStore("things") namespace. Top-level functions and variables do not pollute the global namespace. To expose functions, classes,
.get("coffee_cup"). => [Link]([Link]); and variables for other modules to import, you can use the export keyword.

Section 72.4: Testing for IndexedDB availability Note: Although this is the official method for creating JavaScript modules, it is not supported by any major
browsers right now. However, ES6 Modules are supported by many transpilers.
You can test for IndexedDB support in the current environment by checking for the presence of the
export function greet(name) {
[Link] property:
[Link]("Hello %s!", name);
}
if ([Link]) {
// IndexedDB is available var myMethod = function(param) {
} return "Here's what you said: " + param;
};

export {myMethod}

export class MyClass {


test() {}
}

Using Modules

Importing modules is as simple as specifying their path:

import greet from "[Link]";

greet("Bob");

This imports only the myMethod method from our [Link] file.

It's also possible to import all methods from a module:

import * as myModule from "[Link]";

[Link]("Alice");

You can also import methods under a new name:

import { greet as A, myMethod as B } from "[Link]";

More information on ES6 Modules can be found in the Modules topic.

Section 73.2: Universal Module Definition (UMD)


The UMD (Universal Module Definition) pattern is used when our module needs to be imported by a number of
different module loaders (e.g. AMD, CommonJS).

The pattern itself consists of two parts:

[Link] – JavaScript® Notes for Professionals 369 [Link] – JavaScript® Notes for Professionals 370
1. An IIFE (Immediately-Invoked Function Expression) that checks for the module loader that is being Passing the dependent modules as arguments to the factory function
implemented by the user. This will take two arguments; root (a this reference to the global scope) and
factory (the function where we declare our module). The key thing here is that a module can have a dependency and not hold everything up while waiting for it to load,
without the developer having to write complicated code.
2. An anonymous function that creates our module. This is passed as the second argument to the IIFE portion
of the pattern. This function is passed any number of arguments to specify the dependencies of the module. Here's an example of AMD:

// Define a module "myModule" with two dependencies, jQuery and Lodash


In the below example we check for AMD, then CommonJS. If neither of those loaders are in use we fall back to
define("myModule", ["jquery", "lodash"], function($, _) {
making the module and its dependencies available globally. // This publicly accessible object is our module
// Here we use an object, but it can be of any type
(function (root, factory) { var myModule = {};
if (typeof define === 'function' && [Link]) {
// AMD. Register as an anonymous module. var privateVar = "Nothing outside of this module can see me";
define(['exports', 'b'], factory);
} else if (typeof exports === 'object' && typeof [Link] !== 'string') { var privateFn = function(param) {
// CommonJS return "Here's what you said: " + param;
factory(exports, require('b')); };
} else {
// Browser globals [Link] = 1;
factory(([Link] = {}), root.b);
} [Link] = function() {
}(this, function (exports, b) { // We can still access global variables from here, but it's better
//use b in some fashion. // if we use the passed ones
return privateFn(windowTitle);
// attach properties to the exports object to define };
// the exported module properties.
[Link] = function () {}; return myModule;
})); });

Section 73.3: Immediately invoked function expressions (IIFE) Modules can also skip the name and be anonymous. When that's done, they're usually loaded by file name.

Immediately invoked function expressions can be used to create a private scope while producing a public API. define(["jquery", "lodash"], function($, _) { /* factory */ });

var Module = (function() { They can also skip dependencies:


var privateData = 1;
define(function() { /* factory */ });
return {
getPrivateData: function() {
Some AMD loaders support defining modules as plain objects:
return privateData;
}
}; define("myModule", { version: 1, value: "sample string" });
})();
[Link](); // 1
[Link]; // undefined
Section 73.5: CommonJS - [Link]
CommonJS is a popular modularization pattern that's used in [Link].
See the Module Pattern for more details.
The CommonJS system is centered around a require() function that loads other modules and an exports property
Section 73.4: Asynchronous Module Definition (AMD) that lets modules export publicly accessible methods.

AMD is a module definition system that attempts to address some of the common issues with other systems like Here's an example of CommonJS, we'll load Lodash and [Link]' fs module:
CommonJS and anonymous closures.
// Load fs and lodash, we can use them anywhere inside the module
AMD addresses these issues by: var fs = require("fs"),
_ = require("lodash");
Registering the factory function by calling define(), instead of immediately executing it
Passing dependencies as an array of module names, which are then loaded, instead of using globals var myPrivateFn = function(param) {
return "Here's what you said: " + param;
Only executing the factory function once all the dependencies have been loaded and executed
};

[Link] – JavaScript® Notes for Professionals 371 [Link] – JavaScript® Notes for Professionals 372
// Here we export a public `myMethod` that other modules can use
[Link] = function(param) {
return myPrivateFn(param);
Chapter 74: Proxy
};
Parameter Details
target The target object, actions on this object (getting, setting, etc...) will be routed through the handler
You can also export a function as the entire module using [Link]:
handler An object that can define "traps" for intercepting actions on the target object (getting, setting, etc...)

[Link] = function() {
return "Hello!";
A Proxy in JavaScript can be used to modify fundamental operations on objects. Proxies were introduced in ES6. A
}; Proxy on an object is itself an object, that has traps. Traps may be triggered when operations are performed on the
Proxy. This includes property lookup, function calling, modifying properties, adding properties, et cetera. When no
applicable trap is defined, the operation is performed on the proxied object as if there was no Proxy.

Section 74.1: Proxying property lookup


To influence property lookup, the get handler must be used.

In this example, we modify property lookup so that not only the value, but also the type of that value is returned.
We use Reflect to ease this.

let handler = {
get(target, property) {
if (![Link](target, property)) {
return {
value: undefined,
type: 'undefined'
};
}
let value = [Link](target, property);
return {
value: value,
type: typeof value
};
}
};

let proxied = new Proxy({foo: 'bar'}, handler);


[Link]([Link]); // logs `Object {value: "bar", type: "string"}`

Section 74.2: Very simple proxy (using the set trap)


This proxy simply appends the string " went through proxy" to every string property set on the target object.

let object = {};

let handler = {
set(target, prop, value){ // Note that ES6 object syntax is used
if('string' === typeof value){
target[prop] = value + " went through proxy";
}
}
};

let proxied = new Proxy(object, handler);

[Link] = "ExampleValue";

[Link](object);
// logs: { example: "ExampleValue went through proxy" }

[Link] – JavaScript® Notes for Professionals 373 [Link] – JavaScript® Notes for Professionals 374
// you could also access the object via [Link]
Chapter 75: .postMessage() and
MessageEvent
Parameters
message
targetOrigin
transfer optional

Section 75.1: Getting Started


What is .postMessage(), when and why do we use it

.postMessage() method is a way to safely allow communication between cross-origin scripts.

Normally, two different pages, can only directly communicate with each other using JavaScript when they are under
the same origin, even if one of them is embedded into another (e.g. iframes) or one is opened from inside the
other (e.g. [Link]()). With .postMessage(), you can work around this restriction while still staying safe.

You can only use .postMessage() when you have access to both pages' JavaScript code. Since the receiver
needs to validate the sender and process the message accordingly, you can only use this method to communicate
between two scripts you have access to.

We will build an example to send messages to a child window and have the messages be displayed on the child
window. The parent/sender page will be assumed to be [Link] and child/receiver page will be
assumed to be [Link] for the example.

Sending messages

In order to send messages to another window, you need to have a reference to its window object. [Link]()
returns the reference object of the newly opened window. For other methods to obtain a reference to a window
object, see the explanation under otherWindow parameter here.

var childWindow = [Link]("[Link] "_blank");

Add a textarea and a send button that will be used to send messages to child window.

<textarea id="text"></textarea>
<button id="btn">Send Message</button>

Send the text of textarea using .postMessage(message, targetOrigin) when the button is clicked.

var btn = [Link]("btn"),


text = [Link]("text");

[Link]("click", function () {
sendMessage([Link]);
[Link] = "";
});

function sendMessage(message) {
if (!message || ![Link]) return;
[Link]([Link]({
message: message,
time: new Date()

[Link] – JavaScript® Notes for Professionals 375 [Link] – JavaScript® Notes for Professionals 376
}), '[Link] Click here for a JS Fiddle showcasing its usage.
}

In order send and receive JSON objects instead of a simple string, [Link]() and [Link]() methods
can be used. A Transfarable Object can be given as the third optional parameter of the .postMessage(message,
targetOrigin, transfer) method, but browser support is still lacking even in modern browsers.

For this example, since our receiver is assumed to be [Link] page, we enter its url as the
targetOrigin. The value of this parameter should match the origin of the childWindow object for the message to
be send. It is possible to use * as a wildcard but is highly recommended to avoid using the wildcard and always
set this parameter to receiver's specific origin for security reasons.

Receiving, Validating and Processing Messages

The code under this part should be put in the receiver page, which is [Link] for our example.

In order to receive messages, the message event of the window should be listened.

[Link]("message", receiveMessage);

When a message is received there are a couple of steps that should be followed to assure security as much as
possible.

Validate the sender


Validate the message
Process the message

The sender should always be validated to make sure the message is received from a trusted sender. After that, the
message itself should be validated to make sure nothing malicious is received. After these two validations, the
message can be processed.

function receiveMessage(ev) {
//Check [Link] to see if it is a trusted sender.
//If you have a reference to the sender, validate [Link]
//We only want to receive messages from [Link] our trusted sender page.
if ([Link] !== "[Link] || [Link] !== [Link])
return;

//Validate the message


//We want to make sure it's a valid json object and it does not contain anything malicious
var data;
try {
data = [Link]([Link]);
//[Link] = cleanseText([Link])
} catch (ex) {
return;
}

//Do whatever you want with the received message


//We want to append the message into our #console div
var p = [Link]("p");
[Link] = (new Date([Link])).toLocaleTimeString() + " | " + [Link];
[Link]("console").appendChild(p);
}

[Link] – JavaScript® Notes for Professionals 377 [Link] – JavaScript® Notes for Professionals 378
Chapter 76: WeakMap Section 76.5: Removing an element with the key
To remove an element with a specified key, use the .delete() method. It returns true if the element existed and
Section 76.1: Creating a WeakMap object has been removed, otherwise false.

WeakMap object allows you to store key/value pairs. The difference from Map is that keys must be objects and are const obj1 = {},
weakly referenced. This means that if there aren't any other strong references to the key, the element in WeakMap obj2 = {};
can be removed by garbage collector.
const weakmap = new WeakMap([[obj1, 7]]);
[Link]([Link](obj1)); // true
WeakMap constructor has an optional parameter, which can be any iterable object (for example Array) containing
[Link]([Link](obj1)); // false
key/value pairs as two-element arrays. [Link]([Link](obj2)); // false

const o1 = {a: 1, b: 2},


o2 = {}; Section 76.6: Weak reference demo
const weakmap = new WeakMap([[o1, true], [o2, o1]]); JavaScript uses reference counting technique to detect unused objects. When reference count to an object is zero,
that object will be released by the garbage collector. Weakmap uses weak reference that does not contribute to
Section 76.2: Getting a value associated to the key reference count of an object, therefore it is very useful to solve memory leak problems.

To get a value associated to the key, use the .get() method. If there's no value associated to the key, it returns Here is a demo of weakmap. I use a very large object as value to show that weak reference does not contribute to
undefined. reference count.

const obj1 = {}, // manually trigger garbage collection to make sure that we are in good status.
obj2 = {}; > [Link]();
undefined
const weakmap = new WeakMap([[obj1, 7]]);
[Link]([Link](obj1)); // 7 // check initial memory use,heapUsed is 4M or so
[Link]([Link](obj2)); // undefined > [Link]();
{ rss: 21106688,
heapTotal: 7376896,
Section 76.3: Assigning a value to the key heapUsed: 4153936,
external: 9059 }
To assign a value to the key, use the .set() method. It returns the WeakMap object, so you can chain .set() calls.
> let wm = new WeakMap();
undefined
const obj1 = {},
obj2 = {};
> const b = new Object();
undefined
const weakmap = new WeakMap();
[Link](obj1, 1).set(obj2, 2);
> [Link]();
[Link]([Link](obj1)); // 1
undefined
[Link]([Link](obj2)); // 2

// heapUsed is still 4M or so
Section 76.4: Checking if an element with the key exists > [Link]();
{ rss: 20537344,
heapTotal: 9474048,
To check if an element with a specified key exits in a WeakMap, use the .has() method. It returns true if it exits,
heapUsed: 3967272,
and otherwise false. external: 8993 }

const obj1 = {}, // add key-value tuple into WeakMap,


obj2 = {}; // key is b,value is 5*1024*1024 array
> [Link](b, new Array(5*1024*1024));
const weakmap = new WeakMap([[obj1, 7]]); WeakMap {}
[Link]([Link](obj1)); // true
[Link]([Link](obj2)); // false // manually garbage collection
> [Link]();
undefined

// heapUsed is still 45M

[Link] – JavaScript® Notes for Professionals 379 [Link] – JavaScript® Notes for Professionals 380
> [Link]();
{ rss: 62652416,
heapTotal: 51437568,
Chapter 77: WeakSet
Section 77.1: Creating a WeakSet object
heapUsed: 45911664,
external: 8951 }

// b reference to null The WeakSet object is used for storing weakly held objects in a collection. The difference from Set is that you can't
> b = null; store primitive values, like numbers or string. Also, references to the objects in the collection are held weakly, which
null means that if there is no other reference to an object stored in a WeakSet, it can be garbage collected.

// garbage collection
The WeakSet constructor has an optional parameter, which can be any iterable object (for example an array). All of
> [Link]();
undefined its elements will be added to the created WeakSet.

// after remove b reference to object,heapUsed is 4M again const obj1 = {},


// it means the big array in WeakMap is released obj2 = {};
// it also means weekmap does not contribute to big array's reference count, only b does.
> [Link](); const weakset = new WeakSet([obj1, obj2]);
{ rss: 20639744,
heapTotal: 8425472,
heapUsed: 3979792, Section 77.2: Adding a value
external: 8956 }
To add a value to a WeakSet, use the .add() method. This method is chainable.

const obj1 = {},


obj2 = {};

const weakset = new WeakSet();


[Link](obj1).add(obj2);

Section 77.3: Checking if a value exists


To check if a value exits in a WeakSet, use the .has() method.

const obj1 = {},


obj2 = {};

const weakset = new WeakSet([obj1]);


[Link]([Link](obj1)); // true
[Link]([Link](obj2)); // false

Section 77.4: Removing a value


To remove a value from a WeakSet, use the .delete() method. This method returns true if the value existed and
has been removed, otherwise false.

const obj1 = {},


obj2 = {};

const weakset = new WeakSet([obj1]);


[Link]([Link](obj1)); // true
[Link]([Link](obj2)); // false

[Link] – JavaScript® Notes for Professionals 381 [Link] – JavaScript® Notes for Professionals 382
Chapter 78: Escape Sequences Characters with codes between 0 and 255 can be represented with an escape sequence where \x is followed by the
2-digit hexadecimal character code. For example, the non-breaking space character has code 160 or A0 in base 16,
and so it can be written as \xa0.
Section 78.1: Entering special characters in strings and
regular expressions var str = "ONE\xa0LINE"; // ONE and LINE with a non-breaking space between them

Most printable characters can be included in string or regular expression literals just as they are, e.g. For hex digits above 9, the letters a to f are used, in lowercase or uppercase without distinction.

var str = "ポケモン"; // a valid string var regExp1 = /[\x00-xff]/; // matches any character between U+0000 and U+00FF
var regExp = /[Α-Ωα-ω]/; // matches any Greek letter without diacritics var regExp2 = /[\x00-xFF]/; // same as above

4-digit Unicode escape sequences


In order to add arbitrary characters to a string or regular expression, including non-printable ones, one has to use
escape sequences. Escape sequences consist of a backslash ("\\") followed by one or more other characters. To write Characters with codes between 0 and 65535 (216 - 1) can be represented with an escape sequence where \u is
an escape sequence for a particular character, one typically (but not always) needs to know its hexadecimal followed by the 4-digit hexadecimal character code.
character code.
For example, the Unicode standard defines the right arrow character ("?") with the number 8594, or 2192 in
JavaScript provides a number of different ways to specify escape sequences, as documented in the examples in this hexadecimal format. So an escape sequence for it would be \u2192.
topic. For instance, the following escape sequences all denote the same character: the line feed (Unix newline
This produces the string "A ? B":
character), with character code U+000A.

\\n var str = "A \u2192 B";

\\x0a
\\u000a
For hex digits above 9, the letters a to f are used, in lowercase or uppercase without distinction. Hexadecimal codes
\\u{a} new in ES6, only in strings
shorter than 4 digits must be left-padded with zeros: \u007A for the small letter "z".
\\012 forbidden in string literals in strict mode and in template strings
Curly bracket Unicode escape sequences
\\cj only in regular expressions Version ≥ 6

Section 78.2: Escape sequence types ES6 extends Unicode support to the full code range from 0 to 0x10FFFF. In order to escape characters with code
greater than 216 - 1, a new syntax for escape sequences was introduced:
Single character escape sequences
\u{???}
Some escape sequences consist of a backslash followed by a single character.
Where the code in curly braces is hexadecimal representation of the code point value, e.g.
For example, in alert("Hello\nWorld");, the escape sequence \n is used to introduce a newline in the string
parameter, so that the words "Hello" and "World" are displayed in consecutive lines. alert("Look! \u{1f440}"); // Look! ????

Escape sequence Character Unicode


In the example above, the code 1f440 is the hexadecimal representation of the character code of the Unicode
\b (only in strings, not in regular expressions) backspace U+0008
Character Eyes.
\t horizontal tab U+0009
\n line feed U+000A Note that the code in curly braces may contain any number of hex digits, as long the value does not exceed
\v vertical tab U+000B 0x10FFFF. For hex digits above 9, the letters a to f are used, in lowercase or uppercase without distinction.
\f form feed U+000C
Unicode escape sequences with curly braces only work inside strings, not inside regular expressions!
\r carriage return U+000D
Octal escape sequences
Additionally, the sequence \0, when not followed by a digit between 0 and 7, can be used to escape the null
character (U+0000). Octal escape sequences are deprecated as of ES5, but they are still supported inside regular expressions and in
non-strict mode also inside non-template strings. An octal escape sequence consists of one, two or three octal
The sequences \\, \' and \" are used to escape the character that follows the backslash. While similar to non- digits, with value between 0 and 3778 = 255.
escape sequences, where the leading backslash is simply ignored (i.e. \? for ?), they are explicitly treated as single
character escape sequences inside strings as per the specification. For example, the capital letter "E" has character code 69, or 105 in base 8. So it can be represented with the escape
sequence \105:
Hexadecimal escape sequences

[Link] – JavaScript® Notes for Professionals 383 [Link] – JavaScript® Notes for Professionals 384
/\105scape/.test("Fun with Escape Sequences"); // true
Chapter 79: Behavioral Design Patterns
In strict mode, octal escape sequences are not allowed inside strings and will produce a syntax error. It is worth to
note that \0, unlike \00 or \000, is not considered an octal escape sequence, and is thus still allowed inside strings Section 79.1: Observer pattern
(even template strings) in strict mode.
The Observer pattern is used for event handling and delegation. A subject maintains a collection of observers. The
Control escape sequences subject then notifies these observers whenever an event occurs. If you've ever used addEventListener then you've
utilized the Observer pattern.
Some escape sequences are only recognized inside regular expression literals (not in strings). These can be used to
escape characters with codes between 1 and 26 (U+0001–U+001A). They consist of a single letter A–Z (case makes function Subject() {
no difference) preceded by \c. The alphabetic position of the letter after \c determines the character code. [Link] = []; // Observers listening to the subject

[Link] = function(observer) {
For example, in the regular expression
// Add an observer if it isn't already being tracked
if ([Link](observer) === -1) {
`/\cG/` [Link](observer);
}
The letter "G" (the 7th letter in the alphabet) refers to the character U+0007, and thus };

`/\cG`/.test([Link](7)); // true [Link] = function(observer) {


// Removes a previously registered observer
var index = [Link](observer);
if (index > -1) {
[Link](index, 1);
}
};

[Link] = function(message) {
// Send a message to all observers
[Link](function(observer) {
[Link](message);
});
};
}

function Observer() {
[Link] = function(message) {
// Every observer must implement this function
};
}

Example usage:

function Employee(name) {
[Link] = name;

// Implement `notify` so the subject can pass us messages


[Link] = function(meetingTime) {
[Link]([Link] + ': There is a meeting at ' + meetingTime);
};
}

var bob = new Employee('Bob');


var jane = new Employee('Jane');
var meetingAlerts = new Subject();
[Link](bob);
[Link](jane);
[Link]('4pm');

// Output:

[Link] – JavaScript® Notes for Professionals 385 [Link] – JavaScript® Notes for Professionals 386
// Bob: There is a meeting at 4pm })();
// Jane: There is a meeting at 4pm
function run() {
var yoko = new Participant("Yoko");
Section 79.2: Mediator Pattern var john = new Participant("John");
var paul = new Participant("Paul");
Think of the mediator pattern as the flight control tower that controls planes in the air: it directs this plane to land var ringo = new Participant("Ringo");
now, the second to wait, and the third to take off, etc. However no plane is ever allowed to talk to its peers.
var chatroom = new Chatroom();
This is how mediator works, it works as a communication hub among different modules, this way you reduce [Link](yoko);
[Link](john);
module dependency on each other, increase loose coupling, and consequently portability.
[Link](paul);
[Link](ringo);
This Chatroom example explains how mediator patterns works:
[Link]("All you need is love.");
// each participant is just a module that wants to talk to other modules(other participants) [Link]("I love you John.");
var Participant = function(name) { [Link]("Ha, I heard that!");
[Link] = name;
[Link] = null; [Link]();
}; }
// each participant has method for talking, and also listening to other participants
[Link] = {
send: function(message, to) { Section 79.3: Command
[Link](message, this, to);
}, The command pattern encapsulates parameters to a method, current object state, and which method to call. It is
receive: function(message, from) { useful to compartmentalize everything needed to call a method at a later time. It can be used to issue a "command"
[Link]([Link] + " to " + [Link] + ": " + message);
and decide later which piece of code to use to execute the command.
}
};
There are three components in this pattern:
// chatroom is the Mediator: it is the hub where participants send messages to, and receive messages
from 1. Command Message - the command itself, including the method name, parameters, and state
var Chatroom = function() { 2. Invoker - the part which instructs the command to execute its instructions. It can be a timed event, user
var participants = {}; interaction, a step in a process, callback, or any way needed to execute the command.
3. Receiver - the target of the command execution.
return {

Command Message as an Array


register: function(participant) {
participants[[Link]] = participant;
[Link] = this; var aCommand = new Array();
}, [Link](new Instructions().DoThis); //Method to execute
[Link]("String Argument"); //string argument
send: function(message, from) { [Link](777); //integer argument
for (key in participants) { [Link](new Object {} ); //object argument
if (participants[key] !== from) {//you can't message yourself ! [Link](new Array() ); //array argument
participants[key].receive(message, from);
} Constructor for command class
}
}
class DoThis {
constructor( stringArg, numArg, objectArg, arrayArg ) {
};
this._stringArg = stringArg;
};
this._numArg = numArg;
this._objectArg = objectArg;
// log helper
this._arrayArg = arrayArg;
}
var log = (function() {
Execute() {
var log = "";
var receiver = new Instructions();
[Link](this._stringArg, this._numArg, this._objectArg, this._arrayArg );
return {
}
add: function(msg) { log += msg + "\n"; },
}
show: function() { alert(log); log = ""; }
}

[Link] – JavaScript® Notes for Professionals 387 [Link] – JavaScript® Notes for Professionals 388
Invoker if( preferredBeverage( bevToOrder ) {
[Link]; //false, because "Beer" isn't the final collection item
return bevToOrder; //"Beer"
[Link]();
}
}
Can invoke:
As a Generator
immediately
in response to an event
class FibonacciIterator {
in a sequence of execution constructor() {
as a callback response or in a promise [Link] = 1;
at the end of an event loop [Link] = 1;
}
in any other needed way to invoke a method
next() {
var current = [Link] + [Link];
Receiver
[Link] = [Link];
[Link] = current;
class Instructions { return current;
DoThis( stringArg, numArg, objectArg, arrayArg ) { }
[Link]( `${stringArg}, ${numArg}, ${objectArg}, ${arrayArg}` ); }
}
} var fib = new FibonacciIterator();
[Link](); //2
A client generates a command, passes it to an invoker that either executes it immediately or delays the command, [Link](); //3
[Link](); //5
and then the command acts upon a receiver. The command pattern is very useful when used with companion
patterns to create messaging patterns.
In ECMAScript 2015

Section 79.4: Iterator function* FibonacciGenerator() { //asterisk informs javascript of generator


var previous = 1;
An iterator pattern provides a simple method for selecting, sequentially, the next item in a collection. var beforePrevious = 1;
while(true) {
Fixed Collection var current = previous + beforePrevious;
beforePrevious = previous;
class BeverageForPizza { previous = current;
constructor(preferenceRank) { yield current; //This is like return but
[Link] = beverageList; //keeps the current state of the function
[Link] = 0; // i.e it remembers its place between calls
} }
next() { }
return [Link][[Link]++];
} var fib = FibonacciGenerator();
[Link]().value; //2
var withPepperoni = new BeverageForPizza(["Cola", "Water", "Beer"]); [Link]().value; //3
[Link](); //Cola [Link]().value; //5
[Link](); //Water [Link]().done; //false
[Link](); //Beer

In ECMAScript 2015 iterators are a built-in as a method that returns done and value. done is true when the iterator
is at the end of the collection

function preferredBeverage(beverage){
if( beverage == "Beer" ){
return true;
} else {
return false;
}
}
var withPepperoni = new BeverageForPizza(["Cola", "Water", "Beer", "Orange Juice"]);
for( var bevToOrder of withPepperoni ){

[Link] – JavaScript® Notes for Professionals 389 [Link] – JavaScript® Notes for Professionals 390
Chapter 80: Server-sent events [Link]("heartbeat", function(event) {
var status = [Link];
if (status=='OK') {

Section 80.1: Setting up a basic event stream to the server


// do something
}
});
You can setup your client browser to listen in incoming server events using the EventSource object. You will need to
supply the constructor a string of the path to the server' API endpoint the will subscribe the client to the server
events.

Example:

var eventSource = new EventSource("api/my-events");

Events have names with which they are categorized and sent, and a listener must be setup to listen to each such
event by name. the default event name is message and in order to listen to it you must use the appropriate event
listener, .onmessage

[Link] = function(event) {
var data = [Link]([Link]);
// do something with data
}

The above function will run every time the server will push an event to the client. Data is sent as text/plain, if you
send JSON data you may want to parse it.

Section 80.2: Closing an event stream


An event stream to the server can be closed using the [Link]() method

var eventSource = new EventSource("api/my-events");


// do things ...
[Link](); // you will not receive anymore events from this object

The .close() method does nothing is the stream is already closed.

Section 80.3: Binding event listeners to EventSource


You can bind event listeners to the EventSource object to listen to different events channels using the
.addEventListener method.

[Link](name: String, callback: Function, [options])

name: The name related to the name of the channel the server is emitting events to.

callback: The callback function runs every time an event bound to the channel is emitted, the function provides the
event as an argument.

options: Options that characterize the behavior of the event listener.

The following example shows a heartbeat event stream from the server, the server sends events on the heartbeat
channel and this routine will always run when an event in accepted.

var eventSource = new EventSource("api/heartbeat");


...

[Link] – JavaScript® Notes for Professionals 391 [Link] – JavaScript® Notes for Professionals 392
Chapter 81: Async functions (async/await) }
await (getUnicorn().getSize());

async and await build on top of promises and generators to express asynchronous actions inline. This makes Here we attempt to call getSize() method of the Promise object, which isn't what we want.
asynchronous or callback code much easier to maintain.
Instead, we should use brackets to denote that we first want to wait for the unicorn, and then call getSize()
Functions with the async keyword return a Promise, and can be called with that syntax. method of the result:

Inside an async function the await keyword can be applied to any Promise, and will cause all of the function body async function asyncFunction() {
after the await to be executed after the promise resolves. (await getUnicorn()).getSize();
}

Section 81.1: Introduction Of course. the previous version could be valid in some cases, for example, if the getUnicorn() function was
A function defined as async is a function that can perform asynchronous actions but still look synchronous. The synchronous, but the getSize() method was asynchronous.
way it's done is using the await keyword to defer the function while it waits for a Promise to resolve or reject.
Section 81.3: Async functions compared to Promises
Note: Async functions are a Stage 4 ("Finished") proposal on track to be included in the ECMAScript 2017 standard.
async functions do not replace the Promise type; they add language keywords that make promises easier to call.
For instance, using the promise-based Fetch API: They are interchangeable:

async function getJSON(url) { async function doAsyncThing() { ... }


try {
const response = await fetch(url); function doPromiseThing(input) { return new Promise((r, x) => ...); }
return await [Link]();
} // Call with promise syntax
catch (err) { doAsyncThing()
// Rejections in the promise will get thrown here .then(a => doPromiseThing(a))
[Link]([Link]); .then(b => ...)
} .catch(ex => ...);
}
// Call with await syntax
An async function always returns a Promise itself, so you can use it in other asynchronous functions. try {
const a = await doAsyncThing();
const b = await doPromiseThing(a);
Arrow function style
...
const getJSON = async url => { }
const response = await fetch(url); catch(ex) { ... }
return await [Link]();
}
Any function that uses chains of promises can be rewritten using await:

Section 81.2: Await and operator precedence function newUnicorn() {


return fetch('[Link]') // fetch [Link] from server
You have to keep the operator precedence in mind when using await keyword. .then(responseCurrent => [Link]()) // parse the response as JSON
.then(unicorn =>
Imagine that we have an asynchronous function which calls another asynchronous function, getUnicorn() which fetch('new/unicorn', { // send a request to 'new/unicorn'
method: 'post', // using the POST method
returns a Promise that resolves to an instance of class Unicorn. Now we want to get the size of the unicorn using
body: [Link]({unicorn}) // pass the unicorn to the request body
the getSize() method of that class. })
)
Look at the following code: .then(responseNew => [Link]())
.then(json => [Link]) // return success property of response
async function myAsyncFunction() { .catch(err => [Link]('Error creating unicorn:', err));
await getUnicorn().getSize(); }
}
The function can be rewritten using async / await as follows:
At first sight, it seems valid, but it's not. Due to operator precedence, it's equivalent to the following:
async function newUnicorn() {
async function myAsyncFunction() { try {

[Link] – JavaScript® Notes for Professionals 393 [Link] – JavaScript® Notes for Professionals 394
const responseCurrent = await fetch('[Link]'); // fetch [Link] from server [Link](async(e) => {
const unicorn = await [Link](); // parse the response as JSON const i = await somePromiseFn(e);
const responseNew = await fetch('new/unicorn', { // send a request to 'new/unicorn' [Link](i);
method: 'post', // using the POST method });
body: [Link]({unicorn}) // pass the unicorn to the request body [Link]('this will print first');
}); })();
const json = await [Link]();
return [Link] // return success property of response
This happens because the callback async function can only pause itself, not the parent async function.
} catch (err) {
[Link]('Error creating unicorn:', err);
}
You could write an asyncForEach function that returns a promise and then you could something like
}
await asyncForEach(async (e) => await somePromiseFn(e), data ) Basically you return a promise
that resolves when all the callbacks are awaited and done. But there are better ways of doing this, and
This async variant of newUnicorn() appears to return a Promise, but really there were multiple await keywords.
that is to just use a loop.
Each one returned a Promise, so really we had a collection of promises rather than a chain.

In fact we can think of it as a function* generator, with each await being a yield new Promise. However, the You can use a for-of loop or a for/while loop, it doesn't really matter which one you pick.
results of each promise are needed by the next to continue the function. This is why the additional keyword async
is needed on the function (as well as the await keyword when calling the promises) as it tells JavaScript to (async() => {
automatically creates an observer for this iteration. The Promise returned by async function newUnicorn() data = [1, 2, 3, 4, 5];
resolves when this iteration completes. for (let e of data) {
const i = await somePromiseFn(e);
Practically, you don't need to consider that; await hides the promise and async hides the generator iteration. [Link](i);
}
[Link]('this will print last');
You can call async functions as if they were promises, and await any promise or any async function. You don't need
})();
to await an async function, just as you can execute a promise without a .then().

But there's another catch. This solution will wait for each call to somePromiseFn to complete before iterating over
You can also use an async IIFE if you want to execute that code immediately:
the next one.
(async () => { This is great if you actually want your somePromiseFn invocations to be executed in order but if you want them to
await makeCoffee() run concurrently, you will need to await on [Link].
[Link]('coffee is ready!')
})() (async() => {
data = [1, 2, 3, 4, 5];

Section 81.4: Looping with async await const p = await [Link]([Link](async(e) => await somePromiseFn(e)));
[Link](...p);
})();
When using async await in loops, you might encounter some of these problems.
[Link] receives an array of promises as its only parameter and returns a promise. When all of the promises
If you just try to use await inside forEach, this will throw an Unexpected token error.
in the array are resolved, the returned promise is also resolved. We await on that promise and when it's resolved
(async() => { all our values are available.
data = [1, 2, 3, 4, 5];
[Link](e => { The above examples are fully runnable. The somePromiseFn function can be made as an async echo function with a
const i = await somePromiseFn(e); timeout. You can try out the examples in the babel-repl with at least the stage-3 preset and look at the output.
[Link](i);
}); function somePromiseFn(n) {
})(); return new Promise((res, rej) => {
setTimeout(() => res(n), 250);
This comes from the fact that you've erroneously seen the arrow function as a block. The await will be in the });
context of the callback function, which is not async. }

The interpreter protects us from making the above error, but if you add async to the forEach callback no errors get
thrown. You might think this solves the problem, but it won't work as expected. Section 81.5: Less indentation
Example: With promises:

(async() => { function doTheThing() {


data = [1, 2, 3, 4, 5]; return doOneThing()

[Link] – JavaScript® Notes for Professionals 395 [Link] – JavaScript® Notes for Professionals 396
.then(doAnother)
.then(doSomeMore)
.catch(handleErrors)
Chapter 82: Async Iterators
}
An async function is one that returns a promise. await yields to the caller until the promise resolves and then
continues with the result.
With async functions:
An iterator allows the collection to be looped through with a for-of loop.
async function doTheThing() {
try { An async iterator is a collection where each iteration is a promise which can be awaited using a for-await-of loop.
const doOneThing();
const another = await doAnother(one);
Async iterators are a stage 3 proposal. They are in Chrome Canary 60 with --harmony-async-iteration
return await doSomeMore(another);
} catch (err) {
handleErrors(err); Section 82.1: Basics
}
} A JavaScript Iterator is an object with a .next() method, which returns an IteratorItem, which is an object with
value : <any> and done : <boolean>.
Note how the return is at the bottom, and not at the top, and you use the language's native error-handling
mechanics (try/catch). A JavaScript AsyncIterator is an object with a .next() method, which returns a Promise<IteratorItem>, a promise
for the next value.
Section 81.6: Simultaneous async (parallel) operations To create an AsyncIterator, we can use the async generator syntax:
Often you will want to perform asynchronous operations in parallel. There is direct syntax that supports this in the
/**
async/await proposal, but since await will wait for a promise, you can wrap multiple promises together in
* Returns a promise which resolves after time had passed.
[Link] to wait for them:
*/
const delay = time => new Promise(resolve => setTimeout(resolve, time));
// Not in parallel
async function* delayedRange(max) {
async function getFriendPosts(user) { for (let i = 0; i < max; i++) {
friendIds = await [Link]("friends", {user}, {id: 1}); await delay(1000);
friendPosts = []; yield i;
for (let id in friendIds) { }
friendPosts = [Link]( await [Link]("posts", {user: id}) ); }
}
// etc.
The delayedRange function will take a maximum number, and returns an AsyncIterator, which yields numbers
}
from 0 to that number, in 1 second intervals.

This will do each query to get each friend's posts serially, but they can be done simultaneously:
Usage:

// In parallel
for await (let number of delayedRange(10)) {
[Link](number);
async function getFriendPosts(user) {
}
friendIds = [Link]("friends", {user}, {id: 1});
friendPosts = await [Link]( [Link](id =>
[Link]("posts", {user: id}) The for await of loop is another piece of new syntax, available only inside of async functions, as well as async
); generators. Inside the loop, the values yielded (which, remember, are Promises) are unwrapped, so the Promise is
// etc. hidden away. Within the loop, you can deal with the direct values (the yielded numbers), the for await of loop will
}
wait for the Promises on your behalf.

This will loop over the list of IDs to create an array of promises. await will wait for all promises to be complete. The above example will wait 1 second, log 0, wait another second, log 1, and so on, until it logs 9. At which point the
[Link] combines them into a single promise, but they are done in parallel. AsyncIterator will be done, and the for await of loop will exit.

[Link] – JavaScript® Notes for Professionals 397 [Link] – JavaScript® Notes for Professionals 398
Chapter 83: How to make iterator usable Chapter 84: Tail Call Optimization
inside async callback function Section 84.1: What is Tail Call Optimization (TCO)
When using async callback we need to consider scope. Especially if inside a loop. This simple article shows what
TCO is only available in strict mode
not to do and a simple working example.
As always check browser and JavaScript implementations for support of any language features, and as with any
Section 83.1: Erroneous code, can you spot why this usage of JavaScript feature or syntax, it may change in the future.
key will lead to bugs?
It provides a way to optimise recursive and deeply nested function calls by eliminating the need to push function
var pipeline = {}; state onto the global frame stack, and avoiding having to step down through each calling function by returning
// (...) adding things in pipeline directly to the initial calling function.

for(var key in pipeline) { function a(){


[Link](pipeline[key].path, function(err, stats) { return b(); // 2
if (err) { }
// clear that one function b(){
delete pipeline[key]; return 1; // 3
return; }
} a(); // 1
// (...)
pipeline[key].count++;
}); Without TCO the call to a() creates a new frame for that function. When that function calls b() the a()'s frame is
} pushed onto the frame stack and a new frame is created for function b()

The problem is that there is only one instance of var key. All callbacks will share the same key instance. At the time When b() return to a() a()'s frame is popped from the frame stack. It immediately return to the global frame and
thus does not use any of the states save on the stack.
the callback will fire, the key will most likely have been incremented and not pointing to the element we are
receiving the stats for.
TCO recognises that the call from a() to b() is at the tail of function a() and thus there is no need to push a()'s
state onto the frame stack. When b(0) returns rather than returning to a() it returns directly to the global frame.
Section 83.2: Correct Writing Further optimising by eliminating the intermediate steps.

var pipeline = {}; TCO allows for recursive functions to have indefinite recursion as the frame stack will not grow with each recursive
// (...) adding things in pipeline
call. Without TCO recursive function had a limited recursive depth.
var processOneFile = function(key) {
[Link](pipeline[key].path, function(err, stats) {
Note TCO is a JavaScript engine implementation feature, it cannot be implemented via a transpiler if the
if (err) {
// clear that one browser does not support it. There is no additional syntax in the spec required to implement TCO and
delete pipeline[key]; thus there is concern that TCO may break the web. Its release into the world is cautious and may require
return; browser/engine specific flags to be set for the perceivable future.
}
// (...)
pipeline[key].count++;
}); Section 84.2: Recursive loops
};
Tail Call Optimisation makes it possible to safely implement recursive loops without concern for call stack overflow
// verify it is not growing or the overhead of a growing frame stack.
for(var key in pipeline) {
processOneFileInPipeline(key); function indexOf(array, predicate, i = 0) {
} if (0 <= i && i < [Link]) {
if (predicate(array[i])) { return i; }
By creating a new function, we are scoping key inside a function so all callback have their own key instance. return indexOf(array, predicate, i + 1); // the tail call
}
}
indexOf([1,2,3,4,5,6,7], x => x === 5); // returns index of 5 which is 4

[Link] – JavaScript® Notes for Professionals 399 [Link] – JavaScript® Notes for Professionals 400
Chapter 85: Bitwise Operators - Real if(n & 1) {
[Link]("ODD!");

World Examples (snippets) } else {


[Link]("EVEN!");
}
Section 85.1: Swapping Two Integers with Bitwise XOR
(without additional memory allocation) (this is actually valid not only for JavaScript)

var a = 11, b = 22;


a = a ^ b;
b = a ^ b;
a = a ^ b;
[Link]("a = " + a + "; b = " + b);// a is now 22 and b is now 11

Section 85.2: Faster multiplication or division by powers of 2


Shifting bits left (right) is equivalent to multiplying (dividing) by 2. It's the same in base 10: if we "left-shift" 13 by 2
places, we get 1300, or 13 * (10 ** 2). And if we take 12345 and "right-shift" by 3 places and then remove the
decimal part, we get 12, or [Link](12345 / (10 ** 3)). So if we want to multiply a variable by 2 ** n, we can
just left-shift by n bits.

[Link](13 * (2 ** 6)) //13 * 64 = 832


[Link](13 << 6) // 832

Similarly, to do (floored) integer division by 2 ** n, we can right shift by n bits. Example:

[Link](1000 / (2 ** 4)) //1000 / 16 = 62.5


[Link](1000 >> 4) // 62

It even works with negative numbers:

[Link](-80 / (2 ** 3)) //-80 / 8 = -10


[Link](-80 >> 3) // -10

In reality, speed of arithmetic is unlikely to significantly impact how long your code takes to run, unless you are
doing on the order of 100s of millions of computations. But C programmers love this sort of thing!

Section 85.3: Number's Parity Detection with Bitwise AND


Instead of this (unfortunately too often seen in the real code) "masterpiece":

function isEven(n) {
return n % 2 == 0;
}

function isOdd(n) {
if (isEven(n)) {
return false;
} else {
return true;
}
}

You can do the parity check much more effective and simple:

[Link] – JavaScript® Notes for Professionals 401 [Link] – JavaScript® Notes for Professionals 402
Chapter 86: Tilde ~ let c = ~~0;
let d = ~~1;
let e = ~~2;
// c is now 0
// d is now 1
// e is now 2

The ~ operator looks at the binary representation of the values of the expression and does a bitwise negation
operation on it. g2(n) will essentially round positive numbers down and negative numbers up.

Any digit that is a 1 in the expression becomes a 0 in the result. Any digit that is a 0 in the expression becomes a 1 let a = ~~-2.5; // a is now -2
let b = ~~-1.5; // b is now -1
in the result.
let c = ~~0.5; // c is now 0
let d = ~~1.5; // d is now 1
Section 86.1: ~ Integer let e = ~~2.5; // e is now 2

The following example illustrates use of the bitwise NOT (~) operator on integer numbers.
Section 86.3: Converting Non-numeric values to Numbers
let number = 3;
~~ Could be used on non-numeric values. A numeric expression will be first converted to a number and then
let complement = ~number;
performed bitwise NOT operation on it.
Result of the complement number equals to -4;
If expression cannot be converted to numeric value, it will convert to 0.
Expression Binary value Decimal value
true and false bool values are exceptions, where true is presented as numeric value 1 and false as 0
3 00000000 00000000 00000000 00000011 3
~3 11111111 11111111 11111111 11111100 -4
let a = ~~"-2"; // a is now -2
let b = ~~"1"; // b is now -1
To simplify this, we can think of it as function f(n) = -(n+1). let c = ~~"0"; // c is now 0
let d = ~~"true"; // d is now 0
let a = ~-2; // a is now 1 let e = ~~"false"; // e is now 0
let b = ~-1; // b is now 0 let f = ~~true; // f is now 1
let c = ~0; // c is now -1 let g = ~~false; // g is now 0
let d = ~1; // d is now -2 let h = ~~""; // h is now 0
let e = ~2; // e is now -3

Section 86.4: Shorthands


Section 86.2: ~~ Operator
We can use ~ as a shorthand in some everyday scenarios.
Double Tilde ~~ will perform bitwise NOT operation twice.
We know that ~ converts -1 to 0, so we can use it with indexOf on array.
The following example illustrates use of the bitwise NOT (~~) operator on decimal numbers.
indexOf
To keep the example simple, decimal number 3.5 will be used, cause of it's simple representation in binary format. let items = ['foo', 'bar', 'baz'];
let el = 'a';
let number = 3.5;
if ([Link]('a') !== -1) {}
let complement = ~number;

or
Result of the complement number equals to -4;
if ([Link]('a') >= 0) {}
Expression Binary value Decimal value
can be re-written as
3 00000000 00000000 00000000 00000011 3
if (~[Link]('a')) {}
~~3 00000000 00000000 00000000 00000011 3
3.5 00000000 00000011.1 3.5
~~3.5 00000000 00000011 3
Section 86.5: ~ Decimal
The following example illustrates use of the bitwise NOT (~) operator on decimal numbers.
To simplify this, we can think of it as functions f2(n) = -(-(n+1) + 1) and g2(n) = -(-(integer(n)+1) + 1).
To keep the example simple, decimal number 3.5 will be used, cause of it's simple representation in binary format.
f2(n) will leave the integer number as it is.

let number = 3.5;


let a = ~~-2; // a is now -2
let complement = ~number;
let b = ~~-1; // b is now -1

[Link] – JavaScript® Notes for Professionals 403 [Link] – JavaScript® Notes for Professionals 404
Result of the complement number equals to -4;
Chapter 87: Using JavaScript to get/set
Expression
3.5
Binary value Decimal value
00000000 00000010.1 3.5
CSS custom variables
~3.5 11111111 11111100 -4
Section 87.1: How to get and set CSS variable property values
To simplify this, we can think of it as function f(n) = -(integer(n)+1).
To get a value use the .getPropertyValue() method
let a = ~-2.5; // a is now 1
let b = ~-1.5; // b is now 0 [Link]("--var")
let c = ~0.5; // c is now -1
let d = ~1.5; // c is now -2 To set a value use the .setProperty() method.
let e = ~2.5; // c is now -3
[Link]("--var", "NEW_VALUE")

[Link] – JavaScript® Notes for Professionals 405 [Link] – JavaScript® Notes for Professionals 406
Chapter 88: Selection API Chapter 89: File API, Blobs and FileReaders
Parameter Details Property/Method Description
If the node is a Text node, it is the number of characters from the beginning of startNode to where the error A error that occurred while reading the file.
startOffset range begins. Otherwise, it is the number of child nodes between the beginning of startNode to where readyState Contains the current state of the FileReader.
the range begins.
result Contains the file contents.
If the node is a Text node, it is the number of characters from the beginning of startNode to where the
endOffset range ends. Otherwise, it is the number of child nodes between the beginning of startNode to where onabort Triggered when the operation is aborted.
the range ends. onerror Triggered when an error is encountered.
onload Triggered when the file has loaded.
Section 88.1: Get the text of the selection onloadstart Triggered when the file loading operation has started.
onloadend Triggered when the file loading operation has ended.
let sel = [Link]();
onprogress Triggered whilst reading a Blob.
let text = [Link]();
[Link](text); // logs what the user selected abort() Aborts the current operation.
readAsArrayBuffer(blob) Starts reading the file as an ArrayBuffer.
Alternatively, since the toString member function is called automatically by some functions when converting the readAsDataURL(blob) Starts reading the file as a data url/uri.
object to a string, you don't always have to call it yourself. Starts reading the file as a text file. Not able to read binary files. Use
readAsText(blob[, encoding])
readAsArrayBuffer instead.
[Link]([Link]());

Section 89.1: Read file as string


Section 88.2: Deselect everything that is selected
Make sure to have a file input on your page:
let sel = [Link]();
[Link](); <input type="file" id="upload">

Section 88.3: Select the contents of an element Then in JavaScript:

let sel = [Link](); [Link]('upload').addEventListener('change', readFileAsString)


function readFileAsString() {
let myNode = [Link]('element-to-select'); var files = [Link];
if ([Link] === 0) {
let range = [Link](); [Link]('No file is selected');
[Link](myNode); return;
}
[Link](range);
var reader = new FileReader();
[Link] = function(event) {
It may be necessary to first remove all the ranges of the previous selection, as most browsers don't support [Link]('File content:', [Link]);
multiple ranges. };
[Link](files[0]);
}

Section 89.2: Read file as dataURL


Reading the contents of a file within a web application can be accomplished by utilizing the HTML5 File API. First,
add an input with type="file" in your HTML:

<input type="file" id="upload">

Next, we're going to add a change listener on the file-input. This examples defines the listener via JavaScript, but it
could also be added as attribute on the input element. This listener gets triggered every time a new file has been
selected. Within this callback, we can read the file that was selected and perform further actions (like creating an
image with the contents of the selected file):

[Link] – JavaScript® Notes for Professionals 407 [Link] – JavaScript® Notes for Professionals 408
[Link]('upload').addEventListener('change', showImage); function getFile(event) {
var files = [Link]
function showImage(evt) { , file = files[0];
var files = [Link];
[Link]('Name of the file', [Link]);
if ([Link] === 0) { [Link]('Size of the file', [Link]);
[Link]('No files selected'); }
return;
} You can also get easily the following attributes: lastModified (Timestamp), lastModifiedDate (Date), and type (File
Type)
var reader = new FileReader();
[Link] = function(event) {
var img = new Image(); Section 89.5: Selecting multiple files and restricting file types
[Link] = function() {
[Link](img); The HTML5 file API allows you to restrict which kind of files are accepted by simply setting the accept attribute on a
}; file input, e.g.:
[Link] = [Link];
};
<input type="file" accept="image/jpeg">
[Link](files[0]);
}
Specifying multiple MIME types separated by a comma (e.g. image/jpeg,image/png) or using wildcards (e.g.
image/* for allowing all types of images) give you a quick and powerful way to restrict the type of files you want to
Section 89.3: Slice a file select. Here's an example for allowing any image or video:

The [Link]() method is used to create a new Blob object containing the data in the specified range of bytes of
<input type="file" accept="image/*,video*">
the source Blob. This method is usable with File instances too, since File extends Blob.

Here we slice a file in a specific amount of blobs. This is useful especially in cases where you need to process files By default, the file input lets the user select a single file. If you want to enable multiple file selection, simply add the
that are too large to read in memory all in once. We can then read the chunks one by one using FileReader. multiple attribute:

/** <input type="file" multiple>


* @param {File|Blob} - file to slice
* @param {Number} - chunksAmount You can then read all the selected files via the file input's files array. See read file as dataUrl
* @return {Array} - an array of Blobs
**/
function sliceFile(file, chunksAmount) { Section 89.6: Client side csv download using Blob
var byteIndex = 0;
var chunks = []; function downloadCsv() {
var blob = new Blob([csvString]);
for (var i = 0; i < chunksAmount; i += 1) { if ([Link]){
var byteEnd = [Link](([Link] / chunksAmount) * (i + 1)); [Link](blob, "[Link]");
[Link]([Link](byteIndex, byteEnd)); }
byteIndex += (byteEnd - byteIndex); else {
} var a = [Link]("a");

return chunks; [Link] = [Link](blob, {


} type: "text/plain"
});
[Link] = "[Link]";
Section 89.4: Get the properties of the file [Link](a);
[Link]();
If you want to get the properties of the file (like the name or the size) you can do it before using the File Reader. If [Link](a);
we have the following html piece of code: }
}
var string = "a1,a2,a3";
<input type="file" id="newFile">
downloadCSV(string);

You can access the properties directly like this:


Source reference ; [Link]

[Link]('newFile').addEventListener('change', getFile);

[Link] – JavaScript® Notes for Professionals 409 [Link] – JavaScript® Notes for Professionals 410
Chapter 90: Notifications API let notification = new Notification(title, options);
setTimeout(() => {
[Link]()
Section 90.1: Requesting Permission to send notifications }, 4000);

We use [Link] to ask the user if he/she wants to receive notifications from our website. The above code will spawn a notification and close it after 4 seconds.

[Link](function() { Section 90.4: Notification events


if ([Link] === 'granted') {
// user approved. The Notification API specifications support 2 events that can be fired by a Notification.
// use of new Notification(...) syntax will now be successful
} else if ([Link] === 'denied') {
1. The click event.
// user denied.
} else { // [Link] === 'default'
This event will run when you click on the notification body (excluding the closing X and the Notifications
// user didn’t make a decision.
configuration button).
// You can’t send notifications until they grant permission.
}
}); Example:

[Link] = function(event) {
Since Firefox 47 The .requestPermission method can also return a promise when handling the user's decision for
[Link]("you click me and this is my event object: ", event);
granting permission }

[Link]().then(function(permission) { 2. The error event


if (!('permission' in Notification)) {
[Link] = permission; The notification will fire this event whenever something wrong will happen, like being unable to display
}
// you got permission !
[Link] = function(event) {
}, function(rejection) {
[Link]("There was an error: ", event);
// handle rejection here.
}
}
);

Section 90.2: Sending Notifications


After the user has approved a request for permission to send notifications, we can send a simple notification that
says Hello to the user:

new Notification('Hello', { body: 'Hello, world!', icon: 'url to an .ico image' });

This will send a notification like this:

Hello

Hello, world!

Section 90.3: Closing a notification


You can close a notification by using the .close() method.

let notification = new Notification(title, options);


// do some work, then close the notification
[Link]()

You can utilize the setTimeout function to auto-close the notification sometime in the future.

[Link] – JavaScript® Notes for Professionals 411 [Link] – JavaScript® Notes for Professionals 412
Chapter 91: Vibration API Chapter 92: Battery Status API
Modern mobile devices include hardware for vibrations. The Vibration API offers Web apps the ability to access this Section 92.1: Battery Events
hardware, if it exists, and does nothing if the device doesn't support it.
// Get the battery API
Section 91.1: Single vibration [Link]().then(function(battery) {
[Link]('chargingchange', function(){
[Link]( 'New charging state: ', [Link] );
Vibrate the device for 100ms:
});

[Link](100); [Link]('levelchange', function(){


[Link]( 'New battery level: ', [Link] * 100 + "%" );
or });

[Link]([100]); [Link]('chargingtimechange', function(){


[Link]( 'New time left until full: ', [Link], " seconds" );
});
Section 91.2: Check for support
[Link]('dischargingtimechange', function(){
Check if browser supports vibrations [Link]( 'New time left until empty: ', [Link], " seconds" );
});
});
if ('vibrate' in [Link])
// browser has support for vibrations
else
// no support
Section 92.2: Getting current battery level
// Get the battery API
Section 91.3: Vibration patterns [Link]().then(function(battery) {
// Battery level is between 0 and 1, so we multiply it by 100 to get in percents
[Link]("Battery level: " + [Link] * 100 + "%");
An array of values describes periods of time in which the device is vibrating and not vibrating.
});

[Link]([200, 100, 200]);


Section 92.3: Is battery charging?
// Get the battery API
[Link]().then(function(battery) {
if ([Link]) {
[Link]("Battery is charging");
} else {
[Link]("Battery is discharging");
}
});

Section 92.4: Get time left until battery is empty


// Get the battery API
[Link]().then(function(battery) {
[Link]( "Battery will drain in ", [Link], " seconds" );
});

Section 92.5: Get time left until battery is fully charged


// Get the battery API
[Link]().then(function(battery) {
[Link]( "Battery will get fully charged in ", [Link], " seconds" );
});

[Link] – JavaScript® Notes for Professionals 413 [Link] – JavaScript® Notes for Professionals 414
Chapter 93: Fluent API list(text) {
const list = new List(text, []);
[Link](list);
[Link] = list;
JavaScript is great for designing fluent API - a consumer-oriented API with focus on developer experience. Combine
return this;
with language dynamic features for optimal results. }

Section 93.1: Fluent API capturing construction of HTML addParagraph(text) {

articles with JS const paragraph = new Item(text, 'p');


[Link](paragraph);
[Link] = paragraph;
Version ≥ 6
return this;
class Item { }
constructor(text, type) {
[Link] = text; addListItem(text) {
[Link] = false; const listItem = new Item(text, 'li');
[Link] = type; [Link](listItem);
} [Link] = listItem;
return this;
toHtml() { }
return `<${[Link]}>${[Link] ? '<em>' : ''}${[Link]}${[Link] ? '</em>' :
''}</${[Link]}>`; withEmphasis() {
} [Link] = true;
} return this;
}
class Section {
constructor(header, paragraphs) { toHtml() {
[Link] = header; return `<article><h1>${[Link]}</h1>${[Link](s =>
[Link] = paragraphs; [Link]()).join('')}${[Link](l => [Link]()).join('')}</article>`;
} }
}
toHtml() {
return `<section><h2>${[Link]}</h2>${[Link](p => [Link] = topic => new Article(topic);
[Link]()).join('')}</section>`;
}
} This allows the consumer of the API to have a nice-looking article construction, almost a DSL for this purpose, using
plain JS:
class List {
constructor(text, items) { Version ≥ 6
[Link] = text; const articles = [
[Link] = items; [Link]('Artificial Intelligence - Overview')
} .section('What is Artificial Intelligence?')
.addParagraph('Something something')
toHtml() { .addParagraph('Lorem ipsum')
return `<ol><h2>${[Link]}</h2>${[Link](i => [Link]()).join('')}</ol>`; .withEmphasis()
} .section('Philosophy of AI')
} .addParagraph('Something about AI philosophy')
.addParagraph('Conclusion'),
class Article {
constructor(topic) { [Link]('JavaScript')
[Link] = topic; .list('JavaScript is one of the 3 languages all web developers must learn:')
[Link] = []; .addListItem('HTML to define the content of web pages')
[Link] = []; .addListItem('CSS to specify the layout of web pages')
} .addListItem(' JavaScript to program the behavior of web pages')
];
section(text) {
const section = new Section(text, []); [Link]('content').innerHTML = [Link](a => [Link]()).join('\n');
[Link](section);
[Link] = section;
return this;
}

[Link] – JavaScript® Notes for Professionals 415 [Link] – JavaScript® Notes for Professionals 416
Chapter 94: Web Cryptography API Section 94.3: Generating RSA key pair and converting to PEM
format
Section 94.1: Creating digests (e.g. SHA-256) In this example you will learn how to generate RSA-OAEP key pair and how to convert private key from this key pair
to base64 so you can use it with OpenSSL etc. Please note that this process can also be used for public key you just
// Convert string to ArrayBuffer. This step is only necessary if you wish to hash a string, not if have to use prefix and suffix below:
you already got an ArrayBuffer such as an Uint8Array.
var input = new TextEncoder('utf-8').encode('Hello world!');
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
// Calculate the SHA-256 digest
[Link]('SHA-256', input)
// Wait for completion NOTE: This example is fully tested in these browsers: Chrome, Firefox, Opera, Vivaldi
.then(function(digest) {
// digest is an ArrayBuffer. There are multiple ways to proceed. function arrayBufferToBase64(arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
// If you want to display the digest as a hexadecimal string, this will work: var byteString = '';
var view = new DataView(digest); for(var i=0; i < [Link]; i++) {
var hexstr = ''; byteString += [Link](byteArray[i]);
for(var i = 0; i < [Link]; i++) { }
var b = view.getUint8(i); var b64 = [Link](byteString);
hexstr += '0123456789abcdef'[(b & 0xf0) >> 4];
hexstr += '0123456789abcdef'[(b & 0x0f)]; return b64;
} }
[Link](hexstr);
function addNewLines(str) {
// Otherwise, you can simply create an Uint8Array from the buffer: var finalString = '';
var digestAsArray = new Uint8Array(digest); while([Link] > 0) {
[Link](digestAsArray); finalString += [Link](0, 64) + '\n';
}) str = [Link](64);
// Catch errors }
.catch(function(err) {
[Link](err); return finalString;
}); }

The current draft suggests to provide at least SHA-1, SHA-256, SHA-384 and SHA-512, but this is no strict requirement function toPem(privateKey) {
var b64 = addNewLines(arrayBufferToBase64(privateKey));
and subject to change. However, the SHA family can still be considered a good choice as it will likely be supported in
var pem = "-----BEGIN PRIVATE KEY-----\n" + b64 + "-----END PRIVATE KEY-----";
all major browsers.
return pem;
Section 94.2: Cryptographically random data }

// Let's generate the key pair first


// Create an array with a fixed size and type.
[Link](
var array = new Uint8Array(5);
{
name: "RSA-OAEP",
// Generate cryptographically random values
modulusLength: 2048, // can be 1024, 2048 or 4096
[Link](array);
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"} // or SHA-512
// Print the array to the console
},
[Link](array);
true,
["encrypt", "decrypt"]
[Link](array) can be used with instances of the following classes (described further in Binary ).then(function(keyPair) {
Data) and will generate values from the given ranges (both ends inclusive): /* now when the key pair is generated we are going
to export it from the keypair object in pkcs8
Int8Array: -27 to 27-1 */
[Link](
Uint8Array: 0 to 28-1
"pkcs8",
Int16Array: -215 to 215-1 [Link]
Uint16Array: 0 to 216-1 ).then(function(exportedPrivateKey) {
Int32Array: -231 to 231-1 // converting exported private key to PEM format
Uint32Array: 0 to 231-1 var pem = toPem(exportedPrivateKey);

[Link] – JavaScript® Notes for Professionals 417 [Link] – JavaScript® Notes for Professionals 418
[Link](pem); And now you're done! You can use your imported key in WebCrypto API.
}).catch(function(err) {
[Link](err);
});
});

That's it! Now you have a fully working and compatible RSA-OAEP Private Key in PEM format which you can use
wherever you want. Enjoy!

Section 94.4: Converting PEM key pair to CryptoKey


So, have you ever wondered how to use your PEM RSA key pair that was generated by OpenSSL in Web
Cryptography API? If the answers is yes. Great! You are going to find out.

NOTE: This process can also be used for public key, you only need to change prefix and suffix to:

-----BEGIN PUBLIC KEY-----


-----END PUBLIC KEY-----

This example assumes that you have your RSA key pair generated in PEM.

function removeLines(str) {
return [Link]("\n", "");
}

function base64ToArrayBuffer(b64) {
var byteString = [Link](b64);
var byteArray = new Uint8Array([Link]);
for(var i=0; i < [Link]; i++) {
byteArray[i] = [Link](i);
}

return byteArray;
}

function pemToArrayBuffer(pem) {
var b64Lines = removeLines(pem);
var b64Prefix = [Link]('-----BEGIN PRIVATE KEY-----', '');
var b64Final = [Link]('-----END PRIVATE KEY-----', '');

return base64ToArrayBuffer(b64Final);
}

[Link](
"pkcs8",
pemToArrayBuffer(yourprivatekey),
{
name: "RSA-OAEP",
hash: {name: "SHA-256"} // or SHA-512
},
true,
["decrypt"]
).then(function(importedPrivateKey) {
[Link](importedPrivateKey);
}).catch(function(err) {
[Link](err);
});

[Link] – JavaScript® Notes for Professionals 419 [Link] – JavaScript® Notes for Professionals 420
Chapter 95: Security issues When I search for cute puppies, nothing happens!

This is a collection of common JavaScript security issues, like XSS and eval injection. This collection also contains Than Alice successfully gets Bob to run her script while Bob is logged on to his account.
how to mitigate these security issues.
Mitigation:

Section 95.1: Reflected Cross-site scripting (XSS) 1. Escape all angle brackets in searches before returning the search term when no results are found.
2. Don't return the search term when no results are found.
Let's say Joe owns a website that allows you to log on, view puppy videos, and save them to your account. 3. Add a Content Security Policy that refuses to load active content from other domains

Whenever a user searches on that website, they are redirected to [Link]


Section 95.2: Persistent Cross-site scripting (XSS)
If a user's search doesn't match anything, than they see a message along the lines of:
Let's say that Bob owns a social website that allows users to personalize their profiles.

Your search (brown puppies), didn't match anything. Try again. Alice goes to Bob's website, creates an account, and goes to her profile settings. She sets her profile description to
I'm actually too lazy to write something here.

On the backend, that message is displayed like this: When her friends view her profile, this code gets run on the server:

if(!searchResults){ if([Link]){
webPage += "<div>Your search (<b>" + searchQuery + "</b>), didn't match anything. Try again."; page += "<div>" + [Link] + "</div>";
} }else{
page += "<div>This person doesn't have a profile description.</div>";
}
However, when Alice searches for <h1>headings</h1>, she gets this back:

Resulting in this HTML:


Your search (headings
) didn't match anything. Try again. <div>I'm actually too lazy to write something here.</div>

Than Alice sets her profile description to <b>I like HTML</b>. When she visits her profile, instead of seeing
Raw HTML:

Your search (<b><h1>headings</h1></b>) didn't match anything. Try again. <b>I like HTML</b>

Than Alice searches for <script>alert(1)</script>, she sees:


she sees

Your search (), didn't match anything. Try again.


I like HTML

And:
Then Alice sets her profile to

<script src = "[Link] actually too lazy to write something


here.

Whenever someone visits her profile, they get Alice's script run on Bob's website while logged on as their account.

Mitigation

1. Escape angle brackets in profile descriptions, etc.


Than Alice searches for <script src = "[Link] cute puppies, and 2. Store profile descriptions in a plain text file that is then fetched with a script that adds the description via
copies the link in her address bar, and then emails Bob: .innerText
3. Add a Content Security Policy that refuses to load active content from other domains

Bob,

[Link] – JavaScript® Notes for Professionals 421 [Link] – JavaScript® Notes for Professionals 422
Section 95.3: Persistent Cross-site scripting from JavaScript could do:
string literals 1. Remove itself from the DOM so that it can't be traced
Let's say that Bob owns a site that lets you post public messages. 2. Steal users' session cookies and enable the script author to log in as and impersonate them
3. Show a fake "Your session has expired. Please log in again." message that sends the user's password to the
The messages are loaded by a script that looks like this: script author.
4. Register a malicious service worker that runs a malicious script on every page visit to that website.
addMessage("Message 1"); 5. Put up a fake paywall demanding that users pay money to access the site that actually goes to the script
addMessage("Message 2");
author.
addMessage("Message 3");
addMessage("Message 4");
addMessage("Message 5"); Please, don't think that XSS won't harm your website and its visitors.
addMessage("Message 6");
Section 95.5: Evaled JSON injection
The addMessage function adds a posted message to the DOM. However, in an effort to avoid XSS, any HTML in
messages posted is escaped. Let's say that whenever someone visits a profile page in Bob's website, the following URL is fetched:

The script is generated on the server like this: [Link]

for(var i = 0; i < [Link]; i++){ With a response like this:


script += "addMessage(\"" + messages[i] + "\");";
} {
"name": "Bob",
So alice posts a message that says: My mom said: "Life is good. Pie makes it better. ". Than when she "description": "Likes pie & security holes."
previews the message, instead of seeing her message she sees an error in the console: }

Uncaught SyntaxError: missing ) after argument list Than that data is parsed & inserted:

Why? Because the generated script looks like this: var data = eval("(" + resp + ")");
[Link]("#name").innerText = [Link];
[Link]("#description").innerText = [Link];
addMessage("My mom said: "Life is good. Pie makes it better. "");

Seems good, right? Wrong.


That's a syntax error. Than Alice posts:
What if someone's description is Likes XSS."});alert(1);({"name":"Alice","description":"Likes XSS.?
I like pie ");fetch("[Link]
Seems weird, but if poorly done, the response will be:

Then the generated script looks like:


{
"name": "Alice",
addMessage("I like pie ");fetch("[Link] "description": "Likes pie & security holes."});alert(1);({"name":"Alice","description":"Likes
XSS."
That adds the message I like pie, but it also downloads and runs [Link] whenever }

someone visits Bob's site.


And this will be evaled:
Mitigation:
({
1. Pass the message posted into [Link]() "name": "Alice",
2. Instead of dynamically building a script, build a plain text file containing all the messages that is later fetched "description": "Likes pie & security holes."});alert(1);({"name":"Alice","description":"Likes
XSS."
by the script
})
3. Add a Content Security Policy that refuses to load active content from other domains

If you don't think that's a problem, paste that in your console and see what happens.
Section 95.4: Why scripts from other people can harm your
website and its visitors Mitigation

If you don't think that malicious scripts can harm your site, you are wrong. Here is a list of what a malicious script Use [Link] instead of eval to get JSON. In general, don't use eval, and definitely don't use eval with

[Link] – JavaScript® Notes for Professionals 423 [Link] – JavaScript® Notes for Professionals 424
something a user could control. Eval creates a new execution context, creating a performance hit.
Chapter 96: Same Origin Policy & Cross-
Properly escape " and \ in user data before putting it in JSON. If you just escape the ", than this will happen:
Origin Communication
Hello! \"});alert(1);({
Same-Origin policy is used by web browsers to prevent scripts to be able to access remote content if the remote
address has not the same origin of the script. This prevents malicious scripts from performing requests to other
Will be converted to:
websites to obtain sensitive data.
"Hello! \\"});alert(1);({"
The origin of two addresses is considered the same if both URLs have the same protocol, hostname and port.

Oops. Remember to escape both the \ and ", or just use [Link].
Section 96.1: Safe cross-origin communication with messages
The [Link]() method together with its relative event handler [Link] can be safely used
to enable cross-origin communication.

The postMessage() method of the target window can be called to send a message to another window, which will be
able to intercept it with its onmessage event handler, elaborate it, and, if necessary, send a response back to the
sender window using postMessage() again.

Example of Window communicating with a children frame

Content of [Link]

<!-- ... -->


<iframe id="frame-id" src="[Link]
<script src="main_site_script.js"></script>
<!-- ... -->

Content of [Link]

<!-- ... -->


<script src="other_site_script.js"></src>
<!-- ... -->

Content of main_site_script.js:

// Get the <iframe>'s window


var frameWindow = [Link]('frame-id').contentWindow;

// Add a listener for a response


[Link]('message', function(evt) {

// IMPORTANT: Check the origin of the data!


if ([Link]('[Link] == 0) {

// Check the response


[Link]([Link]);
/* ... */
}
});

// Send a message to the frame's window


[Link](/* any obj or var */, '*');

Content of other_site_script.js:

[Link] – JavaScript® Notes for Professionals 425 [Link] – JavaScript® Notes for Professionals 426
[Link]('message', function(evt) { myfunc({"example_field":true})

// IMPORTANT: Check the origin of the data!


The function always has to be defined first, otherwise it won't be defined when the external script loads.
if ([Link]('[Link] == 0) {

// Read and elaborate the received data


[Link]([Link]);
/* ... */

// Send a response back to the main window


[Link](/* any obj or var */, '*');
}
});

Section 96.2: Ways to circumvent Same-Origin Policy


As far as client-side JavaScript engines are concerned (those running inside a browser), there is no straightforward
solution available for requesting content from sources other than the current domain. (By the way, this limitation
does not exist in JavaScript-server tools such as Node JS.)

However, it is (in some situations) indeed possible to retrieve data from other sources using the following methods.
Please do note that some of them may present hacks or workarounds instead of solutions production system
should rely on.

Method 1: CORS

Most public APIs today allow developers to send data bidirectionally between client and server by enabling a
feature called CORS (Cross-Origin Resource Sharing). The browser will check if a certain HTTP header (Access-
Control-Allow-Origin) is set and that the requesting site's domain is listed in the header's value. If it is, then the
browser will allow establishing AJAX connections.

However, because developers cannot change other servers' response headers, this method can't always be relied
on.

Method 2: JSONP

JSON with Padding is commonly blamed to be a workaround. It is not the most straightforward method, but it still
gets the job done. This method takes advantage of the fact that script files can be loaded from any domain. Still, it is
crucial to mention that requesting JavaScript code from external sources is always a potential security risk and this
should generally be avoided if there's a better solution available.

The data requested using JSONP is typically JSON, which happens to fit the syntax used for object definition in
JavaScript, making this method of transport very simple. A common way to let websites use the external data
obtained via JSONP is to wrap it inside a callback function, which is set via a GET parameter in the URL. Once the
external script file loads, the function will be called with the data as its first parameter.

<script>
function myfunc(obj){
[Link](obj.example_field);
}
</script>
<script src="[Link]

The contents of [Link] might look like this:

[Link] – JavaScript® Notes for Professionals 427 [Link] – JavaScript® Notes for Professionals 428
Chapter 97: Error Handling Caught error: Invalid something

Section 97.1: Error objects Section 97.3: Error types


There are six specific core error constructors in JavaScript:
Runtime errors in JavaScript are instances of the Error object. The Error object can also be used as-is, or as the
base for user-defined exceptions. It's possible to throw any type of value - for example, strings - but you're strongly EvalError - creates an instance representing an error that occurs regarding the global function eval().
encouraged to use Error or one of its derivatives to ensure that debugging information -- such as stack traces -- is
correctly preserved. InternalError - creates an instance representing an error that occurs when an internal error in the
JavaScript engine is thrown. E.g. "too much recursion". (Supported only by Mozilla Firefox)
The first parameter to the Error constructor is the human-readable error message. You should try to always specify
RangeError - creates an instance representing an error that occurs when a numeric variable or parameter is
a useful error message of what went wrong, even if additional information can be found elsewhere.
outside of its valid range.
try { ReferenceError - creates an instance representing an error that occurs when dereferencing an invalid
throw new Error('Useful message');
reference.
} catch (error) {
[Link]('Something went wrong! ' + [Link]); SyntaxError - creates an instance representing a syntax error that occurs while parsing code in eval().
}
TypeError - creates an instance representing an error that occurs when a variable or parameter is not of a

Section 97.2: Interaction with Promises valid type.

URIError - creates an instance representing an error that occurs when encodeURI() or decodeURI() are
Version ≥ 6
passed invalid parameters.
Exceptions are to synchronous code what rejections are to promise-based asynchronous code. If an exception is
thrown in a promise handler, its error will be automatically caught and used to reject the promise instead. If you are implementing error handling mechanism you can check which kind of error you are catching from code.

[Link](5) try {
.then(result => { throw new TypeError();
throw new Error("I don't like five"); }
}) catch (e){
.then(result => { if(e instanceof Error){
[Link]("Promise resolved: " + result); [Link]('instance of general Error constructor');
}) }
.catch(error => {
[Link]("Promise rejected: " + error); if(e instanceof TypeError) {
}); [Link]('type error');
}
}

Promise rejected: Error: I don't like five In such case e will be an instance of TypeError. All error types extend the base constructor Error, therefore it's also
Version > 7 an instance of Error.

The async functions proposal—expected to be part of ECMAScript 2017—extends this in the opposite direction. If Keeping that in mind shows us that checking e to be an instance of Error is useless in most cases.
you await a rejected promise, its error is raised as an exception:
Section 97.4: Order of operations plus advanced thoughts
async function main() {
try { Without a try catch block, undefined functions will throw errors and stop execution:
await [Link](new Error("Invalid something"));
} catch (error) {
undefinedFunction("This will not get executed");
[Link]("Caught error: " + error);
[Link]("I will never run because of the uncaught error!");
}
}
main(); Will throw an error and not run the second line:

// Uncaught ReferenceError: undefinedFunction is not defined

You need a try catch block, similar to other languages, to ensure you catch that error so code can continue to

[Link] – JavaScript® Notes for Professionals 429 [Link] – JavaScript® Notes for Professionals 430
execute: Also, you shouldn't wrap every variable and function in a try/catch block, because these are simple examples that
will only ever occur once until you fix them. However, for objects, functions and other variables that you know exist,
try { but you don't know whether their properties or sub-processes or side-effects will exist, or you expect some error
undefinedFunction("This will not get executed");
states in some circumstances, you should abstract your error handling in some sort of manner. Here is a very basic
} catch(error) {
[Link]("An error occurred!", error);
example and implementation.
} finally {
[Link]("The code-block has finished"); Without a protected way to call untrusted or exception throwing methods:
}
[Link]("I will run because we caught the error!"); function foo(a, b, c) {
[Link](a, b, c);
throw new Error("custom error!");
Now, we've caught the error and can be sure that our code is going to execute
}
try {
// An error occurred! ReferenceError: undefinedFunction is not defined(…) foo(1, 2, 3);
// The code-block has finished } catch(e) {
// I will run because we caught the error! try {
foo(4, 5, 6);
What if an error occurs in our catch block!? } catch(e2) {
[Link]("We had to nest because there's currently no other way...");
}
try {
[Link](e);
undefinedFunction("This will not get executed");
}
} catch(error) {
// 1 2 3
otherUndefinedFunction("Uh oh... ");
// 4 5 6
[Link]("An error occurred!", error);
// We had to nest because there's currently no other way...
} finally {
[Link]("The code-block has finished"); // Error: custom error!(…)
}
[Link]("I won't run because of the uncaught error in the catch block!"); And with protection:

We won't process the rest of our catch block, and execution will halt except for the finally block. function foo(a, b, c) {
[Link](a, b, c);
// The code-block has finished throw new Error("custom error!");
}
// Uncaught ReferenceError: otherUndefinedFunction is not defined(…)
function protectedFunction(fn, ...args) {
try {
You could always nest your try catch blocks.. but you shouldn't because that will get extremely messy.. [Link](this, args);
} catch (e) {
try { [Link]("caught error: " + [Link] + " -> " + [Link]);
undefinedFunction("This will not get executed"); }
} catch(error) { }
try {
otherUndefinedFunction("Uh oh... "); protectedFunction(foo, 1, 2, 3);
} catch(error2) { protectedFunction(foo, 4, 5, 6);
[Link]("Too much nesting is bad for my heart and soul...");
} // 1 2 3
[Link]("An error occurred!", error); // caught error: Error -> custom error!
} finally { // 4 5 6
[Link]("The code-block has finished"); // caught error: Error -> custom error!
}
[Link]("I will run because we caught the error!"); We catch errors and still process all the expected code, though with a somewhat different syntax. Either way will
work, but as you build more advanced applications you will want to start thinking about ways to abstract your error
Will catch all errors from the previous example and log the following: handling.

//Too much nesting is bad for my heart and soul...


//An error occurred! ReferenceError: undefinedFunction is not defined(…)
//The code-block has finished
//I will run because we caught the error!

So, how can we catch all errors!? For undefined variables and functions: you can't.

[Link] – JavaScript® Notes for Professionals 431 [Link] – JavaScript® Notes for Professionals 432
Chapter 98: Global error handling in new Image().src = '/exampleErrorReporting?stack=' + encodeURIComponent(stack);

browsers // window.DEBUG_ENVIRONMENT a configurable property that may be set to true somewhere else for
debugging and testing purposes.
if (window.DEBUG_ENVIRONMENT) {
Parameter Details alert('Client-side script failed: ' + stack);
}
Some browsers will call the event handler with just one argument, an Event object. However,
}
eventOrMessage other browsers, especially the older ones and older mobile ones will supply a String message as
a first argument.
If a handler is called with more than 1 argument, the second argument usually is an URL of a
url
JavaScript file that is the source of the problem.
If a handler is called with more than 1 argument, the third argument is a line number inside the
lineNumber
JavaScript source file.
If a handler is called with more than 1 argument, the fourth argument is the column number
colNumber
inside the JavaScript source file.
If a handler is called with more than 1 argument, the fifth argument is sometimes an Error object
error
describing the problem.

Section 98.1: Handling [Link] to report all errors


back to the server-side
The following example listens to [Link] event and uses an image beacon technique to send the
information through the GET parameters of an URL.

var hasLoggedOnce = false;

// Some browsers (at least Firefox) don't report line and column numbers
// when event is handled through [Link]('error', fn). That's why
// a more reliable approach is to set an event listener via direct assignment.
[Link] = function (eventOrMessage, url, lineNumber, colNumber, error) {
if (hasLoggedOnce || !eventOrMessage) {
// It does not make sense to report an error if:
// 1. another one has already been reported -- the page has an invalid state and may produce
way too many errors.
// 2. the provided information does not make sense (!eventOrMessage -- the browser didn't
supply information for some reason.)
return;
}
hasLoggedOnce = true;
if (typeof eventOrMessage !== 'string') {
error = [Link];
url = [Link] || [Link];
lineNumber = [Link] || [Link];
colNumber = [Link] || [Link];
eventOrMessage = [Link] || [Link] || [Link] ||
[Link];
}
if (error && [Link]) {
eventOrMessage = [eventOrMessage, '; Stack: ', [Link], '.'].join('');
}
var jsFile = (/[^/]+\.js/[Link](url || '') || [])[0] || 'inlineScriptOrDynamicEvalCode',
stack = [eventOrMessage, ' Occurred in ', jsFile, ':', lineNumber || '?', ':', colNumber ||
'?'].join('');

// shortening the message a bit so that it is more likely to fit into browser's URL length limit
(which is 2,083 in some browsers)
stack = [Link](/https?\:\/\/[^/]+/gi, '');
// calling the server-side handler which should probably register the error in a database or a
log file

[Link] – JavaScript® Notes for Professionals 433 [Link] – JavaScript® Notes for Professionals 434
Chapter 99: Debugging 1. Press F12 to open Developer Tools
2. Switch to the Sources tab (Chrome) or Debugger tab (Firefox)
3. Press Ctrl + P and type the name of your JavaScript file
Section 99.1: Interactive interpreter variables 4. Press Enter to open it.

Note that these only work in the developer tools of certain browsers. Internet Explorer or Edge

$_ gives you the value of whatever expression was evaluated last. 1. Press F12 to open Developer Tools
2. Switch to the Debugger tab.
"foo" // "foo" 3. Use the folder icon near the upper-left corner of the window to open a file-selection pane; you can find your
$_ // "foo" JavaScript file there.

Safari
$0 refers to the DOM element currently selected in the Inspector. So if <div id="foo"> is highlighted:

1. Press Command + Option + C to open Developer Tools


$0 // <div id="foo">
2. Switch to the Resources tab
$[Link]('id') // "foo"
3. Open the "Scripts" folder in the left-side panel
4. Select your JavaScript file.
$1 refers to the element previously selected, $2 to the one selected before that, and so forth for $3 and $4.
Adding a breakpoint from the Developer Tools
To get a collection of elements matching a CSS selector, use $$(selector). This is essentially a shortcut for
[Link]. Once you have your JavaScript file open in Developer Tools, you can click a line number to place a breakpoint. The
next time your program runs, it will pause there.
var images = $$('img'); // Returns an array or a nodelist of all matching elements
$_ $()¹ $$() $0 $1 $2 $3 $4 Note about Minified Sources: If your source is minified, you can Pretty Print it (convert to readable format). In
Opera 15+ 11+ 11+ 11+ 11+ 15+ 15+ 15+ Chrome, this is done by clicking on the {} button in the bottom right corner of the source code viewer.
Chrome 22+ ✔ ✔ ✔ ✔ ✔ ✔ ✔
IDEs
Firefox 39+ ✔ ✔ ✔ × × × ×
Visual Studio Code (VSC)
IE 11 11 11 11 11 11 11 11
Safari 6.1+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ VSC has built-in support for debugging JavaScript.

¹ alias to either [Link] or [Link] 1. Click the Debug button on the left or Ctrl + Shift + D
2. If not already done, create a launch configuration file ([Link]) by pressing the gear icon.
Section 99.2: Breakpoints 3. Run the code from VSC by pressing the green play button or hit F5 .

Adding a breakpoint in VSC


Breakpoints pause your program once execution reaches a certain point. You can then step through the program
line by line, observing its execution and inspecting the contents of your variables.
Click next to the line number in your JavaScript source file to add a breakpoint (it will be marked red). To delete the
breakpoint, click the red circle again.
There are three ways of creating breakpoints.

Tip: You can also utilise the conditional breakpoints in browser's dev tools. These help in skipping unnecessary
1. From code, using the debugger; statement.
breaks in execution. Example scenario: you want to examine a variable in a loop exactly at 5th iteration.
2. From the browser, using the Developer Tools.
3. From an Integrated Development Environment (IDE).

Debugger Statement

You can place a debugger; statement anywhere in your JavaScript code. Once the JS interpreter reaches that line, it
will stop the script execution, allowing you to inspect variables and step through your code.

Developer Tools
Section 99.3: Using setters and getters to find what changed
a property
The second option is to add a breakpoint directly into the code from the browser's Developer Tools.
Let's say you have an object like this:
Opening the Developer Tools
Chrome or Firefox var myObject = {

[Link] – JavaScript® Notes for Professionals 435 [Link] – JavaScript® Notes for Professionals 436
name: 'Peter' You can use different console methods to highlight your output in different ways. Other methods are also useful for
}
more advanced debugging.

Later in your code, you try to access [Link] and you get George instead of Peter. You start wondering who For more documentation, information on compatibility, and instructions on how to open your browser's console,
changed it and where exactly it was changed. There is a way to place a debugger (or something else) on every set see the Console topic.
(every time someone does [Link] = 'something'):
Note: if you need to support IE9, either remove [Link] or wrap its calls as follows, because console is
var myObject = { undefined until the Developer Tools are opened:
_name: 'Peter',
set name(name){debugger;this._name=name}, if (console) { //IE9 workaround
get name(){return this._name} [Link]("test");
} }

Note that we renamed name to _name and we are going to define a setter and a getter for name.
Section 99.5: Automatically pausing execution
set name is the setter. That is a sweet spot where you can place debugger, [Link](), or anything else you
In Google Chrome, you can pause execution without needing to place breakpoints.
need for debugging. The setter will set the value for name in _name. The getter (the get name part) will read the
value from there. Now we have a fully functional object with debugging functionality.
Pause on Exception: While this button is toggled on, if your program hits an unhandled exception, the
Most of the time, though, the object that gets changed is not under our control. Fortunately, we can define setters program will pause as if it had hit a breakpoint. The button can be found near Execution Controls and is useful for
and getters on existing objects to debug them. locating errors.

// First, save the name to _name, because we are going to use name for setter/getter You can also pause execution when an HTML tag (DOM node) is modified, or when its attributes are changed. To do
otherObject._name = [Link]; that, right click the DOM node on the Elements tab and select "Break on...".

// Create setter and getter


[Link](otherObject, "name", {
Section 99.6: Elements inspector
set: function(name) {debugger;this._name = name},
get: function() {return this._name} Clicking the Select an element in the page to inspect it button in the upper left corner of the Elements tab in
}); Chrome or Inspector tab in Firefox, available from Developer Tools, and then clicking on an element of the page
highlights the element and assigns it to the $0 variable.
Check out setters and getters at MDN for more information.
Elements inspector can be used in variety of ways, for example:
Browser support for setters/getters:
1. You can check if your JS is manipulating DOM the way you expect it to,
Chrome Firefox IE Opera Safari Mobile 2. You can more easily debug your CSS, when seeing which rules affect the element
Version 1 2.0 9 9.5 3 all
(Styles tab in Chrome)
3. You can play around with CSS and HTML without reloading the page.
Section 99.4: Using the console
Also, Chrome remembers last 5 selections in the Elements tab. $0 is the current selection, while $1 is the previous
In many environments, you have access to a global console object that contains some basic methods for selection. You can go up to $4. That way you can easily debug multiple nodes without constantly switching selection
communicating with standard output devices. Most commonly, this will be the browser's JavaScript console (see to them.
Chrome, Firefox, Safari, and Edge for more information).
You can read more at Google Developers.
// At its simplest, you can 'log' a string
[Link]("Hello, World!"); Section 99.7: Break when a function is called
// You can also log any number of comma-separated values
For named (non-anonymous) functions, you can break when the function is executed.
[Link]("Hello", "World!");

// You can also use string substitution debug(functionName);


[Link]("%s %s", "Hello", "World!");
The next time functionName function runs, the debugger will stop on its first line.
// You can also log any variable that exist in the same scope
var arr = [1, 2, 3];
[Link]([Link], this);

[Link] – JavaScript® Notes for Professionals 437 [Link] – JavaScript® Notes for Professionals 438
Section 99.8: Stepping through code Chapter 100: Unit Testing JavaScript
Once you've paused execution on a breakpoint, you may want to follow execution line-by-line to observe what
happens. Open your browser's Developer Tools and look for the Execution Control icons. (This example uses the Section 100.1: Unit Testing Promises with Mocha, Sinon, Chai
icons in Google Chrome, but they'll be similar in other browsers.) and Proxyquire
Resume: Unpause execution. Shorcut: F8 (Chrome, Firefox) Here we have a simple class to be tested that returns a Promise based on the results of an external
ResponseProcessor that takes time to execute.
Step Over: Run the next line of code. If that line contains a function call, run the whole function and move to
the next line, rather than jumping to wherever the function is defined. Shortcut : F10 (Chrome, Firefox, IE/Edge), For simplicity we'll assume that the processResponse method won't ever fail.
F6 (Safari)
import {processResponse} from '../utils/response_processor';

Step Into: Run the next line of code. If that line contains a function call, jump into the function and pause there. const ping = () => {
Shortcut : F11 (Chrome, Firefox, IE/Edge), F7 (Safari) return new Promise((resolve, _reject) => {
const response = processResponse(data);
resolve(response);
Step Out: Run the rest of the current function, jump back to where the function was called from, and pause at
});
the next statement there. Shortcut : Shift + F11 (Chrome, Firefox, IE/Edge), F8 (Safari) }

Use these in conjunction with the Call Stack, which will tell you which function you're currently inside of, which [Link] = ping;
function called that function, and so forth.
To test this we can leverage the following tools.
See Google's guide on "How to Step Through the Code" for more details and advice.
1. mocha
Links to browser shortcut key documentation:
2. chai
3. sinon
Chrome
4. proxyquire
Firefox
5. chai-as-promised
IE
Edge
I use the following test script in my [Link] file.
Safari
"test": "NODE_ENV=test mocha --compilers js:babel-core/register --require
./test/unit/test_helper.js --recursive test/**/*_spec.js"

This allows me to use es6 syntax. It references a test_helper that will look like

import chai from 'chai';


import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import chaiAsPromised from 'chai-as-promised';
import sinonStubPromise from 'sinon-stub-promise';

[Link](sinonChai);
[Link](chaiAsPromised);
sinonStubPromise(sinon);

Proxyquire allows us to inject our own stub in the place of the external ResponseProcessor. We can then use sinon
to spy on that stub's methods. We use the extensions to chai that chai-as-promised injects to check that the
ping() method's promise is fullfilled, and that it eventually returns the required response.

import {expect} from 'chai';


import sinon from 'sinon';
import proxyquire from 'proxyquire';

let formattingStub = {
wrapResponse: () => {}

[Link] – JavaScript® Notes for Professionals 439 [Link] – JavaScript® Notes for Professionals 440
} let pingWrapper = proxyquire('../src/pingWrapper', {
'./ping': pingStub
let ping = proxyquire('../../../src/api/ping', { });
'../utils/formatting': formattingStub
}); describe('pingWrapper', () => {
let pingSpy;
describe('ping', () => { const response = 'some response';
let wrapResponseSpy, pingResult;
const response = 'some response'; beforeEach(() => {
pingSpy = [Link](pingStub, 'ping').returnsPromise();
beforeEach(() => { [Link](response);
wrapResponseSpy = [Link](formattingStub, 'wrapResponse').returns(response); pingWrapper();
pingResult = ping(); });
})
afterEach(() => {
afterEach(() => { [Link]();
[Link](); });
})
it('wraps the ping', () => {
it('returns a fullfilled promise', () => { expect(pingSpy).[Link](response);
expect(pingResult).[Link]; });
}) });

it('eventually returns the correct response', () => {


expect(pingResult).[Link](response); Section 100.2: Basic Assertion
})
}); At its most basic level, Unit Testing in any language provides assertions against some known or expected output.

Now instead let's assume you wish to test something that uses the response from ping. function assert( outcome, description ) {
var passFail = outcome ? 'pass' : 'fail';
[Link](passFail, ': ', description);
import {ping} from './ping';
return outcome;
};
const pingWrapper = () => {
[Link]((response) => {
// do something with the response The popular assertion method above shows us one quick and easy way to assert a value in most web browsers and
}); interpreters like [Link] with virtually any version of ECMAScript.
}
A good unit test is designed to test a discreet unit of code; usually a function.
[Link] = pingWrapper;

function add(num1, num2) {


To test the pingWrapper we leverage return num1 + num2;
}
1. sinon
2. proxyquire var result = add(5, 20);
3. sinon-stub-promise assert( result == 24, 'add(5, 20) should return 25...');

As before, Proxyquire allows us to inject our own stub in the place of the external dependency, in this case the In the example above, the return value from the function add(x, y) or 5 + 20 is clearly 25, so our assertion of 24
ping method we tested previously. We can then use sinon to spy on that stub's methods and leverage sinon-stub- should fail, and the assert method will log a "fail" line.
promise to allow us to returnsPromise. This promise can then be resolved or rejected as we wish in the test, in
If we simply modify our expected assertion outcome, the test will succeed and the resulting output would look
order to test the wrapper's response to that.
something like this.
import {expect} from 'chai';
import sinon from 'sinon'; assert( result == 25, 'add(5, 20) should return 25...');
import proxyquire from 'proxyquire';
console output:
let pingStub = {
ping: () => {} > pass: should return 25...
};
This simple assertion can assure that in many different cases, your "add" function will always return the expected

[Link] – JavaScript® Notes for Professionals 441 [Link] – JavaScript® Notes for Professionals 442
result and requires no additional frameworks or libraries to work.
Chapter 101: Evaluating JavaScript
A more rigorous set of assertions would look like this (using var result = add(x,y) for each assertion):
Parameter Details
assert( result == 0, 'add(0, 0) should return 0...'); string The JavaScript to be evaluated.
assert( result == -1, 'add(0, -1) should return -1...');
assert( result == 1, 'add(0, 1) should return 1...'); In JavaScript, the eval function evaluates a string as if it were JavaScript code. The return value is the result of the
evaluated string, e.g. eval('2 + 2') returns 4.
And console output would be this:
eval is available in the global scope. The lexical scope of the evaluation is the local scope unless invoked indirectly
> pass: should return 0... (e.g. var geval = eval; geval(s);).
> pass: should return -1...
> pass: should return 1...
The use of eval is strongly discouraged. See the Remarks section for details.

We can now safely say that add(x,y)… should return the sum of two integers. We can roll these up into
something like this:
Section 101.1: Evaluate a string of JavaScript statements
var x = 5;
function test__addsIntegers() {
var str = "if (x == 5) {[Link]('z is 42'); z = 42;} else z = 0; ";

// expect a number of passed assertions


[Link]("z is ", eval(str));
var passed = 3;

// number of assertions to be reduced and added as Booleans The use of eval is strongly discouraged. See the Remarks section for details.
var assertions = [

assert( add(0, 0) == 0, 'add(0, 0) should return 0...'),


Section 101.2: Introduction
assert( add(0, -1) == -1, 'add(0, -1) should return -1...'),
You can always run JavaScript from inside itself, although this is strongly discouraged due to the security
assert( add(0, 1) == 1, 'add(0, 1) should return 1...')
vulnerabilities it presents (see Remarks for details).
].reduce(function(previousValue, currentValue){
To run JavaScript from inside JavaScript, simply use the below function:
return previousValue + current;
eval("var a = 'Hello, World!'");
});

if (assertions === passed) { Section 101.3: Evaluation and Math


[Link]("add(x,y)... did return the sum of two integers"); You can set a variable to something with the eval() function by using something similar to the below code:
return true;
var x = 10;
} else {
var y = 20;
var a = eval("x * y") + "<br>";
[Link]("add(x,y)... does not reliably return the sum of two integers");
var b = eval("2 + 2") + "<br>";
return false;
var c = eval("x + 17") + "<br>";

}
var res = a + b + c;
}

The result, stored in the variable res, will be:

200
4
27

The use of eval is strongly discouraged. See the Remarks section for details.

[Link] – JavaScript® Notes for Professionals 443 [Link] – JavaScript® Notes for Professionals 444
Chapter 102: Linters - Ensuring code case '*':
case 'x':

quality {
result = a * b;
break;

Section 102.1: JSHint }


}

JSHint is an open source tool which detects errors and potential problems in JavaScript code. // JSHint disable error for variable not defined, because it is defined in another file
/* jshint -W117 */
To lint your JavaScript you have two options. globalVariable = '[Link]';
/* jshint +W117 */
1. Go to [Link] and paste your code in there on line text editor.
2. Install JSHint in your IDE. More configuration options are documented at [Link]
Atom: linter-jshint (must have Linter plugin installed)
Sublime Text: JSHint Gutter and/or Sublime Linter Section 102.2: ESLint / JSCS
Vim: [Link] or [Link]
Visual Studio: VSCode JSHint ESLint is a code style linter and formatter for your style guide much like JSHint. ESLint merged with JSCS in April of
2016. ESLint does take more effort to set up than JSHint, but there are clear instructions on their website for getting
A benefit of adding it to your IDE is that you can create a JSON configuration file named .jshintrc that will be used started.
when linting your program. This is convent if you want to share configurations between projects.
A sample configuration for ESLint is as follows:
Example .jshintrc file
{
{ "rules": {
"-W097": false, // Allow "use strict" at document level "semi": ["error", "always"], // throw an error when semicolons are detected
"browser": true, // defines globals exposed by modern browsers "quotes": ["error", "double"] // throw an error when double quotes are detected
[Link] }
"curly": true, // requires you to always put curly braces around blocks in loops and }
conditionals [Link]
"devel": true, // defines globals that are usually used for logging poor-man's debugging:
A sample configuration file where ALL rules are set to off, with descriptions for what they do can be found here.
console, alert, etc. [Link]
// List global variables (false means read only)
"globals": { Section 102.3: JSLint
"globalVar": true
}, JSLint is the trunk from which JSHint branched. JSLint takes a much more opinionated stance on how to write
"jquery": true, // This option defines globals exposed by the jQuery JavaScript library.
JavaScript code, pushing you towards only using the parts Douglas Crockford deems to be its "good parts", and
"newcap": false,
// List any global functions or const vars
away from any code that Crockford believes to have a better solution. The following StackOverflow thread may help
"predef": [ you decide which linter is right for you. While there are differences (here are some brief comparisons between it
"GlobalFunction", and JSHint / ESLint), each option is extremely customizable.
"GlobalFunction2"
], For a more information about configuring JSLint check out NPM or github.
"undef": true, // warn about undefined vars
"unused": true // warn about unused vars
}

JSHint also allows configurations for specific lines/blocks of code

switch(operation)
{
case '+'
{
result = a + b;
break;
}

// JSHint W086 Expected a 'break' statement


// JSHint flag to allow cases to not need a break
/* falls through */

[Link] – JavaScript® Notes for Professionals 445 [Link] – JavaScript® Notes for Professionals 446
Chapter 103: Anti-patterns Chapter 104: Performance Tips
Section 103.1: Chaining assignments in var declarations JavaScript, like any language, requires us to be judicious in the use of certain language features. Overuse of some
features can decrease performance, while some techniques can be used to increase performance.
Chaining assignments as part of a var declaration will create global variables unintentionally.
Section 104.1: Avoid try/catch in performance-critical
For example:
functions
(function foo() {
Some JavaScript engines (for example, the current version of [Link] and older versions of Chrome before
var a = b = 0;
})() Ignition+turbofan) don't run the optimizer on functions that contain a try/catch block.
[Link]('a: ' + a);
[Link]('b: ' + b); If you need to handle exceptions in performance-critical code, it can be faster in some cases to keep the try/catch in
a separate function. For example, this function will not be optimized by some implementations:
Will result in:
function myPerformanceCriticalFunction() {
Uncaught ReferenceError: a is not defined try {
'b: 0' // do complex calculations here
} catch (e) {
[Link](e);
In the above example, a is local but b becomes global. This is because of the right to left evaluation of the = }
operator. So the above code actually evaluated as }

var a = (b = 0); However, you can refactor to move the slow code into a separate function (that can be optimized) and call it from
inside the try block.
The correct way to chain var assignments is:
// This function can be optimized
var a, b; function doCalculations() {
a = b = 0; // do complex calculations here
}
Or:
// Still not always optimized, but it's not doing much so the performance doesn't matter
function myPerformanceCriticalFunction() {
var a = 0, b = a; try {
doCalculations();
This will make sure that both a and b will be local variables. } catch (e) {
[Link](e);
}
}

Here's a jsPerf benchmark showing the difference: [Link] In the current


version of most browsers, there shouldn't be much difference if any, but in less recent versions of Chrome and
Firefox, or IE, the version that calls a helper function inside the try/catch is likely to be faster.

Note that optimizations like this should be made carefully and with actual evidence based on profiling your code. As
JavaScript engines get better, it could end up hurting performance instead of helping, or making no difference at all
(but complicating the code for no reason). Whether it helps, hurts, or makes no difference can depend on a lot of
factors, so always measure the effects on your code. That's true of all optimizations, but especially micro-
optimizations like this that depend on low-level details of the compiler/runtime.

Section 104.2: Limit DOM Updates


A common mistake seen in JavaScript when run in a browser environment is updating the DOM more often than
necessary.

The issue here is that every update in the DOM interface causes the browser to re-render the screen. If an update

[Link] – JavaScript® Notes for Professionals 447 [Link] – JavaScript® Notes for Professionals 448
changes the layout of an element in the page, the entire page layout needs to be re-computed, and this is very Performance interface that represents timing-related performance information for the given page (only available in
performance-heavy even in the simplest of cases. The process of re-drawing a page is known as reflow and can browsers).
cause a browser to run slowly or even become unresponsive.
[Link] on [Link] gives you timing information as [seconds, nanoseconds] tuples. Called without argument
The consequence of updating the document too frequently is illustrated with the following example of adding items it returns an arbitrary time but called with a previously returned value as argument it returns the difference
to a list. between the two executions.

Consider the following document containing a <ul> element: Console timers [Link]("labelName") starts a timer you can use to track how long an operation takes. You
give each timer a unique label name, and may have up to 10,000 timers running on a given page. When you call
<!DOCTYPE html> [Link]("labelName") with the same name, the browser will finish the timer for given name and output
<html>
the time in milliseconds, that elapsed since the timer was started. The strings passed to time() and timeEnd() must
<body>
<ul id="list"></ul>
match otherwise the timer will not finish.
</body>
</html> [Link] function [Link]() returns current Timestamp in milliseconds, which is a Number representation of
time since 1 January 1970 00:00:00 UTC until now. The method now() is a static method of Date, therefore you
We add 5000 items to the list looping 5000 times (you can try this with a larger number on a powerful computer to always use it as [Link]().
increase the effect).
Example 1 using: [Link]()
var list = [Link]("list");
for(var i = 1; i <= 5000; i++) {
In this example we are going to calculate the elapsed time for the execution of our function, and we are going to
[Link] += `<li>item ${i}</li>`; // update 5000 times use the [Link]() method that returns a DOMHighResTimeStamp, measured in milliseconds, accurate to
} one thousandth of a millisecond.

In this case, the performance can be improved by batching all 5000 changes in one single DOM update. let startTime, endTime;

var list = [Link]("list"); function myFunction() {


var html = ""; //Slow code you want to measure
for(var i = 1; i <= 5000; i++) { }
html += `<li>item ${i}</li>`;
} //Get the start time
[Link] = html; // update once startTime = [Link]();

//Call the time-consuming function


The function [Link]() can be used as a lightweight container for the HTML created by myFunction();
the loop. This method is slightly faster than modifying the container element's innerHTML property (as shown
below). //Get the end time
endTime = [Link]();
var list = [Link]("list");
//The difference is how many milliseconds it took to call myFunction()
var fragment = [Link]();
[Link]('Elapsed time:', (endTime - startTime));
for(var i = 1; i <= 5000; i++) {
li = [Link]("li");
[Link] = "item " + i; The result in console will look something like this:
[Link](li);
i++; Elapsed time: 0.10000000009313226
}
[Link](fragment);
Usage of [Link]() has the highest precision in browsers with accuracy to one thousandth of a
millisecond, but the lowest compatibility.
Section 104.3: Benchmarking your code - measuring execution
time Example 2 using: [Link]()

Most performance tips are very dependent of the current state of JS engines and are expected to be only relevant In this example we are going to calculate the elapsed time for the initialization of a big array (1 million values), and
at a given time. The fundamental law of performance optimization is that you must first measure before trying to we are going to use the [Link]() method
optimize, and measure again after a presumed optimization.
let t0 = [Link](); //stores current Timestamp in milliseconds since 1 January 1970 00:00:00 UTC
To measure code execution time, you can use different time measurement tools like: let arr = []; //store empty array
for (let i = 0; i < 1000000; i++) { //1 million iterations
[Link](i); //push current i value

[Link] – JavaScript® Notes for Professionals 449 [Link] – JavaScript® Notes for Professionals 450
} function checkCache(val) {
[Link]([Link]() - t0); //print elapsed time between stored t0 and now if (val in cache) {
[Link]('It was in the cache :D');
return cache[val]; // return cached
Example 3 using: [Link]("label") & [Link]("label")
} else {
cache[val] = factorial(val); // we cache it
In this example we are doing the same task as in Example 2, but we are going to use the [Link]("label") &
return cache[val]; // and then return it
[Link]("label") methods }

[Link]("t"); //start new timer for label name: "t" /* Other alternatives for checking are:
let arr = []; //store empty array || [Link](val) or !!cache[val]
for(let i = 0; i < 1000000; i++) { //1 million iterations || but wouldn't work if the results of those
[Link](i); //push current i value || executions were falsy values.
} */
[Link]("t"); //stop the timer for label name: "t" and print elapsed time }

// We create and name the actual function to be used


Exemple 4 using [Link]()
function factorial(num) {
return (num === 0)? 1 : num * factorial(num - 1);
In [Link] programs this is the most precise way to measure spent time. } // End of factorial function

let start = [Link](); /* We return the function that checks, not the one
|| that computes because it happens to be recursive,
// long execution here, maybe asynchronous || if it weren't you could avoid creating an extra
|| function in this self-invoking closure function.
let diff = [Link](start); */
// returns for example [ 1, 2325 ] return checkCache;
[Link](`Operation took ${diff[0] * 1e9 + diff[1]} nanoseconds`); }());
// logs: Operation took 1000002325 nanoseconds

Now we can start using it:


Section 104.4: Use a memoizer for heavy-computing
functions
If you are building a function that may be heavy on the processor (either clientside or serverside) you may want to
consider a memoizer which is a cache of previous function executions and their returned values. This allows you to
check if the parameters of a function were passed before. Remember, pure functions are those that given an input,
return a corresponding unique output and don't cause side-effects outside their scope so, you should not add Now that I start to reflect on what I did, if I were to increment from 1 instead of decrement from num, I could have
memoizers to functions that are unpredictable or depend on external resources (like AJAX calls or randomly cached all of the factorials from 1 to num in the cache recursively, but I will leave that for you.
returned values).
This is great but what if we have multiple parameters? This is a problem? Not quite, we can do some nice tricks
Let's say I have a recursive factorial function: like using [Link]() on the arguments array or even a list of values that the function will depend on (for
object-oriented approaches). This is done to generate a unique key with all the arguments and dependencies
function fact(num) {
included.
return (num === 0)? 1 : num * fact(num - 1);
}
We can also create a function that "memoizes" other functions, using the same scope concept as before (returning
a new function that uses the original and has access to the cache object):
If I pass small values from 1 to 100 for example, there would be no problem, but once we start going deeper, we
might blow up the call stack or make the process a bit painful for the JavaScript engine we're doing this in,
WARNING: ES6 syntax, if you don't like it, replace ... with nothing and use the var args =
especially if the engine doesn't count with tail-call optimization (although Douglas Crockford says that native ES6
[Link](null, arguments); trick; replace const and let with var, and the other things you
has tail-call optimization included).
already know.

We could hard code our own dictionary from 1 to god-knows-what number with their corresponding factorials but,
function memoize(func) {
I'm not sure if I advise that! Let's create a memoizer, shall we? let cache = {};

var fact = (function() { // You can opt for not naming the function
var cache = {}; // Initialise a memory cache object function memoized(...args) {
const argsKey = [Link](args);
// Use and return this function to check if val is cached

[Link] – JavaScript® Notes for Professionals 451 [Link] – JavaScript® Notes for Professionals 452
// The same alternatives apply for this example p = new P();
if (argsKey in cache) { if (index > 5000000) {
[Link](argsKey + ' was/were in cache :D'); p.x = "some_string";
return cache[argsKey]; }
} else {
cache[argsKey] = [Link](null, args); // Cache it return p;
return cache[argsKey]; // And then return it });
} big_array.reduce((sum, p)=> sum + [Link], 0);
} }

return memoized; // Return the memoized function function f2() {


} var P = function () {
[Link] = 1;
this.x = null;
Now notice that this will work for multiple arguments but won't be of much use in object-oriented methods I think,
};
you may need an extra object for dependencies. Also, [Link](null, args) can be replaced with var big_array = new Array(10000000).fill(1).map((x, index)=> {
func(...args) since array destructuring will send them separately instead of as an array form. Also, just for p = new P();
reference, passing an array as an argument to func won't work unless you use [Link] as I did. if (index > 5000000) {
p.x = "some_string";
To use the above method you just: }

return p;
const newFunction = memoize(oldFunction);
});
big_array.reduce((sum, p)=> sum + [Link], 0);
// Assuming new oldFunction just sums/concatenates:
}
newFunction('meaning of life', 42);
// -> "meaning of life42"

(function perform(){
newFunction('meaning of life', 42); // again
var start = [Link]();
// => ["meaning of life",42] was/were in cache :D
f1();
// -> "meaning of life42"
var duration = [Link]() - start;

Section 104.5: Initializing object properties with null [Link]('duration of f1 ' + duration);

All modern JavaScript JIT compilers trying to optimize code based on expected object structures. Some tip from
start = [Link]();
mdn. f2();
duration = [Link]() - start;

Fortunately, the objects and properties are often "predictable", and in such cases their underlying [Link]('duration of f2 ' + duration);
structure can also be predictable. JITs can rely on this to make predictable accesses faster. })()

This is the result for Chrome and Firefox.


The best way to make object predictable is to define a whole structure in a constructor. So if you're going to add
some extra properties after object creation, define them in a constructor with null. This will help the optimizer to
predict object behavior for its whole life cycle. However all compilers have different optimizers, and the FireFox Chrome
--------------------------
performance increase can be different, but overall it's good practice to define all properties in a constructor, even
f1 6,400 11,400
when their value is not yet known. f2 1,700 9,600

Time for some testing. In my test, I'm creating a big array of some class instances with a for loop. Within the loop,
I'm assigning the same string to all object's "x" property before array initialization. If constructor initializes "x" As we can see, the performance improvements are very different between the two.
property with null, array always processes better even if it's doing extra statement.
Section 104.6: Reuse objects rather than recreate
This is code:
Example A
function f1() {
var i,a,b,len;
var P = function () {
a = {x:0,y:0}
[Link] = 1
function test(){ // return object created each call
};
return {x:0,y:0};
var big_array = new Array(10000000).fill(1).map((x, index)=> {
}

[Link] – JavaScript® Notes for Professionals 453 [Link] – JavaScript® Notes for Professionals 454
function test1(a){ // return object supplied }
a.x=0;
a.y=0;
For every iteration in for loop, the engine will lookup items, lookup the length attribute within items, lookup items
return a;
}
again, lookup the value at index i of items, and then finally lookup global_variable, first trying the local scope
before checking the global scope.
for(i = 0; i < 100; i ++){ // Loop A
b = test(); A performant rewrite of the above function is:
}
function foo(){
for(i = 0; i < 100; i ++){ // Loop B var local_variable = 0;
b = test1(a); for (var i=0, li=[Link]; i<li; i++) {
} local_variable += items[i];
}
Loop B is 4 (400%) times faster than Loop A return local_variable;
}
It is very inefficient to create a new object in performance code. Loop A calls function test() which returns a new
object every call. The created object is discarded every iteration, Loop B calls test1() that requires the object For every iteration in the rewritten for loop, the engine will lookup li, lookup items, lookup the value at index i,
returns to be supplied. It thus uses the same object and avoids allocation of a new object, and excessive GC hits. and lookup local_variable, this time only needing to check the local scope.
(GC were not included in the performance test)
Section 104.8: Be consistent in use of Numbers
Example B
var i,a,b,len; If the engine is able to correctly predict you're using a specific small type for your values, it will be able to optimize
a = {x:0,y:0} the executed code.
function test2(a){
return {x : a.x * 10,y : a.x * 10}; In this example, we'll use this trivial function summing the elements of an array and outputting the time it took:
}
function test3(a){
// summing properties
a.x= a.x * 10;
var sum = (function(arr){
a.y= a.y * 10;
var start = [Link]();
return a;
var sum = 0;
}
for (var i=0; i<[Link]; i++) {
for(i = 0; i < 100; i++){ // Loop A
sum += arr[i];
b = test2({x : 10, y : 10});
}
}
var diffSum = [Link](start);
for(i = 0; i < 100; i++){ // Loop B
[Link](`Summing took ${diffSum[0] * 1e9 + diffSum[1]} nanoseconds`);
a.x = 10;
return sum;
a.y = 10;
})(arr);
b = test3(a);
}
Let's make an array and sum the elements:
Loop B is 5 (500%) times faster than loop A
var N = 12345,
arr = [];
Section 104.7: Prefer local variables to globals, attributes, for (var i=0; i<N; i++) arr[i] = [Link]();
and indexed values
Result:
JavaScript engines first look for variables within the local scope before extending their search to larger scopes. If the
variable is an indexed value in an array, or an attribute in an associative array, it will first look for the parent array
Summing took 384416 nanoseconds
before it finds the contents.

This has implications when working with performance-critical code. Take for instance a common for loop: Now, let's do the same but with only integers:

var global_variable = 0; var N = 12345,


function foo(){ arr = [];
global_variable = 0; for (var i=0; i<N; i++) arr[i] = [Link](1000*[Link]());
for (var i=0; i<[Link]; i++) {
global_variable += items[i];
} Result:

[Link] – JavaScript® Notes for Professionals 455 [Link] – JavaScript® Notes for Professionals 456
Summing took 180520 nanoseconds Chapter 105: Memory eciency
Summing integers took half the time here. Section 105.1: Drawback of creating true private method
Engines don't use the same types you have in JavaScript. As you probably know, all numbers in JavaScript are One drawback of creating private method in JavaScript is memory-inefficient because a copy of the private method
IEEE754 double precision floating point numbers, there's no specific available representation for integers. But will be created every time a new instance is created. See this simple example.
engines, when they can predict you only use integers, can use a more compact and faster to use representation, for
example, short integers. function contact(first, last) {
[Link] = first;
[Link] = last;
This kind of optimization is especially important for computation or data intensive applications.
[Link];

// private method
var formatPhoneNumber = function(number) {
// format phone number based on input
};

// public method
[Link] = function(number) {
[Link] = formatPhoneNumber(number);
};
}

When you create few instances, they all have a copy of formatPhoneNumber method

var rob = new contact('Rob', 'Sanderson');


var don = new contact('Donald', 'Trump');
var andy = new contact('Andy', 'Whitehall');

Thus, would be great to avoid using private method only if it's necessary.

[Link] – JavaScript® Notes for Professionals 457 [Link] – JavaScript® Notes for Professionals 458
Appendix A: Reserved Keywords false protected

ECMAScript 5 / 5.1
Certain words - so-called keywords - are treated specially in JavaScript. There's a plethora of different kinds of
keywords, and they have changed in different versions of the language. There was no change since ECMAScript 3.

Section A.1: Reserved Keywords ECMAScript 5 removed int, byte, char, goto, long, final, float, short, double, native, throws, boolean, abstract,
volatile, transient, and synchronized; it added let and yield.
JavaScript has a predefined collection of reserved keywords which you cannot use as variables, labels, or
A—F F—P P—Z
function names.
break finally public
ECMAScript 1
case for return
Version = 1
A—E E—R S—Z catch function static
break export super class if super
case extends switch const implements switch
catch false this continue import this
class finally throw debugger in throw
const for true default instanceof true
continue function try delete interface try
debugger if typeof do let typeof
default import var else new var
delete in void enum null void
do new while export package while
else null with extends private with
enum return false protected yield

ECMAScript 2
implements, let, private, public, interface, package, protected, static, and yield are disallowed in

Added 24 additional reserved keywords. (New additions in bold). strict mode only.

Version = 3 Version = E4X


A—F F—P P—Z eval and arguments are not reserved words but they act like it in strict mode.
abstract final public
boolean finally return
break float short
byte for static ECMAScript 6 / ECMAScript 2015
case function super A—E E—R S—Z
break export super
catch goto switch
case extends switch
char if synchronized
catch finally this
class implements this
class for throw
const import throw
const function try
continue in throws
continue if typeof
debugger instanceof transient
debugger import var
default int true
default in void
delete interface try
delete instanceof while
do long typeof
do new with
double native var
else return yield
else new void
enum null volatile
Future reserved keywords
export package while
extends private with The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at

[Link] – JavaScript® Notes for Professionals 459 [Link] – JavaScript® Notes for Professionals 460
present, but they might at some future time, so they cannot be used as identifiers. Syntax

enum Identifier ::
IdentifierName but not ReservedWord
The following are only reserved when they are found in strict mode code:
By specification, a ReservedWord is:
implements package public
interface private `static'
Section 7.6.1
let protected

A reserved word is an IdentifierName that cannot be used as an Identifier.


Future reserved keywords in older standards
ReservedWord ::
The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).
Keyword
FutureReservedWord
abstract float short NullLiteral
boolean goto synchronized BooleanLiteral
byte instanceof throws
char int transient This includes keywords, future keywords, null, and boolean literals. The full list of keywords are in Sections 7.6.1
double long volatile and literals are in Section 7.8.
final native
The above (Section 7.6) implies that IdentifierNames can be ReservedWords, and from the specification for object
Additionally, the literals null, true, and false cannot be used as identifiers in ECMAScript. initializers:

From the Mozilla Developer Network.


Section 11.1.5

Section A.2: Identifiers & Identifier Names Syntax

With regards to reserved words there is a small distinctions between the "Identifiers" used for the likes of variable or ObjectLiteral :
function names and the "Identifier Names" allowed as properties of composite data types. { }
{ PropertyNameAndValueList }
For example the following will result in an illegal syntax error: { PropertyNameAndValueList , }

var break = true; Where PropertyName is, by specification:

PropertyName :
Uncaught SyntaxError: Unexpected token break IdentifierName
StringLiteral
NumericLiteral
However the name is deemed valid as a property of an object (as of ECMAScript 5+):
As you can see, a PropertyName may be an IdentifierName, thus allowing ReservedWords to be PropertyNames.
var obj = { That conclusively tells us that, by specification, it is allowed to have ReservedWords such as class and var as
break: true
PropertyNames unquoted just like string literals or numeric literals.
};
[Link]([Link]);
To read more, see Section 7.6 - Identifier Names and Identifiers.

To quote from this answer: Note: the syntax highlighter in this example has spotted the reserved word and still highlighted it. While the
example is valid JavaScript developers can get caught out by some compiler / transpiler, linter and minifier tools
From the ECMAScript® 5.1 Language Specification:
that argue otherwise.

Section 7.6

Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers”
section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an
IdentifierName that is not a ReservedWord (see 7.6.1).

[Link] – JavaScript® Notes for Professionals 461 [Link] – JavaScript® Notes for Professionals 462
Credits Armfoot
AstroCB
Chapter 62
Chapter 1
Aswin Chapter 21
Thank you greatly to all the people from Stack Overflow Documentation who helped provide this content, Atakan Goktepe Chapter 5
more changes can be sent to web@[Link] for new content to be published or updated ATechieThought Chapter 1
Ates Goral Chapters 3, 35 and 42
16807 Chapter 104 Awal Garg Chapters 41 and 42
2426021684 Chapters 1, 7, 12, 42 and 59 azz Chapter 10
4444 Chapter 23 Badacadabra Chapter 25
4m1r Chapter 100 baga Chapter 5
A.J Chapter 61 balpha Chapter 12
A.M.K Chapters 5, 12, 40, 63, 72 and 73 Bamieh Chapter 12
Aadit M Shah Chapter 29 BarakD Chapter 22
Abdelaziz Mokhnache Chapter 1 Barmar Chapter 14
Abhishek Chapter 65 Basilin Joe Chapter 28
Abhishek Singh Chapter 48 Beau Chapter 5
Adam Heath Chapter 59 Bekim Bacaj Chapter 1
adius Chapter 31 Ben Chapter 12
adriennetacke Chapter 68 Ben McCormick Chapter 60
Aeolingamenfel Chapter 62 Benjadahl Chapter 19
afzalex Chapter 42 Bennett Chapter 70
Ahmed Ayoub Chapter 12 bfavaretto Chapter 1
aikeru Chapter 14 Bit Byte Chapter 89
Ajedi32 Chapter 16 Black Chapter 1
Akshat Mahajan Chapter 53 Blindman67 Chapters 10, 12, 14, 28, 41, 56, 84 and 104
Ala Eddine JEBALI Chapters 1, 24 and 56 bloodyKnuckles Chapter 63
Alberto Nicoletti Chapters 13, 14 and 43 Blubberguy22 Chapter 11
Alejandro Nanez Chapter 12 Blue Sheep Chapters 14 and 104
Alex Chapter 63 BluePill Chapter 7
Alex Filatov Chapters 14, 35 and 67 Blundering Philosopher Chapters 1 and 42
Alex Logan Chapter 5 bobylito Chapter 42
Alexander O'Mara Chapter 1 Boopathi Rajaa Chapters 22, 41, 50 and 63
Alexandre N. Chapters 1 and 42 Borja Tur Chapters 13 and 19
aluxian Chapter 81 Chapters 1, 12 and 42
Božo Stojković
amflare Chapter 20
Brandon Buck Chapter 1
Aminadav Chapters 1, 35 and 104
Brendan Doherty Chapter 50
Andrew Burgess Chapter 55
brentonstrine Chapter 19
Andrew Myers Chapter 4
Brett DeWoody Chapter 12
Andrew Sklyarevsky Chapters 59 and 98
Brett Zamir Chapters 1 and 4
Andrew Sun Chapter 59
Brian Liu Chapter 105
Andrey Chapter 14
bwegs Chapters 1, 56 and 62
Angel Politis Chapters 36 and 47
C L K Kissane Chapter 5
Angela Amarapala Chapter 26
Callan Heard Chapter 50
Angelos Chalaris Chapters 13, 37 and 46
CamJohnson26 Chapter 50
Ani Menon Chapters 1 and 36
catalogue_number Chapter 1
Anirudh Modi Chapters 12, 19, 50, 60 and 62
cchamberlain Chapter 5
Anirudha Chapter 103
CD.. Chapters 12 and 13
Anko Chapter 1
cdm Chapter 58
Ankur Anand Chapter 1
cdrini Chapters 19 and 55
Anurag Singh Bisht Chapter 87
Cerbrus Chapters 1, 5, 14, 17, 40, 42, 99 and 103
Ara Yeressian Chapter 42
cFreed Chapter 10
Araknid Chapters 11 and 30
Charlie H Chapters 10, 14, 35 and 54
arbybruce Chapter 33
Chong Lip Phang Chapter 50

[Link] – JavaScript® Notes for Professionals 463 [Link] – JavaScript® Notes for Professionals 464
choz Chapter 19 DVJex Chapter 99
Chris Chapters 10 and 22 DzinX Chapter 12
Christian Chapter 2 Ehsan Sajjad Chapter 99
Christian Landgren Chapter 13 Eirik Birkeland Chapter 19
Christoph Chapter 1 Ekin Chapters 37 and 67
Christophe Marois Chapter 42 eltonkamami Chapters 18, 19, 31, 62 and 99
Christopher Ronning Chapter 27 Emissary Chapters 5, 17, 104 and 106
Claudiu Chapters 7 and 42 Emre Bolat Chapter 106
Cliff Burton Chapters 13 and 19 Erik Minarini Chapter 42
Code Uniquely Chapter 18 Ethan Chapter 62
codemano Chapter 12 et_l Chapters 13 and 65
code_monk Chapter 12 Evan Bechtol Chapter 42
CodingIntrigue Chapters 7, 12, 13, 50, 57 and 69 Everettss Chapters 1, 19 and 57
Colin Chapter 10 Explosion Pills Chapter 81
cone56 Chapter 92 Fab313 Chapter 22
Conlin Durbin Chapter 27 fracz Chapters 12 and 42
CPHPython Chapters 5, 12, 19, 50, 56 and 62 Frank Tan Chapter 60
Creative John Chapter 24 FrankCamara Chapter 12
CroMagnon Chapters 27 and 48 FredMaggiowski Chapter 13
csander Chapters 6, 8, 18, 38, 43, 56 and 85 fson Chapters 42 and 81
cswl Chapters 15 and 81 Gabriel Furstenheim Chapter 41
Daksh Gupta Chapters 1 and 62 Gabriel L. Chapter 42
Damon Chapters 11, 12, 19 and 62 Gaurang Tandon Chapter 14
Dan Pantry Chapter 42 Gavishiddappa Gadagi Chapter 19
Daniel Chapter 12 gca Chapter 10
Daniel Herr Chapters 11, 12, 18, 30, 35, 41, 42 and 55 gcampbell Chapter 7
Daniel LIn Chapter 79 geekonaut Chapters 61, 63 and 89
daniellmb Chapters 1 and 42 georg Chapter 42
daniphilia Chapter 102 George Bailey Chapters 12, 13, 30 and 90
DarkKnight Chapters 19 and 60 GingerPlusPlus Chapter 99
dauruy Chapter 12 gman Chapters 1, 5 and 29
Dave Sag Chapters 42 and 100 gnerkus Chapter 11
David Archibald Chapter 1 GOTO 0 Chapters 7, 67 and 78
David G. Chapters 1 and 42 Grundy Chapter 10
David Knipe Chapter 56 Guybrush Threepwood Chapter 22
Davis Chapters 14, 19, 59 and 62 H. Pauwelyn Chapters 1 and 65
DawnPaladin Chapters 5, 59 and 99 hairboat Chapter 19
Deepak Bansal Chapter 99 Hans Strausl Chapters 3 and 12
Denys Séguret Chapter 104 hansmaad Chapter 12
Derek 朕會功夫 Chapter 35 Hardik Kanjariya ツ Chapters 12, 14, 46 and 47
DevDig Chapter 62 harish gadiya Chapter 104
Devid Farinelli Chapters 1 and 99 haykam Chapters 1, 5, 7 and 101
devlin carnate Chapter 42 Hayko Koryun Chapter 14
Diego Molina Chapter 59 HC_ Chapter 64
dns_nx Chapter 12 HDT Chapter 43
Domenic Chapters 12 and 49 Hendry Chapter 91
DontVoteMeDown Chapter 1 Henrique Barcelos Chapters 42 and 56
Downgoat Chapters 73 and 96 Hi I'm Frogatto Chapter 7
Dr. Cool Chapter 90 hiby Chapter 33
Dr. J. Testington Chapter 12 hindmost Chapters 14 and 29
Drew Chapter 14 hirnwunde Chapter 5
dunnza Chapter 42 hirse Chapter 36
Durgpal Singh Chapters 19 and 42 HopeNick Chapters 15 and 85

[Link] – JavaScript® Notes for Professionals 465 [Link] – JavaScript® Notes for Professionals 466
Hunan Rostomyan Chapter 12 Just a student Chapters 5 and 74
I am always right Chapter 83 K48 Chapters 1, 9, 10, 33, 42 and 99
Iain Ballard Chapter 50 kamoroso94 Chapters 8, 14, 19 and 64
Ian Chapters 10, 19 and 35 kanaka Chapter 61
iBelieve Chapters 55 and 57 kapantzak Chapters 20 and 62
Igor Raush Chapters 10, 41, 42, 57 and 62 Karuppiah Chapter 1
Inanc Gumus Chapters 1, 5 and 81 Kayce Basques Chapter 63
inetphantom Chapter 1 Keith Chapters 81 and 82
Ishmael Smyrnow Chapter 12 Kemi Chapter 69
Isti115 Chapter 12 kevguy Chapters 62 and 63
iulian Chapter 15 Kevin Katzke Chapter 10
Ivan Chapter 36 Kevin Law Chapter 19
ivarni Chapter 22 khawarPK Chapter 10
JF Chapters 14, 58, 59, 89 and 90 Kit Grose Chapter 54
jabacchetta Chapter 62 Knu Chapters 10, 11, 13, 14, 18, 35, 36, 97 and 99
James Donnelly Chapter 32 Kousha Chapter 10
James Long Chapter 12 Kyle Blake Chapters 10 and 12
Jamie Chapter 10 L Bahr Chapters 10, 37, 66 and 102
Jan Pokorný Chapter 13 [Link] Chapter 42
Jason Park Chapter 12 Li357 Chapter 106
Jay Chapters 19 and 22 Liam Chapter 17
JBCP Chapters 3 and 42 Lisa Gagarina Chapter 65
jbmartinez Chapter 19 LiShuaiyuan Chapter 35
jchavannes Chapter 30 Little Child Chapter 41
jchitel Chapter 42 little pootis Chapter 1
JCOC611 Chapter 40 Louis Barranqueiro Chapters 13, 35 and 65
JDB Chapter 19 Luís Hendrix Chapters 10, 60 and 104
Jean Lourenço Chapter 19 Luc125 Chapters 7 and 12
Jef Chapter 106 luisfarzati Chapter 42
Chapters 1, 10, 12, 13, 14, 19, 22, 27, 33, 35, 36, 50, 51, 53, 54, 55, 62, 71, 94 M. Erraysy Chapter 12
Jeremy Banks
and 97 Maciej Gurban Chapters 12 and 65
Jeremy J Starcher Chapter 12 Madara Uchiha Chapters 19, 20, 59, 60, 81 and 82
Jeroen Chapters 1 and 11 maheeka Chapter 9
JimmyLv Chapter 81 maioman Chapters 19 and 42
Jinw Chapter 79 Marco Bonelli Chapters 3, 53 and 96
jisoo Chapter 12 Marco Scabbiolo Chapters 3, 10, 13, 17, 20, 27, 30, 42, 46, 56, 57, 68, 69, 81 and 90
jitendra varshney Chapter 1 Marina K. Chapters 10 and 104
Jivings Chapters 10, 35, 50 and 55 mark Chapters 19 and 56
jkdev Chapters 3, 10, 12, 18, 30, 35, 36, 39 and 56 Mark Schultheiss Chapters 5 and 99
JKillian Chapter 31 mash Chapter 10
jmattheis Chapter 1 MasterBob Chapters 1, 19, 24, 25 and 81
John Chapter 13 Matas Vaitkevicius Chapters 1, 6 and 42
John Archer Chapter 99 Mathias Bynens Chapter 1
John C Chapter 8 Matt Lishman Chapter 57
John Oksasoglu Chapter 28 Matt S Chapter 31
John Slegers Chapters 1, 8, 12, 35, 42, 53 and 62 Mattew Whitt Chapter 42
John Syrinek Chapters 29 and 68 Matthew Crumley Chapters 18, 67, 84 and 104
Jonas W. Chapter 13 mauris Chapters 33 and 56
Jonathan Lam Chapters 1, 7, 29 and 45 Max Alcala Chapters 12, 19, 41 and 56
Jonathan Walters Chapters 18, 27 and 31 Maximillian Laumeister Chapter 42
Joseph Chapters 19 and 42 Md. Mahbubul Haque Chapter 13
Joshua Kleveter Chapters 1 and 25 MEGADEVOPS Chapter 1
Junbang Huang Chapter 76 MegaTom Chapter 11

[Link] – JavaScript® Notes for Professionals 467 [Link] – JavaScript® Notes for Professionals 468
Meow Chapters 7, 11, 14, 19, 59 and 62 Ozan Chapter 75
metal03326 Chapters 92 and 99 oztune Chapters 5, 18, 55 and 57
Michal Pietraszko Chapter 17 [Link] Chapter 62
Michał Perłakowski Chapters 1, 35, 38, 43, 76, 77 and 81 PageYe Chapter 10
Michiel Chapter 12 Pankaj Upadhyay Chapter 62
Mijago Chapter 97 Parvez Rahaman Chapters 30 and 72
Mike C Chapters 10, 11, 12, 13, 18, 19, 37, 57 and 65 patrick96 Chapter 42
Mike McCaughan Chapters 3, 8, 9, 12, 13, 15 and 42 Paul S. Chapters 7, 10, 19, 27, 31 and 62
Mikhail Chapters 5, 7, 12, 14, 33, 39, 45, 55 and 58 Pawel Dubiel Chapters 17 and 59
Mikki Chapter 97 PedroSouki Chapters 23 and 65
Mimouni Chapters 1 and 12 pensan Chapter 14
miquelarranz Chapter 89 Peter Bielak Chapter 94
Mobiletainment Chapter 89 Peter G Chapter 5
Mohamed El Chapter 55 Peter LaBanca Chapter 1
monikapatel Chapter 5 Peter Olson Chapter 13
Morteza Tourani Chapter 12 Peter Seliger Chapter 22
Motocarota Chapter 42 phaistonian Chapter 12
Mottie Chapters 10, 12, 14 and 18 Phil Chapter 13
murrayju Chapter 81 pietrovismara Chapter 89
n4m31ess_c0d3r Chapter 10 Pinal Chapters 19, 42 and 55
Nachiketha Chapter 63 pinjasaur Chapter 4
Naeem Shaikh Chapters 42 and 69 PitaJ Chapter 65
nalply Chapters 10 and 42 Pranav C Balan Chapter 12
Naman Sancheti Chapters 1 and 50 programmer5000 Chapter 95
nasoj1100 Chapter 12 ProllyGeek Chapters 20, 65 and 79
Nathan Tuggy Chapter 7 pzp Chapters 8, 30 and 71
naveen Chapter 65 Qianyue Chapters 12, 60 and 62
ndugger Chapters 17, 19, 22 and 62 QoP Chapters 12, 19, 22, 35, 42 and 57
Neal Chapters 12, 13, 19, 22, 27, 36 and 62 Quartz Fog Chapters 31 and 54
Nelson Teixeira Chapter 12 Quill Chapters 7 and 42
nem035 Chapters 10, 12, 20, 60 and 65 Racil Hilan Chapter 34
nhahtdh Chapter 31 Rafael Dantas Chapter 12
Nhan Chapters 12 and 35 Rahul Arora Chapters 20 and 29
ni8mr Chapters 10 and 18 Rajaprabhu Aravindasamy Chapter 13
nicael Chapters 11, 42, 44 and 99 Rajesh Chapter 10
Nicholas Montaño Chapter 102 Rakitić Chapter 1
Nick Chapter 1 RamenChef Chapter 14
Nick Larsen Chapter 61 Randy Chapters 19 and 50
NickHTTPS Chapter 63 Raphael Schweikert Chapter 10
Nikita Kurtin Chapters 99 and 104 rfsbsb Chapter 67
Nikola Lukic Chapters 58 and 101 richard Chapter 37
Nina Scholz Chapters 12 and 40 Richard Hamilton Chapters 7, 10, 12, 14, 31, 48 and 99
Nisarg Chapter 66 Richard Turner Chapter 62
npdoty Chapter 71 riyaz Chapter 42
nseepana Chapter 104 Roamer Chapter 42
Nuri Tasdemir Chapters 42 and 62 Rohit Jindal Chapters 30 and 40
nus Chapter 19 Rohit Kumar Chapter 57
nylki Chapter 1 Rohit Shelhalkar Chapter 5
Oriol Chapter 10 Roko C. Buljan Chapters 4, 7, 12, 14, 33, 44, 45, 89 and 106
Ortomala Lokni Chapter 10 rolando Chapters 12, 13, 18 and 19
orvi Chapters 1 and 18 rolfedh Chapter 19
Oscar Jara Chapter 10 Ronen Ness Chapters 12, 19, 32 and 43
Ovidiu Dolha Chapter 93 ronnyfm Chapter 1

[Link] – JavaScript® Notes for Professionals 469 [Link] – JavaScript® Notes for Professionals 470
royhowie Chapter 35 teppic Chapter 42
Ruhul Amin Chapter 41 Thomas Leduc Chapter 31
rvighne Chapters 13, 19, 22, 45 and 88 Thriggle Chapters 1 and 19
Ry Chapter 31 Ties Chapter 74
S Willis Chapter 8 tiffon Chapter 101
sabithpocker Chapter 7 Tim Chapter 30
Sagar V Chapters 19, 29 and 61 Tim Rijavec Chapter 86
Sammy I. Chapter 20 Tiny Giant Chapter 36
Sandro Chapter 12 tjfwalker Chapter 11
SarathChandra Chapter 11 tnga Chapter 1
Saroj Sasmal Chapter 1 Tolen Chapter 1
Scimonster Chapter 24 Tomás Cañibano Chapters 7 and 59
Sean Vieira Chapter 27 Tomboyo Chapter 17
SeanKendle Chapter 1 tomturton Chapter 65
SeinopSys Chapters 1 and 96 ton Chapter 56
SEUH Chapter 61 Tot Zam Chapter 36
SgtPooki Chapter 97 towerofnix Chapter 38
shaedrich Chapter 70 transistor09 Chapter 33
shaN Chapter 90 Traveling Tech Guy Chapter 12
Shawn Chapter 60 Travis Acton Chapter 1
Shog9 Chapters 19 and 59 Trevor Clarke Chapters 8, 14 and 46
Shrey Gupta Chapter 12 trincot Chapters 19 and 35
Sibeesh Venu Chapter 56 Tschallacka Chapter 65
sielakos Chapters 12, 19 and 50 Tushar Chapters 1 and 31
Siguza Chapter 40 user2314737 Chapters 8, 12, 14, 19, 35, 50, 59 and 104
simonv Chapter 29 user3882768 Chapter 11
SirPython Chapter 5 Vaclav Chapter 12
smallmushroom Chapter 18 VahagnNikoghosian Chapters 12 and 104
Spencer Wieczorek Chapters 7, 10, 15 and 65 Vasiliy Levykin Chapters 3, 10 and 19
spirit Chapter 35 Ven Chapters 1, 10 and 42
splay Chapters 7, 10 and 40 Victor Bjelkholm Chapter 5
Sreekanth Chapter 89 VisioN Chapters 12 and 52
ssc Chapter 1 Vlad Nicula Chapter 62
stackoverfloweth Chapter 13 Vladimir Gabrielyan Chapter 42
Stephen Leppik Chapter 40 wackozacko Chapters 42 and 60
Steve Greatrex Chapter 42 WebBrother Chapter 65
Stewartside Chapter 14 whales Chapters 8 and 18
Stides Chapter 60 Will Chapter 62
still_learning Chapters 14 and 94 Wladimir Palant Chapters 5, 10, 42 and 62
styfle Chapter 20 Wolfgang Chapter 30
sudo bangbang Chapter 42 wuxiandiejia Chapters 7, 12 and 43
Sumit Chapter 11 XavCo7 Chapters 1, 11, 12, 13, 18, 40, 50, 63, 64, 71, 90 and 92
Sumner Evans Chapters 99 and 102 xims Chapter 1
Sumurai8 Chapters 8, 10, 13, 14, 17, 35 and 56 YakovL Chapter 56
Sunny R Gupta Chapter 56 ymz Chapter 19
svarog Chapters 7, 17, 43, 80 and 90 Yosvel Quintero Chapters 1, 5, 12, 13, 14, 17, 22, 34, 35, 42 and 104
Sverri M. Olsen Chapter 1 Yumiko Chapter 33
SZenC Chapters 1, 10, 11, 13, 14, 18, 19, 30, 31, 32, 36, 59, 62, 80 and 97 Yury Fedorov Chapters 1 and 42
Tacticus Chapter 96 Zack Harley Chapter 56
tandrewnichols Chapter 19 Zaga Chapter 31
Tanmay Nehete Chapter 19 Zaz Chapter 42
Taras Lukavyi Chapter 59 zb' Chapter 42
tcooc Chapter 42 zer00ne Chapter 12

[Link] – JavaScript® Notes for Professionals 471 [Link] – JavaScript® Notes for Professionals 472
ZeroBased_IX
Zhegan
Chapter 12
Chapter 35 You may also like
zhirzh Chapters 12, 14 and 19
Zirak Chapter 56
[Link] Chapter 42
zur4ik Chapters 19 and 62
zurfyx Chapter 70
Zze Chapter 1

[Link] – JavaScript® Notes for Professionals 473

You might also like