Javascript.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
JavaScript #javascript Table of Contents About 1 Chapter 1: Getting started with JavaScript 2 Remarks 2 Versions 2 Examples 3 Using the DOM API 3 Using console.log() 4 Introduction 4 Getting Started 4 Logging variables 5 Placeholders 5 Logging Objects 6 Logging HTML elements 6 End Note 7 Using window.alert() 7 Notes 7 Using window.prompt() 8 Syntax 8 Examples 8 Notes 9 Using the DOM API (with graphical text: Canvas, SVG, or image file) 9 Using window.confirm() 10 Notes 11 Chapter 2: .postMessage() and MessageEvent 12 Syntax 12 Parameters 12 Examples 12 Getting Started 12 What is .postMessage(), when and why do we use it 12 Sending messages 12 Receiving, Validating and Processing Messages 13 Chapter 3: AJAX 15 Introduction 15 Remarks 15 Examples 15 Using GET and no parameters 15 Sending and Receiving JSON Data via POST 15 Displaying the top JavaScript questions of the month from Stack Overflow's API 16 Using GET with parameters 17 Check if a file exists via a HEAD request 17 Add an AJAX preloader 18 Listening to AJAX events at a global level 19 Chapter 4: Anti-patterns 20 Examples 20 Chaining assignments in var declarations. 20 Chapter 5: Arithmetic (Math) 21 Remarks 21 Examples 21 Addition (+) 21 Subtraction (-) 22 Multiplication (*) 22 Division (/) 22 Remainder / Modulus (%) 23 Using modulus to obtain the fractional part of a number 24 Incrementing (++) 24 Decrementing (--) 24 Common Uses 25 Exponentiation (Math.pow() or **) 25 Use Math.pow to find the nth root of a number. 26 Constants 26 Trigonometry 27 Sine 27 Cosine 28 Tangent 28 Rounding 28 Rounding 29 Rounding up 29 Rounding down 29 Truncating 29 Rounding to decimal places 30 Random Integers and Floats 31 Bitwise operators 31 Bitwise or 31 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) 32 Bitwise assignment operators 33 Get Random Between Two Numbers 34 Random with gaussian distribution 34 Ceiling and Floor 35 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 36 Math.hypot 37 Periodic functions using Math.sin 37 Simulating events with different probabilities 39 Little / Big endian for typed arrays when using bitwise operators 40 Getting maximum and minimum 41 Getting maximum and minimum from an array: 41 Restrict Number to Min/Max Range 42 Getting roots of a number 42 Square Root 42 Cube Root 42 Finding nth-roots 42 Chapter 6: Arrays 43 Syntax 43 Remarks 43 Examples 43 Standard array initialization 43 Array spread / rest 44 Spread operator 44 Rest operator 45 Mapping values 45 Filtering values 46 Filter falsy values 47 Another simple example 47 Iteration 47 A traditional for-loop 48 Using a traditional for loop to loop through an array 48 A while loop 49 for...in 49 for...of 49 Array.prototype.keys() 50 Array.prototype.forEach() 50 Array.prototype.every 51 Array.prototype.some 51 Libraries 52 Filtering Object Arrays 52 Joining array elements in a string 54 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 Logical connective of values 59 Concatenating Arrays 60 Append / Prepend items to Array 62 Unshift 62 Push 62 Object keys and values to array 62 Sorting multidimensional array 63 Removing items from an array 63 Shift 63 Pop 64 Splice 64 Delete 65 Array.prototype.length 65 Reversing arrays 65 Remove value from array 66 Checking if an object is an Array 66 Sorting Arrays 67 Shallow cloning an array 69 Searching an Array 70 FindIndex 70 Removing/Adding elements using splice() 70 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 Finding the minimum or maximum element 78 Flattening Arrays 79 2 Dimensional arrays 79 Higher Dimension Arrays 79 Insert an item into an array at a specific index 80 The entries() method 80 Chapter 7: Arrow Functions 82 Introduction 82 Syntax 82 Remarks 82 Examples 82 Introduction 82 Lexical Scoping & Binding (Value of "this") 83 Arguments Object 84 Implicit Return 84 Explicit Return 85 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 Chapter 9: Async Iterators 93 Introduction 93 Syntax 93 Remarks 93 Useful Links 93 Examples 93 Basics 93 Chapter 10: Automatic Semicolon Insertion - ASI 95 Examples 95 Rules of Automatic Semicolon Insertion 95 Statements affected by automatic semicolon insertion 95 Avoid semicolon insertion on return statements 96 Chapter 11: Battery Status API 98 Remarks 98 Examples 98 Getting current battery level 98 Is battery charging? 98 Get time left until battery is empty 98 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 Shift Operators 113 Left Shift 113 Right Shift (Sign-propagating) 113 Right Shift (Zero fill) 114 Chapter 15: Bitwise Operators - Real World Examples (snippets) 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 115 Chapter 16: BOM (Browser Object Model) 117 Remarks 117 Examples 117 Introduction 117 Window Object Methods 118 Window Object Properties 118 Chapter 17: Built-in Constants 120 Examples 120 Operations that return NaN 120 Math library functions that return NaN 120 Testing for NaN using isNaN() 120 window.isNaN() 120 Number.isNaN() 121 null 122 undefined and null 122 Infinity and -Infinity 124 NaN 124 Number constants 125 Chapter 18: Callbacks 126 Examples 126 Simple Callback Usage Examples 126 Examples with Asynchronous Functions 127 What is a callback? 128 Continuation (synchronous and asynchronous) 128 Error handling and control-flow branching 129 Callbacks and `this` 130 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 Using HTML comments in JavaScript (Bad practice) 142 Chapter 21: Comparison Operations 145 Remarks 145 Examples 145 Logic Operators with Booleans 145 AND 145 OR 145 NOT 145 Abstract Equality (==) 146 7.2.13 Abstract Equality Comparison 146 Examples: 146 Relational operators (<, <=, >, >=) 147 Inequality 147 Logic Operators with Non-boolean values (boolean coercion) 148 Null and Undefined 149 The differences between null and undefined 149 The similarities between null and undefined 149 Using undefined 150 NaN Property of the Global Object 150 Checking if a value is NaN 150 Points to note 152 Short-circuiting in boolean operators 152 Abstract equality / inequality and type conversion 154 The Problem 154 The Solution 155 Empty Array 156 Equality comparison operations 156 SameValue 156 SameValueZero 156 Strict Equality Comparison 157 Abstract Equality Comparison 158 Grouping multiple logic statements 158 Automatic Type Conversions 159 List of Comparison Operators 159 Bit fields to optimise comparison of multi state data 160 Chapter 22: Conditions 162 Introduction 162 Syntax 162 Remarks 163 Examples 163 If / Else If / Else Control 163 Switch statement 164 Multiple Inclusive Criteria for Cases 166 Ternary operators 166 Strategy 168 Using || and && short circuiting 169 Chapter 23: Console 170 Introduction 170 Syntax 170 Parameters 170 Remarks 170 Opening the Console 171 Chrome 171 Firefox 171 Edge and Internet Explorer 172 Safari 172 Opera 173 Compatibility 173 Examples 174 Tabulating values - console.table() 174 Including a stack trace when logging - console.trace() 175 Printing to a browser's debugging console 176 Other print methods 177 Measuring time - console.time()