JavaScript #javascript
Table of Contents 1 2 About 2 Chapter 1: Getting started with JavaScript 2 3 Remarks Versions 3 Examples 4 Using the DOM API 4 Using console.log() 4 5 Introduction 5 Getting Started 6 Logging variables 6 Placeholders 7 Logging Objects 7 Logging HTML elements 7 End Note 8 8 Using window.alert() 8 Notes 9 9 Using window.prompt() 10 Syntax 11 Examples 12 Notes 12 Using the DOM API (with graphical text: Canvas, SVG, or image file) 12 Using window.confirm() 12 Notes Chapter 2: .postMessage() and MessageEvent 12 Syntax Parameters 12 Examples Getting Started What is .postMessage(), when and why do we use it
Sending messages 12 Receiving, Validating and Processing Messages 13 Chapter 3: AJAX 15 15 Introduction 15 Remarks 15 Examples 15 Using GET and no parameters 15 Sending and Receiving JSON Data via POST 16 Displaying the top JavaScript questions of the month from Stack Overflow's API 17 Using GET with parameters 17 Check if a file exists via a HEAD request 18 Add an AJAX preloader 19 Listening to AJAX events at a global level 20 Chapter 4: Anti-patterns 20 Examples 20 Chaining assignments in var declarations. 21 Chapter 5: Arithmetic (Math) 21 Remarks 21 Examples 21 Addition (+) 22 Subtraction (-) 22 Multiplication (*) 22 Division (/) 23 Remainder / Modulus (%) 24 Using modulus to obtain the fractional part of a number 24 Incrementing (++) 24 Decrementing (--) 25 Common Uses 25 Exponentiation (Math.pow() or **) 26 Use Math.pow to find the nth root of a number. 26 Constants 27 Trigonometry
Sine 27 Cosine 28 Tangent 28 28 Rounding 29 Rounding 29 Rounding up 29 Rounding down 29 Truncating 30 Rounding to decimal places 31 Random Integers and Floats 31 Bitwise operators 31 Bitwise or 32 Bitwise and 32 Bitwise not 32 Bitwise xor (exclusive or) 32 Bitwise left shift 32 Bitwise right shift >> (Sign-propagating shift) >>> (Zero-fill right shift) 33 Bitwise assignment operators 34 Get Random Between Two Numbers 34 Random with gaussian distribution 35 Ceiling and Floor 36 Math.atan2 to find direction 36 Direction of a vector 36 Direction of a line 36 Direction from a point to another point 36 Sin & Cos to create a vector given direction & distance 37 Math.hypot 37 Periodic functions using Math.sin 39 Simulating events with different probabilities 40 Little / Big endian for typed arrays when using bitwise operators 41 Getting maximum and minimum
Getting maximum and minimum from an array: 41 Restrict Number to Min/Max Range 42 Getting roots of a number 42 42 Square Root 42 Cube Root 42 Finding nth-roots 43 Chapter 6: Arrays 43 Syntax 43 Remarks 43 Examples 43 44 Standard array initialization 44 Array spread / rest 45 Spread operator 45 Rest operator 46 Mapping values 47 Filtering values 47 47 Filter falsy values 48 Another simple example 48 49 Iteration 49 A traditional for-loop 49 Using a traditional for loop to loop through an array 50 A while loop 50 for...in 51 for...of 51 Array.prototype.keys() 52 Array.prototype.forEach() 52 Array.prototype.every 54 Array.prototype.some Libraries Filtering Object Arrays Joining array elements in a string
Converting Array-like Objects to Arrays 54 What are Array-like Objects? 54 Convert Array-like Objects to Arrays in ES6 55 Convert Array-like Objects to Arrays in ES5 55 Modifying Items During Conversion 56 Reducing values 57 Array Sum 57 Flatten Array of Objects 57 Map Using Reduce 58 Find Min or Max Value 58 Find Unique Values 59 59 Logical connective of values 60 Concatenating Arrays 62 Append / Prepend items to Array 62 Unshift 62 Push 62 Object keys and values to array 63 Sorting multidimensional array 63 Removing items from an array 63 Shift 64 Pop 64 Splice 65 Delete 65 Array.prototype.length 65 Reversing arrays 66 Remove value from array 66 Checking if an object is an Array 67 Sorting Arrays 69 Shallow cloning an array 70 Searching an Array 70 FindIndex 70 Removing/Adding elements using splice()
Array comparison 71 Destructuring an array 72 Removing duplicate elements 72 Removing all elements 73 Method 1 73 Method 2 74 Method 3 74 Using map to reformat objects in an array 74 Merge two array as key value pair 75 Convert a String to an Array 76 Test all array items for equality 76 Copy part of an Array 77 begin 77 end 77 Example 1 77 Example 2 77 78 Finding the minimum or maximum element 79 Flattening Arrays 79 2 Dimensional arrays 79 Higher Dimension Arrays 80 Insert an item into an array at a specific index 80 The entries() method 82 Chapter 7: Arrow Functions 82 Introduction 82 Syntax 82 Remarks 82 Examples 82 Introduction 83 Lexical Scoping & Binding (Value of \"this\") 84 Arguments Object 84 Implicit Return 85 Explicit Return
Arrow functions as a constructor 85 Chapter 8: Async functions (async/await) 86 Introduction 86 Syntax 86 Remarks 86 Examples 86 Introduction 86 Arrow function style 87 Less indentation 87 Await and operator precedence 87 Async functions compared to Promises 88 Looping with async await 90 Simultaneous async (parallel) operations 91 93 Chapter 9: Async Iterators 93 Introduction 93 Syntax 93 Remarks 93 Useful Links 93 Examples 93 Basics 95 95 Chapter 10: Automatic Semicolon Insertion - ASI Examples 95 95 Rules of Automatic Semicolon Insertion 96 Statements affected by automatic semicolon insertion Avoid semicolon insertion on return statements 98 98 Chapter 11: Battery Status API 98 Remarks Examples 98 98 Getting current battery level 98 Is battery charging? Get time left until battery is empty
Get time left until battery is fully charged 98 Battery Events 99 Chapter 12: Behavioral Design Patterns 100 Examples 100 Observer pattern 100 Mediator Pattern 101 Command 102 Iterator 103 Chapter 13: Binary Data 106 Remarks 106 Examples 106 Converting between Blobs and ArrayBuffers 106 Convert a Blob to an ArrayBuffer (asynchronous) 106 Convert a Blob to an ArrayBuffer using a Promise (asynchronous) 106 Convert an ArrayBuffer or typed array to a Blob 107 Manipulating ArrayBuffers with DataViews 107 Creating a TypedArray from a Base64 string 107 Using TypedArrays 107 Getting binary representation of an image file 108 Iterating through an arrayBuffer 109 Chapter 14: Bitwise operators 111 Examples 111 Bitwise operators 111 Conversion to 32-bit integers 111 Two's Complement 111 Bitwise AND 111 Bitwise OR 112 Bitwise NOT 112 Bitwise XOR 113 113 Shift Operators 113 Left Shift 113 Right Shift (Sign-propagating)
Right Shift (Zero fill) 114 Chapter 15: Bitwise Operators - Real World Examples (snippets) 115 115 Examples 115 Number's Parity Detection with Bitwise AND 115 Swapping Two Integers with Bitwise XOR (without additional memory allocation) 115 Faster multiplication or division by powers of 2 117 117 Chapter 16: BOM (Browser Object Model) 117 Remarks 117 Examples 118 118 Introduction 120 Window Object Methods 120 Window Object Properties 120 120 Chapter 17: Built-in Constants 120 Examples 120 121 Operations that return NaN 122 Math library functions that return NaN 122 Testing for NaN using isNaN() 124 window.isNaN() 124 Number.isNaN() 125 null 126 undefined and null 126 Infinity and -Infinity 126 NaN 127 Number constants 128 128 Chapter 18: Callbacks 129 Examples 130 Simple Callback Usage Examples Examples with Asynchronous Functions What is a callback? Continuation (synchronous and asynchronous) Error handling and control-flow branching Callbacks and `this`
Solutions 130 Solutions: 131 Callback using Arrow function 132 Chapter 19: Classes 133 Syntax 133 Remarks 133 Examples 133 Class Constructor 134 Static Methods 134 Getters and Setters 135 Class Inheritance 136 Private Members 136 Dynamic Method Names 137 Methods 138 Managing Private Data with Classes 138 Using Symbols 138 Using WeakMaps 139 Define all methods inside the constructor 140 Using naming conventions 140 Class Name binding 140 Chapter 20: Comments 142 Syntax 142 Examples 142 Using Comments 142 Single line Comment // 142 Multi-line Comment /**/ 142 142 Using HTML comments in JavaScript (Bad practice) 145 Chapter 21: Comparison Operations 145 145 Remarks Examples 145 Logic Operators with Booleans
AND 145 OR 145 NOT 145 146 Abstract Equality (==) 146 7.2.13 Abstract Equality Comparison 146 Examples: 147 147 Relational operators (<, <=, >, >=) 148 Inequality 149 Logic Operators with Non-boolean values (boolean coercion) 149 Null and Undefined 149 150 The differences between null and undefined 150 The similarities between null and undefined 150 Using undefined 152 152 NaN Property of the Global Object 154 Checking if a value is NaN 154 Points to note 155 156 Short-circuiting in boolean operators 156 Abstract equality / inequality and type conversion 156 The Problem 156 The Solution 157 158 Empty Array 158 Equality comparison operations 159 SameValue 159 SameValueZero 160 Strict Equality Comparison 162 Abstract Equality Comparison Grouping multiple logic statements Automatic Type Conversions List of Comparison Operators Bit fields to optimise comparison of multi state data Chapter 22: Conditions
Introduction 162 Syntax 162 Remarks 163 Examples 163 163 If / Else If / Else Control 164 Switch statement 166 166 Multiple Inclusive Criteria for Cases 168 Ternary operators 169 Strategy 170 Using || and && short circuiting 170 170 Chapter 23: Console 170 Introduction 170 Syntax 171 Parameters 171 Remarks 171 172 Opening the Console 172 Chrome 173 Firefox 173 Edge and Internet Explorer 174 Safari 174 Opera 175 Compatibility 176 177 Examples 178 Tabulating values - console.table() 179 Including a stack trace when logging - console.trace() 181 Printing to a browser's debugging console 181 Other print methods Measuring time - console.time() Counting - console.count() Empty string or absence of argument Debugging with assertions - console.assert()
Formatting console output 182 Advanced styling 182 Using groups to indent output 183 184 Clearing the console - console.clear() 184 Displaying objects and XML interactively - console.dir(), console.dirxml() 187 Chapter 24: Constructor functions 187 Remarks 187 Examples 187 189 Declaring a constructor function 189 189 Chapter 25: Context (this) 189 Examples 190 191 this with simple objects 192 Saving this for use in nested functions / objects 192 Binding function context 192 this in constructor functions 192 192 Chapter 26: Cookies 192 Examples 194 194 Adding and Setting Cookies 194 Reading cookies 194 Removing cookies 194 Test if cookies are enabled 195 195 Chapter 27: Creational Design Patterns 195 Introduction 196 Remarks 197 Examples Singleton Pattern Module and Revealing Module Patterns Module Pattern Revealing Module Pattern Revealing Prototype Pattern Prototype Pattern
Factory Functions 198 Factory with Composition 199 Abstract Factory Pattern 200 Chapter 28: Custom Elements 202 Syntax 202 Parameters 202 Remarks 202 Examples 202 202 Registering New Elements 203 Extending Native Elements 204 204 Chapter 29: Data attributes 204 Syntax 204 Remarks 204 Examples 206 206 Accessing data attributes 206 206 Chapter 30: Data Manipulation 207 Examples 208 208 Extract extension from file name 208 Format numbers as money 209 Set object property given its string name 210 212 Chapter 31: Datatypes in Javascript 212 Examples 212 212 typeof 212 Getting object type by constructor name 213 Finding an object's class Chapter 32: Date Syntax Parameters Examples Get the current time and date Get the current year
Get the current month 213 Get the current day 213 Get the current hour 213 Get the current minutes 213 Get the current seconds 213 Get the current milliseconds 214 Convert the current time and date to a human-readable string 214 214 Create a new Date object 215 Exploring dates 216 216 Convert to JSON 216 Creating a Date from UTC The problem 217 217 Naive approach with WRONG results 218 Correct approach 218 Creating a Date from UTC 218 Changing a Date object 219 Avoiding ambiguity with getTime() and setTime() Convert to a string format 219 219 Convert to String 219 Convert to Time String 220 Convert to Date String 220 Convert to UTC String 220 Convert to ISO String 220 Convert to GMT String 221 Convert to Locale Date String 222 222 Increment a Date Object 222 Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC 223 Formatting a JavaScript date Formatting a JavaScript date in modern browsers How to use
Going custom 223 Chapter 33: Date Comparison 225 225 Examples Comparing Date values 225 Date Difference Calculation 226 Chapter 34: Debugging 227 Examples 227 Breakpoints 227 Debugger Statement 227 Developer Tools 227 227 Opening the Developer Tools Chrome or Firefox 227 Internet Explorer or Edge 227 Safari 228 228 Adding a breakpoint from the Developer Tools IDEs 228 228 Visual Studio Code (VSC) 228 Adding a breakpoint in VSC 228 Stepping through code 229 Automatically pausing execution 229 Interactive interpreter variables 230 Elements inspector 230 Using setters and getters to find what changed a property 231 Break when a function is called 231 Using the console 233 Chapter 35: Declarations and Assignments 233 Syntax 233 Remarks 233 Examples 233 Reassigning constants 233 Modifying constants 234 Declaring and initializing constants
Declaration 234 Data Types 234 Undefined 235 Assignment 235 Mathematic operations and assignment 236 Increment by 236 Decrement by 236 Multiply by 237 Divide by 237 Raised to the power of 237 Chapter 36: Destructuring assignment 238 Introduction 238 Syntax 238 Remarks 238 Examples 238 Destructuring function arguments 238 Renaming Variables While Destructuring 239 Destructuring Arrays 239 Destructuring Objects 240 Destructuring inside variables 241 Using rest parameters to create an arguments array 241 Default Value While Destructuring 241 Nested Destructuring 242 Chapter 37: Detecting browser 244 Introduction 244 Remarks 244 Examples 244 Feature Detection Method 244 Library Method 245 User Agent Detection 245 Chapter 38: Enumerations 247 Remarks 247
Examples 247 Enum definition using Object.freeze() 247 Alternate definition 248 Printing an enum variable 248 Implementing Enums Using Symbols 248 Automatic Enumeration Value 249 251 Chapter 39: Error Handling 251 Syntax 251 Remarks 251 Examples 251 252 Interaction with Promises 252 Error objects 254 Order of operations plus advanced thoughts 256 Error types 256 256 Chapter 40: Escape Sequences 256 Remarks 256 257 Similarity to other formats 257 Examples 257 258 Entering special characters in strings and regular expressions 258 Escape sequence types 259 259 Single character escape sequences 260 Hexadecimal escape sequences 260 4-digit Unicode escape sequences 260 Curly bracket Unicode escape sequences 260 Octal escape sequences 260 Control escape sequences Chapter 41: Evaluating JavaScript Introduction Syntax Parameters Remarks
Examples 260 Introduction 260 Evaluation and Math 261 Evaluate a string of JavaScript statements 261 262 Chapter 42: Events 262 Examples 262 263 Page, DOM and Browser loading 263 263 Chapter 43: execCommand and contenteditable 264 Syntax 264 Parameters 265 Examples 265 266 Formatting 268 Listening to Changes of contenteditable 268 Getting started 268 Copy to clipboard from textarea using execCommand(\"copy\") 268 269 Chapter 44: Fetch 269 Syntax 269 Parameters 269 Remarks 269 Examples 270 270 GlobalFetch 271 Set Request Headers 271 POST Data 271 Send cookies 271 Getting JSON data 271 Using Fetch to Display Questions from the Stack Overflow API 271 Chapter 45: File API, Blobs and FileReaders Syntax Parameters Remarks Examples Read file as string
Read file as dataURL 272 Slice a file 273 Client side csv download using Blob 273 Selecting multiple files and restricting file types 273 Get the properties of the file 274 Chapter 46: Fluent API 275 Introduction 275 Examples 275 Fluent API capturing construction of HTML articles with JS 275 Chapter 47: Functional JavaScript 278 Remarks 278 Examples 278 Accepting Functions as Arguments 278 Higher-Order Functions 278 Identity Monad 279 Pure Functions 281 Chapter 48: Functions 283 Introduction 283 Syntax 283 Remarks 283 Examples 283 Functions as a variable 283 A Note on Hoisting 286 Anonymous Function 286 286 Defining an Anonymous Function 286 Assigning an Anonymous Function to a Variable 287 Supplying an Anonymous Function as a Parameter to Another Function 287 Returning an Anonymous Function From Another Function 287 Immediately Invoking an Anonymous Function 288 Self-Referential Anonymous Functions 290 Immediately Invoked Function Expressions
Function Scoping 291 Binding `this` and arguments 292 Bind Operator 293 Binding console functions to variables 294 Function Arguments, \"arguments\" object, rest and spread parameters 294 arguments object 294 Rest parameters: function (...parm) {} 295 Spread parameters: function_name(...varb); 295 Named Functions 295 Named functions are hoisted 296 Named Functions in a recursive scenario 296 The name property of functions 298 298 Recursive Function 299 Currying 300 Using the Return Statement 301 Passing arguments by reference or value 302 Call and apply 303 Default parameters 304 305 Functions/variables as default values and reusing parameters 305 Reusing the function's return value in a new invocation's default value: 306 307 arguments value and length when lacking parameters in invocation 307 Functions with an Unknown Number of Arguments (variadic functions) 308 Get the name of a function object 310 Partial Application 310 Function Composition 310 310 Chapter 49: Generators 310 Introduction 310 Syntax Remarks Examples Generator Functions
Early iteration exit 311 Throwing an error to generator function 311 Iteration 311 Sending Values to Generator 312 Delegating to other Generator 312 Iterator-Observer interface 313 Iterator 313 Observer 313 Doing async with Generators 314 315 How does it work ? 315 Use it now 315 Async flow with generators 316 Chapter 50: Geolocation 316 Syntax 316 Remarks 316 Examples 316 Get a user's latitude and longitude 316 More descriptive error codes 317 Get updates when a user's location changes 318 Chapter 51: Global error handling in browsers 318 Syntax 318 Parameters 318 Remarks 318 Examples 318 Handling window.onerror to report all errors back to the server-side 320 Chapter 52: History 320 Syntax 320 Parameters 320 Remarks 320 Examples 320 history.replaceState()
history.pushState() 321 Load a specific URL from the history list 321 Chapter 53: How to make iterator usable inside async callback function 323 Introduction 323 Examples 323 Erroneous code, can you spot why this usage of key will lead to bugs? 323 Correct Writing 323 Chapter 54: IndexedDB 325 Remarks 325 325 Transactions 325 Examples 325 Testing for IndexedDB availability 325 Opening a database 326 Adding objects 327 Retrieving data 328 Chapter 55: Inheritance 328 Examples 328 Standard function prototype 328 Difference between Object.key and Object.prototype.key 328 New object from prototype 329 Prototypal inheritance 331 Pseudo-classical inheritance 332 Setting an Object's prototype 334 Chapter 56: Intervals and Timeouts 334 Syntax 334 Remarks 334 Examples 334 Intervals 334 Removing intervals 335 Removing timeouts 335 Recursive setTimeout 336 setTimeout, order of operations, clearTimeout
setTimeout 336 Problems with setTimeout 336 Order of operations 336 Cancelling a timeout 337 337 Intervals 339 339 Chapter 57: JavaScript Variables 339 Introduction 339 Syntax 339 Parameters 339 Remarks 339 340 h11 340 Nested Arrays 340 340 h12 340 h13 340 h14 340 341 Nested Objects 341 h15 341 h16 341 h17 342 343 Examples 343 Defining a Variable 343 Using a Variable 343 Types of Variables 343 Arrays and Objects 344 344 Chapter 58: JSON Introduction Syntax Parameters Remarks Examples Parsing a simple JSON string
Serializing a value 344 Serializing with a replacer function 345 Parsing with a reviver function 345 Serializing and restoring class instances 347 JSON versus JavaScript literals 348 Cyclic object values 350 Chapter 59: Linters - Ensuring code quality 351 Remarks 351 Examples 351 JSHint 351 ESLint / JSCS 352 JSLint 352 Chapter 60: Localization 354 Syntax 354 Parameters 354 Examples 354 Number formatting 354 Currency formatting 354 Date and time formatting 355 Chapter 61: Loops 356 Syntax 356 Remarks 356 Examples 356 Standard \"for\" loops 356 Standard usage 356 Multiple declarations 357 Changing the increment 357 Decremented loop 357 \"while\" Loops 357 Standard While Loop 357 Decremented loop 358 Do...while Loop 358
\"Break\" out of a loop 358 Breaking out of a while loop 358 Breaking out of a for loop 359 359 \"continue\" a loop 359 Continuing a \"for\" Loop 359 Continuing a While Loop 360 360 \"do ... while\" loop 360 Break specific nested loops 361 Break and continue labels \"for ... of\" loop 361 361 Support of for...of in other collections 362 Strings 362 Sets 363 Maps Objects 363 \"for ... in\" loop 365 365 Chapter 62: Map 365 Syntax 365 Parameters 365 Remarks Examples 365 366 Creating a Map 366 Clearing a Map 366 Removing an element from a Map 367 Checking if a key exists in a Map 367 Iterating Maps 368 Getting and setting elements Getting the number of elements of a Map 369 369 Chapter 63: Memory efficiency Examples 369 Drawback of creating true private method 370 Chapter 64: Method Chaining
Examples 370 Method Chaining 370 Chainable object design and chaining 370 Object designed to be chainable 371 Chaining example 371 Don't create ambiguity in the return type 371 Syntax convention 372 A bad syntax 372 Left hand side of assignment 373 Summary 373 374 Chapter 65: Modals - Prompts 374 Syntax 374 Remarks 374 Examples 374 375 About User Prompts 375 Persistent Prompt Modal 376 Confirm to Delete element 377 Usage of alert() 378 Usage of prompt() 378 378 Chapter 66: Modularization Techniques 378 Examples 379 380 Universal Module Definition (UMD) 380 Immediately invoked function expressions (IIFE) 381 Asynchronous Module Definition (AMD) 382 CommonJS - Node.js 382 ES6 Modules 382 382 Using Modules 382 Chapter 67: Modules Syntax Remarks Examples Default exports
Importing with side effects 383 Defining a module 383 Importing named members from another module 384 Importing an entire module 384 Importing named members with aliases 385 Exporting multiple named members 385 Chapter 68: Namespacing 386 Remarks 386 Examples 386 Namespace by direct assignment 386 Nested Namespaces 386 Chapter 69: Navigator Object 387 Syntax 387 Remarks 387 Examples 387 Get some basic browser data and return it as a JSON object 387 Chapter 70: Notifications API 389 Syntax 389 Remarks 389 Examples 389 Requesting Permission to send notifications 389 Sending Notifications 390 Hello 390 Closing a notification 390 Notification events 390 Chapter 71: Objects 392 Syntax 392 Parameters 392 Remarks 392 Examples 393 Object.keys 393 Shallow cloning 393
Object.defineProperty 394 Read-Only property 394 Non enumerable property 395 Lock property description 395 Accesor properties (get and set) 396 Properties with special characters or reserved words 396 All-digit properties: 397 Dynamic / variable property names 397 Arrays are Objects 398 Object.freeze 399 Object.seal 400 Creating an Iterable object 401 Object rest/spread (...) 401 Descriptors and Named Properties 402 meaning of fields and their defaults 403 Object.getOwnPropertyDescriptor 404 Object cloning 404 Object.assign 405 Object properties iteration 406 Retrieving properties from an object 407 Characteristics of properties : 407 Purpose of enumerability : 407 Methods of retrieving properties : 407 Miscellaneous : 409 Convert object's values to array 409 Iterating over Object entries - Object.entries() 410 Object.values() 410 Chapter 72: Performance Tips 412 Introduction 412 Remarks 412 Examples 412 Avoid try/catch in performance-critical functions 412
Use a memoizer for heavy-computing functions 413 Benchmarking your code - measuring execution time 415 Prefer local variables to globals, attributes, and indexed values 417 Reuse objects rather than recreate 418 Example A 418 Example B 418 Limit DOM Updates 419 Initializing object properties with null 420 Be consistent in use of Numbers 421 Chapter 73: Promises 423 Syntax 423 Remarks 423 Examples 423 Promise chaining 423 Introduction 425 States and control flow 425 Example 425 426 Delay function call 427 Waiting for multiple concurrent promises 428 Waiting for the first of multiple concurrent promises 428 \"Promisifying\" values 429 \"Promisifying\" functions with callbacks 430 Error Handling 430 Chaining 431 Unhandled rejections 432 Caveats 432 Chaining with fulfill and reject 433 Synchronously throwing from function that should return a promise 433 Return a rejected promise with the error 434 Wrap your function into a promise chain 434 Reconciling synchronous and asynchronous operations 435 Reduce an array to chained promises
forEach with promises 436 Performing cleanup with finally() 437 Asynchronous API request 437 Using ES2017 async/await 438 Chapter 74: Prototypes, objects 440 Introduction 440 Examples 440 Creation and initialising Prototype 440 Chapter 75: Proxy 442 Introduction 442 Syntax 442 Parameters 442 Remarks 442 Examples 442 Very simple proxy (using the set trap) 442 Proxying property lookup 443 Chapter 76: Regular expressions 444 Syntax 444 Parameters 444 Remarks 444 Examples 444 Creating a RegExp Object 444 Standard Creation 444 Static initialization 445 445 RegExp Flags 445 Matching With .exec() 445 Match Using .exec() 446 Loop Through Matches Using .exec() 446 Check if string contains pattern using .test() 446 Using RegExp With Strings 446 Match with RegExp 447 Replace with RegExp
Split with RegExp 447 Search with RegExp 447 447 Replacing string match with a callback function 448 RegExp Groups 448 Capture 448 Non-Capture 449 Look-Ahead 449 Using Regex.exec() with parentheses regex to extract matches of a string 451 451 Chapter 77: requestAnimationFrame 451 Syntax 451 Parameters 452 Remarks 452 Examples 453 454 Use requestAnimationFrame to fade in element 455 Cancelling an Animation 455 Keeping Compatability 455 455 Chapter 78: Reserved Keywords 455 Introduction 455 Examples 455 456 Reserved Keywords 457 JavaScript has a predefined collection of reserved keywords which you cannot use as variab 458 ECMAScript 1 461 ECMAScript 2 461 ECMAScript 5 / 5.1 461 ECMAScript 6 / ECMAScript 2015 461 461 Identifiers & Identifier Names Chapter 79: Same Origin Policy & Cross-Origin Communication Introduction Examples Ways to circumvent Same-Origin Policy Method 1: CORS
Method 2: JSONP 461 Safe cross-origin communication with messages 462 Example of Window communicating with a children frame 462 464 Chapter 80: Scope 464 Remarks 464 Examples 464 Difference between var and let 465 Global variable declaration 465 Re-declaration 466 Hoisting 466 Closures 467 Private data 468 Immediately-invoked function expressions (IIFE) 468 Hoisting 468 What is hoisting? 470 Limitations of Hoisting 471 472 Using let in loops instead of var (click handlers example) 472 Method invocation 472 Anonymous invocation 473 Constructor invocation 473 Arrow function invocation 475 Apply and Call syntax and invocation. 476 Bound invocation 476 Chapter 81: Screen Examples 476 476 Getting the screen resolution 476 Getting the “available” area of the screen 476 Getting color information about the screen 476 Window innerWidth and innerHeight Properties Page width and height 478 Chapter 82: Security issues
Introduction 478 Examples 478 478 Reflected Cross-site scripting (XSS) 478 479 headings 479 Mitigation: 480 480 Persistent Cross-site scripting (XSS) 481 Mitigation 481 481 Persistent Cross-site scripting from JavaScript string literals 482 Mitigation: 483 483 Why scripts from other people can harm your website and its visitors 483 Evaled JSON injection 483 Mitagation 483 Chapter 83: Selection API 483 Syntax 483 Parameters 484 Remarks 485 Examples 485 485 Deselect everything that is selected 485 Select the contents of an element 485 Get the text of the selection 486 487 Chapter 84: Server-sent events 487 Syntax 487 Examples 487 487 Setting up a basic event stream to the server Closing an event stream Binding event listeners to EventSource Chapter 85: Set Introduction Syntax Parameters Remarks
Examples 488 Creating a Set 488 Adding a value to a Set 488 Removing value from a set 488 Checking if a value exist in a set 488 Clearing a Set 489 Getting set length 489 Converting Sets to arrays 489 Intersection and difference in Sets 490 Iterating Sets 490 491 Chapter 86: Setters and Getters 491 Introduction 491 Remarks 491 Examples 491 491 Defining an Setter/Getter in a Newly Created Object 492 Defining a Setter/Getter Using Object.defineProperty 493 Defining getters and setters in ES6 class 493 493 Chapter 87: Strict mode 493 Syntax 493 Remarks 493 Examples 494 495 For entire scripts 496 For functions 497 Changes to global properties 497 Changes to properties 497 Behaviour of a function's arguments list 499 Duplicate Parameters 499 Function scoping in strict mode 499 Non-Simple parameter lists Chapter 88: Strings Syntax Examples
Basic Info and String Concatenation 499 Concatenating Strings 499 String Templates 500 500 Escaping quotes 501 Reverse String 502 Explanation 503 Trim whitespace 503 Substrings with slice 503 Splitting a string into an array 503 Strings are unicode 504 Detecting a string 505 Comparing Strings Lexicographically 505 String to Upper Case 506 String to Lower Case 506 Word Counter 506 Access character at index in string 507 String Find and Replace Functions 507 indexOf( searchString ) and lastIndexOf( searchString ) 507 includes( searchString, start ) 507 replace( regexp|substring, replacement|replaceFunction ) 508 Find the index of a substring inside a string 508 String Representations of Numbers 509 Repeat a String 510 Character code 511 Chapter 89: Symbols 511 Syntax 511 Remarks 511 Examples 511 Basics of symbol primitive type 511 Converting a symbol into a string 512 Using Symbol.for() to create global, shared symbols 513 Chapter 90: Tail Call Optimization
Syntax 513 Remarks 513 Examples 513 513 What is Tail Call Optimization (TCO) 514 Recursive loops 515 515 Chapter 91: Template Literals 515 Introduction 515 Syntax 515 Remarks 515 Examples 515 516 Basic interpolation and multiline strings 517 Raw strings 517 Tagged strings 519 Templating HTML With Template Strings 519 Introduction 519 520 Chapter 92: The Event Loop 521 Examples 521 521 The event loop in a web browser 521 Asynchronous operations and the event loop 521 522 Chapter 93: Tilde ~ 522 Introduction 523 Examples 523 523 ~ Integer 524 ~~ Operator 524 Converting Non-numeric values to Numbers Shorthands indexOf can be re-written as ~ Decimal Chapter 94: Timestamps Syntax
Remarks 524 Examples 524 524 High-resolution timestamps 524 Low-resolution timestamps 524 Support for legacy browsers 525 Get Timestamp in Seconds 526 526 Chapter 95: Transpiling 526 Introduction 526 Remarks 526 Examples 526 527 Introduction to Transpiling 527 529 Examples 529 Start using ES6/7 with Babel 529 Quick setup of a project with Babel for ES6/7 support 529 529 Chapter 96: Unary Operators 529 Syntax 529 Examples 529 530 The unary plus operator (+) 530 530 Syntax: 530 Returns: 531 Description 531 Examples: 531 531 The delete operator 532 Syntax: Returns: Description Examples: The typeof operator Syntax: Returns: Examples:
The void operator 533 Syntax: 533 Returns: 533 Description 533 Examples: 533 534 The unary negation operator (-) 534 Syntax: 534 Returns: 534 Description 534 Examples: 535 535 The bitwise NOT operator (~) 535 Syntax: 535 Returns: 535 Description 536 Examples: 536 536 The logical NOT operator (!) 536 Syntax: 537 Returns: 537 Description 539 Examples: 539 539 Overview 540 Chapter 97: Unit Testing Javascript 544 544 Examples 544 Basic Assertion 545 Unit Testing Promises with Mocha, Sinon, Chai and Proxyquire 545 Chapter 98: Using javascript to get/set CSS custom variables Examples How to get and set CSS variable property values. Chapter 99: Variable coercion/conversion Remarks
Examples 545 Converting a string to a number 545 Converting a number to a string 546 Double Negation (!!x) 546 Implicit conversion 546 Converting a number to a boolean 547 Converting a string to a boolean 547 Integer to Float 547 Float to Integer 548 Convert string to float 548 Converting to boolean 548 Convert an array to a string 549 Array to String using array methods 549 Primitive to Primitive conversion table 550 552 Chapter 100: Vibration API 552 Introduction 552 Syntax 552 Remarks 552 Examples 552 552 Check for support 553 Single vibration 554 Vibration patterns 554 554 Chapter 101: WeakMap 554 Syntax 554 Remarks 554 Examples 554 555 Creating a WeakMap object 555 Getting a value associated to the key 555 Assigning a value to the key Checking if an element with the key exists Removing an element with the key Weak reference demo
Chapter 102: WeakSet 557 Syntax 557 Remarks 557 Examples 557 Creating a WeakSet object 557 Adding a value 557 Checking if a value exists 557 Removing a value 558 Chapter 103: Web Cryptography API 559 Remarks 559 Examples 559 Cryptographically random data 559 Creating digests (e.g. SHA-256) 559 Generating RSA key pair and converting to PEM format 560 Converting PEM key pair to CryptoKey 561 Chapter 104: Web Storage 563 Syntax 563 Parameters 563 Remarks 563 Examples 563 Using localStorage 563 localStorage limits in browsers 564 Storage events 564 Notes 565 sessionStorage 565 Clearing storage 566 Error conditions 566 Remove Storage Item 566 Simpler way of handling Storage 567 localStorage length 567 Chapter 105: WebSockets 569 Introduction 569
Syntax 569 Parameters 569 Examples 569 569 Establish a web socket connection 569 Working with string messages 570 Working with binary messages 570 Making a secure web socket connection 571 571 Chapter 106: Workers 571 Syntax 571 Remarks 571 Examples 571 572 Register a service worker 572 Web Worker 572 A simple service worker 573 573 main.js 574 Few Things: 574 575 sw.js 577 Dedicated Workers and Shared Workers Terminate a worker Populating your cache Communicating with a Web Worker Credits
About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: javascript It is an unofficial and free JavaScript ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official JavaScript. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected] https://riptutorial.com/ 1
Chapter 1: Getting started with JavaScript Remarks JavaScript (not to be confused with Java) is a dynamic, weakly-typed language used for client-side as well as server-side scripting. JavaScript is a case-sensitive language. This means the language considers capital letters to be different from their lowercase counterparts. Keywords in JavaScript are all lowercase. JavaScript is a commonly referenced implementation of ECMAScript standard. Topics in this tag often refer to the use of JavaScript within the browser, unless otherwise stated. JavaScript files alone can't be run directly by the browser; it's necessary to embed them in an HTML document. If you have some JavaScript code you'd like to try, you can embed it in some placeholder content like this, and save the result as example.html: <!doctype html> <html> <head> <meta charset=\"utf-8\"> <title>Test page</title> </head> <body> Inline script (option 1): <script> // YOUR CODE HERE </script> External script (option 2): <script src=\"your-code-file.js\"></script> </body> </html> Versions 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 https://riptutorial.com/ 2
Version Release Date 6 2015-06-01 7 2016-06-14 8 2017-06-27 Examples Using the DOM API DOM stands for Document Object Model. It is an object-oriented representation of structured documents like XML and HTML. Setting the textContent property of an Element is one way to output text on a web page. For example, consider the following HTML tag: <p id=\"paragraph\"></p> To change its textContent property, we can run the following JavaScript: document.getElementById(\"paragraph\").textContent = \"Hello, World\"; 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> In our JavaScript, we create a new <p> tag with a textContent property of and add it at the end of the html body: var element = document.createElement('p'); element.textContent = \"Hello, World\"; document.body.appendChild(element); //add the newly created element to the DOM That will change your HTML body to the following: https://riptutorial.com/ 3
<body> <h1>Adding an element</h1> <p>Hello, World</p> </body> Note that in order to manipulate elements in the DOM using JavaScript, the JavaScript code must be run after the relevant element has been created in the document. This can be achieved by putting the JavaScript <script> tags after all of your other <body> content. Alternatively, you can also use an event listener to listen to eg. window's onload event, adding your code to that event listener will delay running your code until after the whole content on your page has been loaded. A third way to make sure all your DOM has been loaded, is to wrap the DOM manipulation code with a timeout function of 0 ms. This way, this JavaScript code is re-queued at the end of the execution queue, which gives the browser a chance to finish doing some non-JavaScript things that have been waiting to finish before attending to this new piece of JavaScript. Using console.log() Introduction All modern web browsers, NodeJs as well as almost every other JavaScript environments support writing messages to a console using a suite of logging methods. The most common of these methods is console.log(). In a browser environment, the console.log() function is predominantly used for debugging purposes. Getting Started Open up the JavaScript Console in your browser, type the following, and press Enter: console.log(\"Hello, World!\"); This will log the following to the console: In the example above, the console.log() function prints Hello, World! to the console and returns undefined (shown above in the console output window). This is because console.log() has no https://riptutorial.com/ 4
explicit return value. Logging variables console.log() can be used to log variables of any kind; not only strings. Just pass in the variable that you want to be displayed in the console, for example: var foo = \"bar\"; console.log(foo); 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'; console.log(\"thisVar:\", thisVar, \"and thatVar:\", thatVar); This will log the following to the console: Placeholders 5 You can use console.log() in combination with placeholders: var greet = \"Hello\", who = \"World\"; https://riptutorial.com/
console.log(\"%s, %s!\", greet, who); This will log the following to the console: Logging Objects Below we see the result of logging an object. This is often useful for logging JSON responses from API calls. console.log({ 'Email': '', 'Groups': {}, 'Id': 33, 'IsHiddenInUI': false, 'IsSiteAdmin': false, 'LoginName': 'i:0#.w|virtualdomain\\\\user2', 'PrincipalType': 1, 'Title': 'user2' }); 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: console.log(document.body); https://riptutorial.com/ 6
This will log the following to the console: End Note For more information on the capabilities of the console, see the Console topic. Using window.alert() The alert method displays a visual alert box on screen. The alert method parameter is displayed to the user in plain text: window.alert(message); Because window is the global object, you can call also use the following shorthand: alert(message); So what does window.alert() do? Well, let's take the following example: alert('hello, world'); In Chrome, that would produce a pop-up like this: https://riptutorial.com/ 7
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
- 486
- 487
- 488
- 489
- 490
- 491
- 492
- 493
- 494
- 495
- 496
- 497
- 498
- 499
- 500
- 501
- 502
- 503
- 504
- 505
- 506
- 507
- 508
- 509
- 510
- 511
- 512
- 513
- 514
- 515
- 516
- 517
- 518
- 519
- 520
- 521
- 522
- 523
- 524
- 525
- 526
- 527
- 528
- 529
- 530
- 531
- 532
- 533
- 534
- 535
- 536
- 537
- 538
- 539
- 540
- 541
- 542
- 543
- 544
- 545
- 546
- 547
- 548
- 549
- 550
- 551
- 552
- 553
- 554
- 555
- 556
- 557
- 558
- 559
- 560
- 561
- 562
- 563
- 564
- 565
- 566
- 567
- 568
- 569
- 570
- 571
- 572
- 573
- 574
- 575
- 576
- 577
- 578
- 579
- 580
- 581
- 582
- 583
- 584
- 585
- 586
- 587
- 588
- 589
- 590
- 591
- 592
- 593
- 594
- 595
- 596
- 597
- 598
- 599
- 600
- 601
- 602
- 603
- 604
- 605
- 606
- 607
- 608
- 609
- 610
- 611
- 612
- 613
- 614
- 615
- 616
- 617
- 618
- 619
- 620
- 621
- 622
- 623
- 624
- 625
- 626
- 627
- 628
- 629
- 630
- 1 - 50
- 51 - 100
- 101 - 150
- 151 - 200
- 201 - 250
- 251 - 300
- 301 - 350
- 351 - 400
- 401 - 450
- 451 - 500
- 501 - 550
- 551 - 600
- 601 - 630
Pages: