├── .gitattributes ├── 01.Variables-and-data-types └── README.md ├── 02.Operators-and-expressions └── README.md ├── 03.Conditionals-and-loops └── README.md ├── 04.Functions └── README.md ├── 05.Arrays └── README.md ├── 06.Objects └── README.md ├── 07.Events └── README.md ├── 08.DOM-manipulation └── README.md ├── 09.Callbacks └── README.md ├── 10.Asynchronous-programming └── README.md ├── 11.Closures └── README.md ├── 12.Prototypal-inheritance └── README.md ├── 13.Scoping-and-hoisting └── README.md ├── 14.Regular-expressions └── README.md ├── 15.Error-handling └── README.md ├── 16.Promises └── README.md ├── 17.ES6+-features └── README.md ├── 18.Generators-and-async-await └── README.md ├── 19.Higher-order-functions └── README.md ├── 20.Functional-programming └── README.md ├── 21.Module-pattern-and-module-loaders └── README.md ├── 22.Web-Workers └── README.md ├── 23.Service-Workers └── README.md ├── 24.Data structures-and-algorithms └── README.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md └── images ├── 1-1.jpg ├── hositing.png └── javascript.png /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-vendored=false 2 | *.md linguist-generated=false 3 | *.md linguist-documentation=false 4 | *.md linguist-detectable=true 5 | -------------------------------------------------------------------------------- /01.Variables-and-data-types/README.md: -------------------------------------------------------------------------------- 1 | ## Variables and data types 2 | 3 | Variables are used to store data in computer programs. In programming, a variable is a named container that holds a value of a particular data type. The data type determines the kind of data that can be stored in a variable and what operations can be performed on it. 4 | 5 | In JavaScript, variables are declared using the var, let, or const keywords, followed by the variable name. The var keyword has been traditionally used in JavaScript to declare variables, but the let and const keywords were introduced in ES6 and provide more control over variable scoping and immutability, respectively. 6 | 7 | **JavaScript has several built-in data types, including:** 8 | 9 | | Data Types | Description | Example 10 | | -------- | -------- | -------- | 11 | | Strings | integers and floating-point numbers | Hello Clifford 12 | | Numbers | sequences of characters | 1, 2, 3, 4 etc. 13 | | BigInt | An integer with arbitrary precision |900719925124740999n , 1n etc. 14 | | Booleans | values that can be either true or false | true, false 15 | | Null | A value representing nothing | null 16 | | Undefined | A value representing an uninitialized variable | undefined 17 | | Symbol | Data type whose instances are unique and immutable| let value = Symbol('hello'); 18 | | Objects | Collections of key-value pairs | {name: "Clifford", age: 25} 19 | | Arrays | Ordered collections of value | [1, 2, 3, "four" , "javascript"] 20 | 21 | Here, all data types except Object are primitive data types, whereas Object and Array is non-primitive. 22 | 23 | 24 | 25 | **JavaScript String** 26 | String is used to store text. In JavaScript, strings are surrounded by quotes: 27 | - Single quotes: 'Hello' 28 | - Double quotes: "Hello" 29 | - Backticks: `` 30 | 31 | For Example: 32 | 33 | ```javascript 34 | // String Example 35 | const Single-quotes = 'Hello , This single quote in javascript' 36 | const DoubleQuotes = " Hello, This double quote in javascript" 37 | const Name = Clifford 38 | const Backticks =` Hello, ${Name} This is Backticks in javascript` 39 | 40 | 41 | ``` 42 | Single quotes and double quotes are practically the same and you can use either of them.Backticks are generally used when you need to include variables or expressions into a string. This is done by wrapping variables or expressions with ${variable or expression} as shown above. 43 | 44 | 45 | **JavaScript Number** 46 | 47 | Number represents integer and floating numbers (decimals and exponential). 48 | 49 | For example 50 | ```javascript 51 | // Number Example 52 | const number1 = 2; 53 | const number2 = 2.433; 54 | const number3 = 3e5 // 3 * 10^5 55 | 56 | ``` 57 | A number type can also be +Infinity, -Infinity, and NaN (not a number). 58 | 59 | - Infinity: Represents positive infinity, which is a value greater than any other number. 60 | - Infinity: Represents negative infinity, which is a value less than any other number. 61 | - NaN: (Not a Number): Represents a value that is not a legal number. 62 | 63 | For example, 64 | 65 | ```javascript 66 | const number1 = 3/0; 67 | console.log(number1); // Infinity 68 | 69 | const number2 = -3/0; 70 | console.log(number2); // -Infinity 71 | 72 | // strings can't be divided by numbers 73 | const number3 = "abc"/3; 74 | console.log(number3); // NaN 75 | 76 | ``` 77 | It's important to note that arithmetic operations with these special number values can sometimes produce unexpected results. For example, NaN is contagious, meaning that if you perform any operation with NaN, the result will also be NaN. Additionally, dividing a non-zero number by Infinity will result in zero, and dividing zero by Infinity will result in NaN. Therefore, it's important to handle these special values with care in your JavaScript code. 78 | 79 | 80 | **JavaScript BigInt** 81 | 82 | In JavaScript, BigInt is a built-in numeric data type that represents integers with arbitrary precision. It allows you to work with very large numbers that are too big to be represented by the regular Number type. BigInt values are represented with the **n** suffix, like this: 12345678901234567890n. 83 | 84 | Here's an example of using BigInt to perform arithmetic with large integers: 85 | 86 | ```javascript 87 | const a = 12345678901234567890n; 88 | const b = 98765432109876543210n; 89 | const c = a + b; 90 | 91 | console.log(c); // Outputs "111111111111111111100n" 92 | 93 | ``` 94 | 95 | In this example, we're adding two BigInt values together to get a third BigInt value. Note that the result is also a BigInt, and it has the n suffix to indicate that it is a BigInt value. 96 | 97 | One thing to keep in mind when working with BigInt is that you cannot mix BigInt and regular Number values in arithmetic operations. For example, this code will not work as expected: 98 | 99 | ```javascript 100 | const a = 12345678901234567890n; 101 | const b = 123; 102 | 103 | const c = a + b; // This will result in an error! 104 | 105 | 106 | ``` 107 | In this example, we're trying to add a BigInt value and a regular Number value together. This will result in an error, because BigInt and Number cannot be mixed in arithmetic operations. 108 | 109 | To avoid this error, you should always use BigInt values throughout your arithmetic operations if you need to work with very large numbers. 110 | 111 | Also, it's worth noting that BigInt is a relatively new addition to JavaScript (as of ES2020), and it may not be supported in all web browsers or environments. Be sure to check the compatibility of BigInt before using it in your project. 112 | 113 | 114 | 115 | **JavaScript Boolean** 116 | In JavaScript, Boolean is a primitive data type that represents a logical value, either true or false. 117 | 118 | Boolean values are commonly used in programming to make decisions based on whether a certain condition is true or false. For example, you might use a Boolean variable to store whether a user is logged in to a website or not, or to determine whether a certain input field has been filled out by the user. 119 | 120 | In JavaScript, you can create Boolean values using the keywords true and false. 121 | For example 122 | 123 | ```javascript 124 | 125 | // javascript Boolean Example 126 | const isTrue = true; 127 | const isFalse = false; 128 | 129 | ``` 130 | You can also use comparison operators to create Boolean values 131 | 132 | ```javascript 133 | // javascript Boolean Example 134 | let age = 25; 135 | let isAdult = age >= 18; // This will evaluate to true because 25 is greater than or equal to 18 136 | 137 | 138 | ``` 139 | In addition, many JavaScript functions return Boolean values. For example, the Array.includes() method returns true if an array includes a certain value, and false otherwise: 140 | 141 | for example 142 | 143 | ```javascript 144 | // javascript Boolean Example 145 | let myArray = [1, 2, 3, 4]; 146 | let includesTwo = myArray.includes(2); // This will evaluate to true 147 | let includesFive = myArray.includes(5); // This will evaluate to false 148 | ``` 149 | 150 | 151 | **JavaScript Null** 152 | 153 | In JavaScript, null is a primitive data type that represents the intentional absence of any object value. It is often used to indicate that a variable or object does not currently have a value, or to reset a value to null when it is no longer needed. 154 | 155 | In JavaScript, null is represented by the keyword null. For example: 156 | 157 | ```javascript 158 | // javascript Null Example 159 | const nullValue = null; 160 | 161 | ``` 162 | 163 | The null value can also be used to check whether a variable or object has a value or not. For example, if you have a variable that might be empty or null, you can check it using an if statement: 164 | 165 | ```javascript 166 | // javascript Null Example 167 | let myVariable = null; 168 | 169 | if (myVariable === null) { 170 | console.log("The variable is null"); 171 | } else { 172 | console.log("The variable has a value"); 173 | } 174 | 175 | } 176 | 177 | ``` 178 | 179 | It is important to note that null is different from undefined in JavaScript. undefined means a variable has been declared but has not been assigned a value, while null represents an explicitly assigned empty value. For example: 180 | 181 | ```javascript 182 | let myVariable; 183 | 184 | console.log(myVariable); // This will output 'undefined' 185 | 186 | myVariable = null; 187 | 188 | console.log(myVariable); // This will output 'null' 189 | 190 | ``` 191 | It is also important to note that null is a primitive value, not an object, and therefore it does not have properties or methods. However, you can still use the typeof operator to determine if a value is null: 192 | 193 | ```javascript 194 | 195 | let myVariable = null; 196 | 197 | console.log(typeof myVariable); // This will output 'object' 198 | 199 | ``` 200 | 201 | **JavaScript Undefined** 202 | 203 | In JavaScript, undefined is a primitive data type that represents the absence of a value. It is often used to indicate that a variable or object has not yet been assigned a value. 204 | 205 | In JavaScript, undefined is represented by the keyword undefined. For example: 206 | 207 | ```javascript 208 | // javascript Undefined Example 209 | const undefinedValue = undefined; 210 | let undefinedValue2; 211 | console.log(undefinedValue); // This will output 'undefined' 212 | 213 | ``` 214 | 215 | 216 | 217 | **JavaScript Symbol** 218 | 219 | 220 | In JavaScript, the symbol is a primitive data type, introduced in ECMAScript 2015 (ES6). It is used to create unique identifiers that are not accessible by any other part of the program. Symbols are often used as keys in objects to ensure that the property names are unique. 221 | 222 | Symbols are created using the Symbol() function, which returns a new unique symbol each time it is called: 223 | 224 | ```javascript 225 | 226 | // javascript Symbol Example 227 | const mySymbol = Symbol(); 228 | const mySymbol2 = Symbol(); 229 | 230 | console.log(mySymbol); // This will output 'Symbol()' 231 | console.log(mySymbol2); // This will output 'Symbol()' 232 | 233 | 234 | const symbol1 = Symbol(); 235 | const symbol2 = Symbol(); 236 | 237 | console.log(symbol1 === symbol2); // false 238 | 239 | ``` 240 | 241 | Symbols can be used as keys in objects: 242 | 243 | ```javascript 244 | 245 | // javascript Symbol Example 246 | const mySymbol = Symbol('My symbol'); 247 | const myObject = {}; 248 | 249 | myObject[mySymbol] = 'Hello, world!'; 250 | 251 | console.log(myObject[mySymbol]); // 'Hello, world!' 252 | 253 | ``` 254 | 255 | 256 | **JavaScript Object** 257 | In JavaScript, an object is a data structure that allows you to store data as key-value pairs. It is a fundamental part of the language and is used extensively in web development. 258 | 259 | Objects in JavaScript are created using curly braces {} and can contain any number of properties, which are defined as key-value pairs separated by commas. The keys in an object are always strings, while the values can be any type of data, including other objects. 260 | 261 | Here's an example of an object with two properties: 262 | 263 | ```javascript 264 | // javascript Object Example 265 | const Clifford = { 266 | name: 'Clifford', 267 | age: 30, 268 | Profession : " Web Developer" 269 | 270 | }; 271 | 272 | ``` 273 | In this example, person is an object with three properties: name, Profession and age. The value of the name and Profession property is a string, and the value of the age property is a number. 274 | 275 | You can access the properties of an object using dot notation or bracket notation: 276 | 277 | ```javascript 278 | // javascript Object Example 279 | console.log(Clifford.name); // 'John Doe' 280 | console.log( console.log(Clifford.Profession); // 'Web Developer' 281 | console.log(Clifford .age ); // 30" 282 | 283 | }; 284 | ``` 285 | 286 | In addition to storing data, objects can also have methods, which are functions that are attached to the object as properties. Here's an example of an object with a method: 287 | 288 | ```javascript 289 | 290 | // javascript Object Example 291 | const person = { 292 | name: 'John Doe', 293 | age: 30, 294 | greet: function() { 295 | console.log('Hello, world!'); 296 | } 297 | }; 298 | 299 | person.greet(); // 'Hello, world!' 300 | 301 | ``` 302 | 303 | In this example, the greet method is a function that logs the string 'Hello, world!' to the console. The greet method is attached to the person object as a property, and can be accessed using dot notation. 304 | 305 | 306 | **JavaScript Array** 307 | In JavaScript, an array is a collection of values that can be of any type, including other arrays and objects. Arrays are commonly used to store lists of items, such as numbers, strings, or objects. 308 | 309 | Arrays in JavaScript are created using square brackets [] and can contain any number of values, separated by commas. Here's an example of an array with three values: 310 | 311 | ```javascript 312 | // javascript Array Example 313 | const myArray = [1, 2, 3]; 314 | 315 | ``` 316 | 317 | In this example, myArray is an array with three values: 1, 2, and 3. You can access the values in an array using bracket notation and the index of the value you want to access: 318 | 319 | You can also use the length property to get the number of values in an array: 320 | 321 | 322 | ```javascript 323 | // javascript Array Example 324 | console.log(myArray[0]); // 1 325 | console.log(myArray[1]); // 2 326 | console.log(myArray[2]); // 3 327 | 328 | ``` 329 | 330 | 331 | You can also add and remove elements from an array using built-in methods, such as push() and pop(): 332 | 333 | ```javascript 334 | const myArray = [1, 2, 3]; 335 | 336 | myArray.push(4); // adds the value 4 to the end of the array 337 | console.log(myArray); // [1, 2, 3, 4] 338 | 339 | myArray.pop(); // removes the last value from the array 340 | console.log(myArray); // [1, 2, 3] 341 | 342 | ``` 343 | 344 | Arrays also have several other built-in methods for manipulating their contents, such as shift() and unshift() for adding and removing elements from the beginning of the array, and splice() for adding or removing elements at any position in the array. 345 | 346 | Arrays are a fundamental part of JavaScript and are used extensively in web development for handling collections of data, such as the results of a database query or a list of items to display on a page. 347 | 348 | 349 | 350 | -------------------------------------------------------------------------------- /02.Operators-and-expressions/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Operators and expressions # 3 | 4 | In computer programming, operators and expressions are used to perform various calculations and manipulations on data. 5 | Operators are symbols or keywords used to perform operations on one or more operands (values or variables). Some common operators include* 6 | **What is an Operator?** 7 | 8 | In JavaScript, an operator is a special symbol used to perform operations on operands (values and variables). For example, 9 | ```javascript 10 | 2 + 3 // the + operator is used to add two numbers (2 and 3) and the result is 5 11 | 12 | ``` 13 | 14 | ### JavaScript Operator Types ### 15 | 16 | JavaScript has the following types of operators: 17 | 18 | * **Arithmetic Operators** - used to perform arithmetic on numbers (addition, subtraction, multiplication, etc.) 19 | * **Assignment Operators** - used to assign values to variables (equal, add and assign, subtract and assign, etc.) 20 | * **Comparison Operators** - used to compare two values (equal, greater than, less than, etc.) 21 | * **Logical Operators** - used to determine the logic between variables or values (AND, OR, NOT, etc.) 22 | * **String Operators** - used to concatenate two strings (addition, addition assignment, etc.) 23 | * **Conditional (Ternary) Operator** - used as a shortcut for the if statement (ternary if, else if, else) 24 | * **Bitwise Operators** - used to perform bitwise operations on numbers (AND, OR, XOR, NOT, etc.) 25 | 26 | 27 | In JavaScript, arithmetic operators are used to perform mathematical operations on numerical values. Here are some common arithmetic operators in JavaScript: 28 | 29 | 30 | 31 | **Arithmetic Operators** 32 | 33 | * Addition Operator (+) 34 | The addition operator adds two or more numbers. 35 | Example: 36 | ```javascript 37 | let x = 10; 38 | let y = 20; 39 | let z = x + y; 40 | console.log(z) // the result is 30 41 | 42 | 43 | // Example 2 44 | let x = 5; 45 | let y = 20; 46 | let z = y + x; 47 | console.log(z) // the result is 25 48 | ``` 49 | 50 | 51 | * Subtraction Operator (-) 52 | The subtraction operator subtracts one number from another. 53 | Example: 54 | ```javascript 55 | // Subtraction Operator (-) example 56 | let x = 10; 57 | let y = 20; 58 | let z = x - y; 59 | console.log(z) // the result is -10 60 | 61 | 62 | // Example 2 63 | let x = 5; 64 | let y = 20; 65 | let z = y - x; 66 | console.log(z) // the result is 15 67 | ``` 68 | 69 | 70 | * Multiplication Operator (*) 71 | The multiplication operator multiplies two or more numbers. 72 | Example: 73 | ```javascript 74 | // Multiplication Operator (*) example 75 | let x = 2; 76 | let y = 2; 77 | let z = x * y; 78 | console.log(z) // the result is 4 79 | 80 | 81 | // Example 2 82 | let x = 5; 83 | let y = 20; 84 | let z = y * x; 85 | console.log(z) // the result is 100 86 | ``` 87 | 88 | 89 | * Division Operator (/) 90 | The division operator divides one number by another. 91 | Example: 92 | ```javascript 93 | // Division Operator (/) example 94 | let x = 10; 95 | let y = 2; 96 | let z = x / y; 97 | console.log(z) // the result is 5 98 | 99 | // example 2 100 | let x = 5; 101 | let y = 20; 102 | let z = y / x; 103 | console.log(z) // the result is 4 104 | ``` 105 | 106 | * Modulus Operator or Remainder Operator (%) 107 | The modulus operator returns the remainder of a division operation. 108 | Example: 109 | ```javascript 110 | // Modulus Operator (%) example 111 | let x = 10; 112 | let y = 2; 113 | let z = x % y; 114 | console.log(z) // the result is 0 the remainder of 10 / 2 is 0 115 | 116 | // example 2 117 | let x = 5; 118 | let y = 21; 119 | let z = y % x; 120 | 121 | console.log(z) // the result is 1 the remainder of 21 / 5 is 1 122 | ``` 123 | 124 | * Increment Operator (++) 125 | The increment operator increases a number by 1. 126 | Example: 127 | ```javascript 128 | // Increment Operator (++) example 129 | let x = 10; 130 | x++; 131 | console.log(x) // the result is 11 the value of x is increased by 1 132 | 133 | // example 2 134 | let x = 5; 135 | x++; 136 | console.log(x) // the result is 6 the value of x is increased by 1 137 | ``` 138 | 139 | * Decrement Operator (--) 140 | The decrement operator decreases a number by 1. 141 | Example: 142 | ```javascript 143 | // Decrement Operator (--) example 144 | let x = 10; 145 | x--; 146 | console.log(x) // the result is 9 the value of x is decreased by 1 147 | 148 | // example 2 149 | let x = 5; 150 | x--; 151 | console.log(x) // the result is 4 the value of x is decreased by 1 152 | ``` 153 | 154 | **Assignment Operators** 155 | In JavaScript, assignment operators are used to assign values to variables. Here are some common assignment operators in JavaScript: 156 | 157 | * Simple Assignment Operator (=) 158 | The simple assignment operator assigns a value to a variable. 159 | Example: 160 | ```javascript 161 | // Simple Assignment Operator (=) example 162 | let x = 10; 163 | console.log(x) // the result is 10 164 | 165 | 166 | // example 2 167 | let x = 5; 168 | console.log(x) // the result is 5 169 | ``` 170 | 171 | * Addition Assignment Operator (+=) 172 | The addition assignment operator adds a value to a variable and assigns the result to the variable. 173 | Example: 174 | ```javascript 175 | // Addition Assignment Operator (+=) example 176 | let x = 10; 177 | x += 5; 178 | console.log(x) // the result is 15 the value of x is increased by 5 179 | 180 | // example 2 181 | let x = 5; 182 | x += 5; 183 | console.log(x) // the result is 10 the value of x is increased by 5 184 | ``` 185 | 186 | 187 | * Subtraction Assignment Operator (-=) 188 | The subtraction assignment operator subtracts a value from a variable and assigns the result to the variable. 189 | Example: 190 | ```javascript 191 | // Subtraction Assignment Operator (-=) example 192 | let x = 10; 193 | x -= 5; 194 | console.log(x) // the result is 5 the value of x is decreased by 5 195 | 196 | // example 2 197 | let x = 5; 198 | x -= 5; 199 | console.log(x) // the result is 0 the value of x is decreased by 5 200 | ``` 201 | 202 | * Multiplication Assignment Operator (*=) 203 | The multiplication assignment operator multiplies a variable by a value and assigns the result to the variable. 204 | Example: 205 | ```javascript 206 | // Multiplication Assignment Operator (*=) example 207 | let x = 10; 208 | x *= 5; 209 | console.log(x) // the result is 50 the value of x is multiplied by 5 210 | 211 | // example 2 212 | let x = 5; 213 | x *= 5; 214 | console.log(x) // the result is 25 the value of x is multiplied by 5 215 | ``` 216 | 217 | * Division Assignment Operator (/=) 218 | The division assignment operator divides a variable by a value and assigns the result to the variable. 219 | Example: 220 | ```javascript 221 | // Division Assignment Operator (/=) example 222 | let x = 10; 223 | x /= 5; 224 | console.log(x) // the result is 2 the value of x is divided by 5 225 | 226 | // example 2 227 | let x = 5; 228 | x /= 5; 229 | console.log(x) // the result is 1 the value of x is divided by 5 230 | ``` 231 | 232 | * Remainder Assignment Operator (%=) 233 | The remainder assignment operator divides a variable by a value and assigns the remainder to the variable. 234 | Example: 235 | ```javascript 236 | // Remainder Assignment Operator (%=) example 237 | let x = 10; 238 | x %= 5; 239 | console.log(x) // the result is 0 the remainder of 10 / 5 is 0 240 | 241 | // example 2 242 | let a = 10; 243 | a %= 3; // equivalent to a = a % 3; 244 | console.log(a); 245 | // the result is 1 the remainder of 10 / 3 is 1 246 | ``` 247 | Note : The commonly used assignment operator is =. You will understand other assignment operators such as +=, -=, *= etc. once we learn arithmetic operators. 248 | 249 | **Comparison Operators** 250 | In JavaScript, comparison operators are used to compare two values. 251 | Here are some common comparison operators in JavaScript: 252 | 253 | * Equal to Operator (==) 254 | The equal to operator compares two values and returns true if they are equal. 255 | Example: 256 | ```javascript 257 | // Equal to Operator (==) example 258 | let x = 10; 259 | let y = 10; 260 | console.log(x == y) // the result is true 261 | 262 | // example 2 263 | let x = 5; 264 | let y = 20; 265 | console.log(x == y) // the result is false 266 | ``` 267 | 268 | * Not Equal to Operator (!=) 269 | The not equal to operator compares two values and returns true if they are not equal. 270 | Example: 271 | ```javascript 272 | // Not Equal to Operator (!=) example 273 | let x = 10; 274 | let y = 10; 275 | console.log(x != y) // the result is false 276 | 277 | // example 2 278 | let x = 5; 279 | let y = 20; 280 | console.log(x != y) // the result is true 281 | ``` 282 | 283 | * Strict Equal to Operator (===) 284 | The strict equal to operator compares two values for equality, but also checks the data type of the values. 285 | Example: 286 | ```javascript 287 | // Strict Equal to Operator (===) example 288 | let x = 10; 289 | let y = 10; 290 | console.log(x === y) // the result is true because both x and y are numbers 291 | 292 | // example 2 293 | let x = 5; 294 | let y = '5'; 295 | console.log(x === y) // the result is false because x is a number and y is a string 296 | ``` 297 | 298 | * Strict Not Equal to Operator (!==) 299 | The strict not equal to operator compares two values for inequality, but also checks the data type of the values. 300 | Example: 301 | ```javascript 302 | // Strict Not Equal to Operator (!==) example 303 | let x = 10; 304 | let y = 10; 305 | console.log(x !== y) // the result is false because both x and y are numbers 306 | 307 | // example 2 308 | let x = 5; 309 | let y = '5'; 310 | console.log(x !== y) // the result is true because x is a number and y is a string 311 | ``` 312 | 313 | * Greater than Operator (>) 314 | The greater than operator compares two values and returns true if the value on the left is greater than the value on the right. 315 | Example: 316 | ```javascript 317 | // Greater than Operator (>) example 318 | let x = 10; 319 | let y = 5; 320 | console.log(x > y) // the result is true 321 | 322 | // example 2 323 | let x = 5; 324 | let y = 20; 325 | console.log(x > y) // the result is false 326 | ``` 327 | 328 | * Less than Operator (<) 329 | The less than operator compares two values and returns true if the value on the left is less than the value on the right. 330 | Example: 331 | ```javascript 332 | // Less than Operator (<) example 333 | let x = 10; 334 | let y = 5; 335 | console.log(x < y) // the result is false 336 | 337 | // example 2 338 | let x = 10; 339 | let y = 40; 340 | console.log(x < y) // the result is true 341 | ``` 342 | 343 | * Greater than or Equal to Operator (>=) 344 | The greater than or equal to operator compares two values and returns true if the value on the left is greater than or equal to the value on the right. 345 | Example: 346 | ```javascript 347 | // Greater than or Equal to Operator (>=) example 348 | let x = 10; 349 | let y = 10; 350 | console.log(x >= y) // the result is true because both x and y are equal 351 | 352 | // example 2 353 | let x = 5; 354 | let y = 20; 355 | console.log(x >= y) // the result is false because both x and y are equal 356 | ``` 357 | 358 | * Less than or Equal to Operator (<=) 359 | The less than or equal to operator compares two values and returns true if the value on the left is less than or equal to the value on the right. 360 | 361 | Example: 362 | ```javascript 363 | // Less than or Equal to Operator (<=) example 364 | let x = 20; 365 | let y = 20; 366 | console.log(x <= y) // the result is true because both x and y are equal 367 | 368 | // example 2 369 | let x = 50; 370 | let y = 20; 371 | console.log(x <= y) // the result is false because x is greater than y 372 | 373 | ``` 374 | 375 | **Logical Operators** 376 | Logical operators perform logical operations and return a boolean value, either true or false. 377 | * Logical AND (&& operator): It returns true if both operands are true, and false otherwise. 378 | Example: 379 | ```javascript 380 | // Logical AND (&& operator) example 381 | let x = 10; 382 | let y = 20; 383 | console.log(x < y && y > x) // the result is true because both x and y are true 384 | 385 | // example 2 386 | let x = 10; 387 | let y = 30; 388 | console.log(x < y && y < x) // the result is false because y is false 389 | ``` 390 | 391 | * Logical OR (|| operator): It returns true if either of the operands is true, and false otherwise. 392 | 393 | Example: 394 | ```javascript 395 | // Logical OR (|| operator) example 396 | let x = 10; 397 | let y = 20; 398 | console.log(x < y || y > x) // the result is true because x is true 399 | 400 | // example 2 401 | let x = 30; 402 | let y = 5; 403 | console.log(x < y || x < y) // the result is false because both x and y are false 404 | 405 | ``` 406 | 407 | * Logical NOT (! operator): It returns the opposite of the operand. If the operand is true, it returns false, and if the operand is false, it returns true. 408 | 409 | Example: 410 | ```javascript 411 | // Logical NOT (! operator) example 412 | let a = true; 413 | console.log(!a); // Output: false because a is true 414 | 415 | // example 2 416 | let b = false; 417 | console.log(!b); // Output: true because b is false 418 | ``` 419 | 420 | **String Operators** 421 | JavaScript provides several string operators that can be used to manipulate and concatenate strings: 422 | 423 | * Concatenation Operator (+): It is used to concatenate two strings. It returns a new string that is the combination of the two strings. 424 | 425 | Example: 426 | ```javascript 427 | // Concatenation Operator (+) example 428 | let firstName = 'Isaiah'; 429 | let lastName = 'Clifford'; 430 | console.log(firstName + ' ' + lastName); // Output: Isaiah Clifford 431 | ``` 432 | 433 | *(Compound concatenation assignment operator) (+=): It is used to concatenate a string to the end of another string. It returns a new string that is the combination of the two strings. 434 | 435 | Example: 436 | ```javascript 437 | // (Compound concatenation assignment operator) (+=) example 438 | let firstName = 'Isaiah'; 439 | let lastName = 'Clifford'; 440 | firstName += ' ' + lastName; 441 | console.log(firstName); // Output: Isaiah Clifford 442 | ``` 443 | 444 | *Strict equality operator (===): This operator is used to compare two strings for strict equality. It returns true if the two strings are equal, and false otherwise. 445 | 446 | Example: 447 | ```javascript 448 | // Strict equality operator (===) example 449 | let firstName = 'Isaiah'; 450 | let lastName = 'Clifford'; 451 | console.log(firstName === lastName); // Output: false because the two strings are not equal 452 | 453 | // example 2 454 | let firstName = 'Isaiah'; 455 | let lastName = 'Isaiah'; 456 | console.log(firstName === lastName); // Output: true because the two strings are equal 457 | 458 | ``` 459 | 460 | *Strict inequality operator (!==): This operator is used to compare two strings for strict inequality. It returns true if the two strings are not equal, and false otherwise. 461 | 462 | Example: 463 | ```javascript 464 | // Strict inequality operator (!==) example 465 | let firstName = 'Isaiah'; 466 | let lastName = 'Clifford'; 467 | console.log(firstName !== lastName); // Output: true because the two strings are not equal 468 | 469 | 470 | // example 2 471 | let firstName = 'Isaiah'; 472 | let lastName = 'Isaiah'; 473 | console.log(firstName !== lastName); // Output: false because the two strings are equal 474 | 475 | ``` 476 | 477 | 478 | **Conditional (Ternary) Operator** 479 | The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is as follows: 480 | ```javascript 481 | condition ? value1 : value2 482 | ``` 483 | The condition is evaluated. If it’s truthy, value1 is returned, otherwise, value2 is returned. 484 | 485 | Here's an example: 486 | ```javascript 487 | // Conditional (Ternary) Operator example 488 | let age = 20; 489 | let isAdult = age >= 18 ? "Yes" : "No"; 490 | console.log(isAdult); // Output: Yes Because age is greater than or equal to 18 491 | //In this example, if the age is greater than or equal to 18, the value of isAdult will be "Yes", otherwise it will be "No" 492 | 493 | // example 2 494 | 495 | let age = 10; 496 | let isAdult = age >= 18 ? "Yes" : "No"; 497 | console.log(isAdult); // Output: No Because age is less than 18 498 | 499 | ``` 500 | The conditional operator can be used to assign values or execute functions based on a condition in a more concise way than using an if-else statement. However, it can also make the code harder to read if it is overused or if the expressions are too complex. Therefore, it is important to use the conditional operator judiciously and only when it makes the code clearer and more concise. 501 | 502 | **Bitwise Operators** 503 | Bitwise operators perform operations on binary representations of numbers.JavaScript provides six bitwise operators that allow you to manipulate the binary representation of numbers at the bit level. 504 | 505 | * Bitwise AND (&): It returns a number where the bits of that number are set to 1 if the corresponding bits of both numbers are 1. Otherwise, it returns 0. 506 | 507 | Example: 508 | ```javascript 509 | // Bitwise AND (&) example 510 | let a = 5; // binary: 0101 511 | let b = 3; // binary: 0011 512 | console.log(a & b); // Output: 1 (binary: 0001) 513 | // example 2 514 | 515 | let a = 5; // binary: 0101 516 | let b = 7; // binary: 0111 517 | console.log(a & b); // Output: 5 (binary: 0101) 518 | 519 | ``` 520 | 521 | * Bitwise OR (|): It returns a number where the bits of that number are set to 1 if the corresponding bits of either of the two numbers are 1. Otherwise, it returns 0. 522 | 523 | Example: 524 | ```javascript 525 | // Bitwise OR (|) example 526 | let a = 5; // binary: 0101 527 | let b = 3; // binary: 0011 528 | console.log(a | b); // Output: 7 (binary: 0111) 529 | 530 | // example 2 531 | let a = 5; // binary: 0101 532 | let b = 7; // binary: 0111 533 | console.log(a | b); // Output: 7 (binary: 0111) 534 | 535 | ``` 536 | 537 | * Bitwise XOR (^): It returns a number where the bits of that number are set to 1 if the corresponding bits of either of the two numbers are 1, but not both. Otherwise, it returns 0. 538 | 539 | Example: 540 | ```javascript 541 | // Bitwise XOR (^) example 542 | let a = 5; // binary: 0101 543 | let b = 3; // binary: 0011 544 | console.log(a ^ b); // Output: 6 (binary: 0110) 545 | 546 | ``` 547 | 548 | * Bitwise NOT (~): It returns a number where the bits of that number are flipped. It returns the one’s complement of the number. 549 | 550 | Example 551 | 552 | ```javascript 553 | // Bitwise NOT (~) example 554 | let a = 5; // binary: 0101 555 | console.log(~a); // Output: -6 (binary: 1010) 556 | ``` 557 | 558 | 559 | * Left shift (<<): It returns a number where the bits of the first number are shifted to the left by the number of places specified by the second number. The bits shifted out of the left side of the number are discarded. The bits shifted in on the right side are filled with 0. 560 | 561 | 562 | Example: 563 | ```javascript 564 | 565 | // Left shift (<<) example 566 | let a = 5; // binary: 0101 567 | console.log(a << 1); // Output: 10 (binary: 1010) 568 | ``` 569 | 570 | * Right shift (>>): It returns a number where the bits of the first number are shifted to the right by the number of places specified by the second number. The bits shifted out of the right side of the number are discarded. The bits shifted in on the left side are filled with 0. 571 | 572 | Example: 573 | ```javascript 574 | // Right shift (>>) example 575 | let a = 5; // binary: 0101 576 | console.log(a >> 1); // Output: 2 (binary: 0010) 577 | ``` 578 | -------------------------------------------------------------------------------- /03.Conditionals-and-loops/README.md: -------------------------------------------------------------------------------- 1 | ## Conditionals and loops in javascript 2 | 3 | Conditionals and loops are essential building blocks of programming, and they are no different in JavaScript. In this answer, we'll take a closer look at how to use conditionals and loops in JavaScript. 4 | 5 | **Conditional statements in JavaScript** 6 | JavaScript provides two conditional statements: "if" and "switch". Here's how they work: 7 | 8 | - if statement: 9 | The if statement executes a block of code if a specified condition is true. 10 | Here's an example: 11 | 12 | ```javascript 13 | if (condition) { 14 | // code to be executed if condition is true 15 | // if the condition is true, the code inside the curly braces will be executed 16 | } 17 | 18 | let age = 18; 19 | 20 | if (age >= 18) { 21 | console.log("You are old enough to vote."); 22 | } else { 23 | console.log("You are not old enough to vote yet."); 24 | } 25 | ``` 26 | 27 | In this example, we have a variable "age" that is set to 18. The "if" statement checks if the value of "age" is greater than or equal to 18. If it is, it executes the code block inside the "if" statement and prints "You are old enough to vote.". Otherwise, it executes the code block inside the "else" statement and prints "You are not old enough to vote yet. 28 | 29 | - switch statement: 30 | 31 | The switch statement allows you to execute different actions based on different conditions. 32 | Here's an example: 33 | 34 | ```javascript 35 | switch (expression) { 36 | case x: 37 | // code block 38 | break; 39 | case y: 40 | // code block 41 | break; 42 | default: 43 | // code block 44 | 45 | let day = "Monday"; 46 | 47 | switch (day) { 48 | case "Monday": 49 | console.log("Today is Monday."); 50 | break; 51 | case "Tuesday": 52 | console.log("Today is Tuesday."); 53 | break; 54 | case "Wednesday": 55 | console.log("Today is Wednesday."); 56 | break; 57 | default: 58 | console.log("Today is some other day."); 59 | } 60 | } 61 | ``` 62 | 63 | In this example, we have a variable "day" that is set to "Monday". The "switch" statement checks the value of "day" and executes the code block that matches the value. In this case, it prints "Today is Monday. 64 | 65 | 66 | **Loops in JavaScript** 67 | JavaScript provides three types of loops: "for", "while", and "do...while". Here's how they work: 68 | 69 | - for loop: 70 | 71 | The for loop is used to execute a block of code a number of times. 72 | Here's an example: 73 | 74 | ```javascript 75 | for (statement 1; statement 2; statement 3) { 76 | // code block to be executed 77 | } 78 | 79 | for (let i = 0; i < 5; i++) { 80 | console.log(i); // 0, 1, 2, 3, 4 81 | } 82 | ``` 83 | 84 | In this example, we have a variable "i" that is set to 0. The "for" loop checks if the value of "i" is less than 5. If it is, it executes the code block inside the "for" loop and prints the value of "i". Then, it increments the value of "i" by 1 and checks the condition again. This process repeats until the value of "i" is no longer less than 5. 85 | 86 | 87 | - while loop: 88 | 89 | The while loop loops through a block of code as long as a specified condition is true. 90 | Here's an example: 91 | 92 | ```javascript 93 | while (condition) { 94 | // code block to be executed 95 | } 96 | 97 | let i = 0; 98 | 99 | while (i < 5) { 100 | console.log(i); // 0, 1, 2, 3, 4 101 | i++; 102 | } 103 | ``` 104 | 105 | In this example, we have a variable "i" that is set to 0. The "while" loop checks if the value of "i" is less than 5. If it is, it executes the code block inside the "while" loop and prints the value of "i". Then, it increments the value of "i" by 1 and checks the condition again. This process repeats until the value of "i" is no longer less than 5. 106 | 107 | 108 | 109 | - do...while loop: 110 | 111 | The do...while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. 112 | Here's an example: 113 | 114 | ```javascript 115 | do { 116 | // code block to be executed 117 | } while (condition); 118 | 119 | let i = 0; 120 | 121 | do { 122 | console.log(i); // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 123 | i++; 124 | } while (i < 10); 125 | ``` 126 | 127 | In this example, we have a variable "i" that is set to 0. The "do...while" loop executes the code block inside the "do...while" loop and prints the value of "i". Then, it increments the value of "i" by 1 and checks the condition. If the condition is true, the loop repeats. This process repeats until the value of "i" is no longer less than 10. 128 | 129 | **Conclusion** 130 | In this answer, we took a closer look at how to use conditionals and loops in JavaScript. We learned about the "if" and "switch" statements, and the "for", "while", and "do...while" loops. We also learned how to use these statements and loops in JavaScript. 131 | 132 | 133 | -------------------------------------------------------------------------------- /04.Functions/README.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Functions ## 2 | 3 | Functions are one of the fundamental concepts in programming. They let us write concise, modular, reusable, and maintainable code. They also help us obey the DRY principle when writing code. In this section , you will learn what functions are in JavaScript, how to write your own custom functions, and how to implement them. 4 | 5 | **What is a Function in JavaScript?** 6 | JavaScript functions are blocks of code that can be used repeatedly to perform a specific task. They're a crucial aspect of JavaScript programming and are widely utilized in both front-end and back-end web development. There are various ways to define functions in JavaScript, including: 7 | * **Function Declaration** 8 | * **Function Parameters** 9 | * **Function Return Value** 10 | * **Function Expression** 11 | * **Arrow Function** 12 | * **Higher-Order Function** 13 | 14 | Each of these methods has its unique features and benefits, allowing developers to write clean and efficient code. By using functions, developers can avoid repeating code and make their programs more modular and reusable. 15 | 16 | let's take it one by one in details. 17 | 18 | **Function Declaration** 19 | 20 | A function can be declared in JavaScript using the function keyword followed by the function name and a set of parentheses. The parentheses can contain a list of parameters, which are variables that are passed to the function. The function body is enclosed in curly braces. Here's an example: 21 | 22 | ```javascript 23 | 24 | // function declaration example 25 | function myFunction() { 26 | // code to be executed 27 | } 28 | 29 | // example 2 30 | function myFunction(a, b) { 31 | // code to be executed 32 | } 33 | 34 | // example 3 35 | function sayHello() { 36 | console.log('Hello!'); 37 | } 38 | ``` 39 | An important thing to note is that function declarations are hoisted. This means that you can call a function before it is declared in your code. For example: 40 | 41 | ```javascript 42 | sayHello(); // Hello! 43 | 44 | function sayHello() { 45 | console.log('Hello!'); 46 | } 47 | ``` 48 | 49 | **Function Parameters** 50 | 51 | A function can accept input values or parameters by specifying them in the parentheses after the function name. 52 | For example: 53 | 54 | ```javascript 55 | // function with parameters 56 | function myFunction(value) { 57 | console.log(value); 58 | 59 | function sayHello() { 60 | console.log('Hello!'); 61 | } 62 | 63 | 64 | // function with multiple parameters 65 | function myFunction(value1, value2) { 66 | console.log(value1, value2); 67 | 68 | function myFunction( firstName, LastName) { 69 | console.log(`Hello your Name is ${firsName} + ${lastName }`); // first name + last name 70 | } 71 | // 72 | } 73 | } 74 | ``` 75 | function parameters are optional. If a function does not have any parameters, you can still call it by using empty parentheses. For example: 76 | 77 | ```javascript 78 | function sayHello() { 79 | console.log('Hello!'); 80 | } 81 | 82 | sayHello(); // Hello! 83 | ``` 84 | 85 | 86 | **Function Return Value** 87 | A function can return a value by using the return keyword. 88 | For example: 89 | 90 | ```javascript 91 | // function with return value 92 | function myFunction(value) { 93 | return value; 94 | } 95 | 96 | function myFunction(name) { 97 | return name; 98 | } 99 | 100 | 101 | // function with multiple return values 102 | function myFunction(value1, value2) { 103 | return [value1, value2]; 104 | } 105 | 106 | 107 | function sum(a, b) { 108 | return a + b; 109 | } 110 | ``` 111 | 112 | **Function Expression** 113 | A function expression is a function that is assigned to a variable. 114 | For example: 115 | 116 | ```javascript 117 | // function expression example 118 | const myFunction = function() { 119 | // code to be executed 120 | }; 121 | 122 | const sayHello = function() { 123 | console.log('Hello!'); 124 | }; 125 | 126 | // function expression with parameters 127 | const myFunction = function(value) { 128 | // code to be executed 129 | }; 130 | 131 | const sayHello = function(name) { 132 | console.log(`Hello ${name}!`); 133 | }; 134 | 135 | // function expression with return value 136 | const myFunction = function(value) { 137 | return value; 138 | }; 139 | 140 | const sum = function(a, b) { 141 | return a + b; 142 | }; 143 | ``` 144 | 145 | **Arrow Function** 146 | 147 | An arrow function is a concise way to write a function expression. It is a shorter syntax for a function expression and does not have its own this, arguments, super, or new.target. Arrow functions are always anonymous. They cannot be used as constructors and do not have a prototype property. 148 | For example: 149 | 150 | ```javascript 151 | // arrow function example 152 | const myFunction = () => { 153 | // code to be executed 154 | }; 155 | 156 | const sayHello = () => { 157 | console.log('Hello!'); // Hello! 158 | }; 159 | 160 | // arrow function with parameters 161 | const myFunction = (value) => { 162 | // code to be executed 163 | }; 164 | 165 | const sayHello = (name) => { 166 | console.log(`Hello ${name}!`); // Hello name! 167 | }; 168 | 169 | // arrow function with return value 170 | const myFunction = (value) => { 171 | return value; 172 | console.log(value); // 5 173 | }; 174 | // call the function 175 | myFunction(5); // passing 5 to the function and we can see the value 5 in the console 176 | 177 | 178 | const sum = (a, b) => { 179 | return a + b; 180 | 181 | console.log(a + b); // 8 182 | }; 183 | 184 | // call the function 185 | sum(5, 3); // passing the value of the 5 and 3 and add it and we can see the value of 8 in the console 186 | 187 | ``` 188 | 189 | **Higher-Order Function** 190 | 191 | A higher-order function is a function that takes a function as an argument or returns a function. Higher-order functions are also known as functional programming. They are used to create abstractions and reduce code duplication. They are also used to create higher-level functions that can be used to solve complex problems. 192 | 193 | For example: 194 | 195 | ```javascript 196 | // higher-order function example 197 | function myFunction(callback) { 198 | callback(); 199 | } 200 | 201 | function applyOperation(a, b, operation) { 202 | return operation(a, b); 203 | } 204 | 205 | const result = applyOperation(5, 2, (a, b) => a * b); 206 | console.log(result); // Output: 10 207 | 208 | 209 | ``` 210 | -------------------------------------------------------------------------------- /05.Arrays/README.md: -------------------------------------------------------------------------------- 1 | ## Arrays in JavaScript ## 2 | 3 | In JavaScript, an array is a collection of elements (values or variables) stored in a single variable. An array is a special type of object that has a length property and a set of numbered properties that can hold values. 4 | 5 | Arrays in JavaScript can hold any type of value, including strings, numbers, objects, and even other arrays. The elements of an array are indexed starting at 0, so the first element of an array is at index 0, the second element is at index 1, and so on. 6 | 7 | To create an array in JavaScript, you can use square brackets [] with a list of values or variables separated by commas. 8 | For Example: 9 | 10 | ```javascript 11 | // array of alphabet with 3 elements 12 | let myArray = ["a", "b", "c"]; 13 | console.log(myArray); // output: ['a', 'b', 'c'] 14 | 15 | // array of numbers with 4 elements 16 | let myArray = [1, 2, 3, 4]; 17 | console.log(myArray); // output: [1, 2, 3, 4] 18 | 19 | // array of strings with 3 elements 20 | let myArray = ["Hello", "World", "JavaScript"]; 21 | /console.log(myArray); // output: ['Hello', 'World', 'JavaScript'] 22 | 23 | // array of objects with 2 elements 24 | let myArray = [{ name: "John" }, { name: "Doe" }]; 25 | 26 | console.log(myArray); // output: [{ name: 'John' }, { name: 'Doe' }] 27 | 28 | // array of arrays with 2 elements 29 | let myArray = [ 30 | [1, 2, 3], 31 | [4, 5, 6], 32 | ]; console.log(myArray); // output: [[1, 2, 3], [4, 5, 6]] 33 | 34 | 35 | // array of mixed types with 4 elements 36 | 37 | let myArray = ["Hello", 10, { name: "John" }, [1, 2, 3]]; 38 | console.log(myArray); // output: ['Hello', 10, { name: 'John' }, [1, 2, 3]] 39 | ``` 40 | 41 | 42 | You can also create an empty array and add elements to it later using the push() method: 43 | 44 | ```javascript 45 | // creating an empty array and adding elements to it later 46 | let myArray = []; 47 | myArray.push("Hello"); 48 | myArray.push("World"); 49 | myArray.push("JavaScript"); 50 | 51 | console.log(myArray); // output: ['Hello', 'World', 'JavaScript'] 52 | ``` 53 | 54 | You can access the elements of an array using square bracket notation with the index of the element you want to access. 55 | For example 56 | 57 | ```javascript 58 | // using square bracket notation to access the elements of an array 59 | let myArray = ["Hello", "World", "JavaScript"]; 60 | 61 | console.log(myArray[0]); // output: Hello 62 | 63 | console.log(myArray[1]); // output: World 64 | 65 | console.log(myArray[2]); // output: JavaScript 66 | ``` 67 | 68 | You can also modify the values of an array by assigning new values to its elements. 69 | For example 70 | 71 | ```javascript 72 | //modifying the values of an array 73 | let myArray = ["Hello", "World", "JavaScript"]; 74 | 75 | myArray[0] = "Hi"; 76 | myArray[1] = "Clifford"; 77 | 78 | console.log(myArray); // output: ['Hi', 'Clifford', 'JavaScript'] 79 | ``` 80 | 81 | - Arrays are dynamic: Unlike some other programming languages, arrays in JavaScript are dynamic, which means their length can be changed at any time by adding or removing elements. 82 | 83 | ```javascript 84 | // Array are dynamic example 85 | let myArray = ["Hello", "World", "JavaScript"]; 86 | 87 | myArray.push("!"); // add an element to the end of the array 88 | 89 | console.log(myArray); // output: ['Hello', 'World', 'JavaScript', '!'] 90 | // myArray now has 4 elements we have added something to the end of the array which changed the length of the array. 91 | ``` 92 | 93 | - Arrays can be used as stacks and queues: Arrays can be used as both stacks (last-in, first-out) and queues (first-in, first-out) by using the push(), pop(), shift(), and unshift() methods. 94 | 95 | **LIFO (Stack)**: 96 | ```javascript 97 | // LIFO (Stack) example 98 | 99 | // Create a new stack (empty array) 100 | let stack = []; 101 | 102 | // Add elements to the top of the stack using push() 103 | stack.push("apple"); 104 | stack.push("banana"); 105 | stack.push("cherry"); 106 | 107 | // Remove the top element of the stack using pop() 108 | let lastItem = stack.pop(); 109 | console.log(lastItem); // output : "cherry" 110 | console.log(stack); // output: ["apple", "banana"] 111 | 112 | ``` 113 | In this example, the push() method is used to add elements to the top of the stack, and the pop() method is used to remove the top element of the stack (i.e., the last item that was added). 114 | 115 | 116 | **FIFO (Queue)**: 117 | ```javascript 118 | // FIFO (Queue) example 119 | 120 | // Create a new queue (empty array) 121 | let queue = []; 122 | 123 | // Add elements to the end of the queue using push() 124 | queue.push("apple"); 125 | queue.push("banana"); 126 | queue.push("cherry"); 127 | 128 | // Remove the first element of the queue using shift() 129 | let firstItem = queue.shift(); 130 | console.log(firstItem); // output: "apple" 131 | console.log(queue); // output: ["banana", "cherry"] 132 | ``` 133 | In this example, the push() method is used to add elements to the end of the queue, and the shift() method is used to remove the first element of the queue (i.e., the item that was added first). 134 | 135 | 136 | - Arrays have many built-in methods: In addition to the push(), pop(), shift(), and unshift() methods, arrays in JavaScript have many other built-in methods, such as slice(), splice(), concat(), join(), reverse(), sort(), and more. These methods can be used to manipulate arrays in various ways. 137 | 138 | ```javascript 139 | // Array built-in methods example 140 | 141 | // Define an array of numbers 142 | let numbers = [5, 3, 8, 2, 4, 1]; 143 | 144 | // Use the slice() method to create a new array with a subset of the original array 145 | let slicedNumbers = numbers.slice(1, 4); // output: [3, 8, 2] 146 | 147 | // Use the splice() method to remove elements from the array and add new elements in their place 148 | numbers.splice(2, 2, 9, 7); // output: [5, 3, 9, 7, 4, 1] 149 | 150 | // Use the concat() method to combine two arrays into a new array 151 | let moreNumbers = [6, 0]; 152 | let combinedNumbers = numbers.concat(moreNumbers); // [5, 3, 9, 7, 4, 1, 6, 0] 153 | 154 | // Use the join() method to create a string from the elements of the array 155 | let numberString = numbers.join(" - "); // output: "5 - 3 - 9 - 7 - 4 - 1" 156 | 157 | // Use the reverse() method to reverse the order of the elements in the array 158 | numbers.reverse(); // output [1, 4, 7, 9, 3, 5] 159 | 160 | // Use the sort() method to sort the elements of the array 161 | numbers.sort(); // output: [1, 3, 4, 5, 7, 9] 162 | ``` 163 | 164 | In this example, the slice() method is used to create a new array with a subset of the original array, the splice() method is used to remove elements from the array and add new elements in their place, the concat() method is used to combine two arrays into a new array, the join() method is used to create a string from the elements of the array, the reverse() method is used to reverse the order of the elements in the array, and the sort() method is used to sort the elements of the array. These are just a few examples of the many built-in array methods available in JavaScript. 165 | 166 | 167 | * Arrays can be iterated using loops: You can iterate over the elements of an array using loops, such as for loops and while loops, or using array-specific methods, such as forEach(), map(), filter(), reduce(), and others. 168 | 169 | ```javascript 170 | 171 | // Array iteration example 172 | 173 | // Define an array of numbers 174 | let numbers = [1, 2, 3, 4, 5]; 175 | 176 | // Iterate over the elements of the array using a for loop 177 | console.log("Using a for loop:"); 178 | for (let i = 0; i < numbers.length; i++) { 179 | console.log(numbers[i]); // output: 1, 2, 3, 4, 5 180 | } 181 | 182 | // Iterate over the elements of the array using a while loop 183 | console.log("Using a while loop:"); 184 | let j = 0; 185 | while (j < numbers.length) { 186 | console.log(numbers[j]); // output: 1, 2, 3, 4, 5 187 | j++; 188 | } 189 | 190 | // Iterate over the elements of the array using the forEach() method 191 | console.log("Using the forEach() method:"); 192 | numbers.forEach(function(number) { 193 | console.log(number); // output: 1, 2, 3, 4, 5 194 | }); 195 | 196 | // Use the map() method to create a new array with the square of each element 197 | console.log("Using the map() method:"); 198 | let squaredNumbers = numbers.map(function(number) { 199 | return number * number; // output: 1, 4, 9, 16, 25 200 | }); 201 | console.log(squaredNumbers); 202 | 203 | // Use the filter() method to create a new array with only the even elements 204 | console.log("Using the filter() method:"); 205 | let evenNumbers = numbers.filter(function(number) { 206 | return number % 2 === 0; 207 | }); 208 | console.log(evenNumbers); // output 2, 4 209 | 210 | // Use the reduce() method to compute the sum of the elements 211 | console.log("Using the reduce() method:"); 212 | let sum = numbers.reduce(function(accumulator, number) { 213 | return accumulator + number; 214 | }, 0); 215 | console.log(sum); // output: 15 216 | ``` 217 | In this example, we defined an array of numbers and demonstrated several ways to iterate over the elements of the array: 218 | 219 | Using a for loop 220 | Using a while loop 221 | Using the forEach() method 222 | We also used several array-specific methods to manipulate the array: 223 | 224 | Using the map() method to create a new array with the square of each element 225 | Using the filter() method to create a new array with only the even elements 226 | Using the reduce() method to compute the sum of the elements 227 | 228 | 229 | * Arrays can be nested: You can nest arrays inside other arrays to create multi-dimensional arrays, which can be useful for storing complex data structures. For example, you could create a 2D array to represent a matrix, or a 3D array to represent a cube. 230 | 231 | ```javascript 232 | // Nested arrays example 233 | 234 | // Define a 2D array to represent a matrix 235 | let matrix = [ 236 | [1, 2, 3], 237 | [4, 5, 6], 238 | [7, 8, 9] 239 | ]; 240 | 241 | // Iterate over the elements of the 2D array using nested for loops 242 | console.log("Iterating over the 2D array:"); 243 | for (let i = 0; i < matrix.length; i++) { 244 | for (let j = 0; j < matrix[i].length; j++) { 245 | console.log(matrix[i][j]); // output: 1, 2, 3, 4, 5, 6, 7, 8, 9 246 | } 247 | } 248 | 249 | // Define a 3D array to represent a cube 250 | let cube = [ 251 | [ 252 | [0, 0, 0], 253 | [0, 0, 1], 254 | [0, 0, 2] 255 | ], 256 | [ 257 | [0, 1, 0], 258 | [0, 1, 1], 259 | [0, 1, 2] 260 | ], 261 | [ 262 | [0, 2, 0], 263 | [0, 2, 1], 264 | [0, 2, 2] 265 | ] 266 | ]; 267 | 268 | // Iterate over the elements of the 3D array using nested for loops 269 | console.log("Iterating over the 3D array:"); 270 | for (let i = 0; i < cube.length; i++) { 271 | for (let j = 0; j < cube[i].length; j++) { 272 | for (let k = 0; k < cube[i][j].length; k++) { 273 | console.log(cube[i][j][k]); // output: 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 1, 0, 0, 1, 1, 0, 1, 2, 0, 2, 0, 0, 2, 1, 0, 2, 2 274 | } 275 | } 276 | } 277 | 278 | ``` 279 | 280 | * Arrays can be copied by value or by reference: When you copy an array in JavaScript, you can do it either by value or by reference. Copying by value creates a new array with the same elements as the original array, while copying by reference creates a new variable that points to the same array as the original variable. This can have some unexpected consequences when working with arrays, so it's important to understand how copying works in JavaScript. 281 | 282 | ```javascript 283 | 284 | // Array copying example 285 | // Define an array 286 | let originalArray = [1, 2, 3]; 287 | 288 | // Copy the array by value using the slice() method 289 | let copyByValue = originalArray.slice(); 290 | 291 | // Modify the copy by value 292 | copyByValue.push(4); 293 | 294 | // Modify the original array 295 | originalArray.push(5); 296 | 297 | // Print the results 298 | console.log("Copy by value:", copyByValue); // Output: [1, 2, 3, 4] 299 | console.log("Original array:", originalArray); // Output: [1, 2, 3, 5] 300 | 301 | // Define an array 302 | let anotherArray = [4, 5, 6]; 303 | 304 | // Copy the array by reference 305 | let copyByReference = anotherArray; 306 | 307 | // Modify the copy by reference 308 | copyByReference.push(7); 309 | 310 | // Modify the original array 311 | anotherArray.push(8); 312 | 313 | // Print the results 314 | console.log("Copy by reference:", copyByReference); // Output: [4, 5, 6, 7, 8] 315 | console.log("Original array:", anotherArray); // Output: [4, 5, 6, 7, 8] 316 | ``` 317 | 318 | In this example, we first defined an array and then created a copy of it by value using the slice() method. We also created another array and copied it by reference. We then modified both the copies and the originals to see how the changes propagate. 319 | 320 | When we modified the copy by value, the original array was not affected. This is because the slice() method creates a new array with the same elements as the original array. When we modified the copy by reference, the original array was also affected. This is because the copy by reference is just a new variable that points to the same array as the original variable. When we modify the copy by reference, we are actually modifying the original array. 321 | 322 | 323 | 324 | **Array Methods** 325 | 326 | | Method | Description 327 | | -------- | -------- | 328 | |concat() | Joins two or more arrays and returns a resulting array 329 | |indexOf() |Searches an element of an array and returns its position 330 | |find() | Returns the first value of an array element that passes a test 331 | |findIndex()| Returns the first index of an array element that passes a test 332 | |forEach() | Calls a function for each element 333 | | includes() | Checks if an array contains a specified element 334 | | push() | Adds a new element to the end of an array and returns the new length of an array 335 | | unshift() | adds a new element to the beginning of an array and returns the new length of an array 336 | | pop() | removes the last element of an array and returns the removed element 337 | | shift() | emoves the first element of an array and returns the removed element 338 | | sort() | sorts the elements alphabetically in strings and in ascending order 339 | | slice() | selects the part of an array and returns the new array 340 | 341 | So far we have cover some the coempts of arrays in javascript. Arrays are important when your dealing with data in javascript. 342 | take them and practices you can do a further reading to get more information on arrays in javascript. 343 | 344 | -------------------------------------------------------------------------------- /06.Objects/README.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Objects ## 2 | 3 | 4 | **What is a JavaScript Object?** 5 | In JavaScript, an object is a collection of properties, where each property consists of a key and a value. The key is a string that represents the name of the property, and the value can be any valid JavaScript value, including other objects. 6 | 7 | 8 | Creating a JavaScript Object: 9 | There are several ways to create a JavaScript object. One of the most common ways is to use object literal notation, which allows you to define an object by enclosing a comma-separated list of key-value pairs in curly braces. 10 | 11 | Here is an example of creating an object using object literal notation: 12 | 13 | ```javascript 14 | let myObject = { 15 | name : "John", 16 | age : 30, 17 | city : "New York" 18 | 19 | 20 | }; 21 | 22 | ``` 23 | Accessing Object Properties: 24 | You can access the properties of an object using the dot notation or the bracket notation. The dot notation is used when you know the name of the property you want to access. The bracket notation is used when you want to access a property using a variable. 25 | 26 | Here is an example of accessing an object property using the dot notation: 27 | 28 | ```javascript 29 | let myObject = { 30 | name : "John", 31 | age : 30, 32 | city : "New York" 33 | }; 34 | 35 | // Accessing object properties using the dot notation 36 | console.log(myObject.name); // outPut: John 37 | console.log(myObject.age); // output: 30 38 | console.log(myObject.city); // output: New York 39 | 40 | 41 | // Accessing object properties using the bracket notation 42 | console.log(myObject["name"]); // outPut: John 43 | console.log(myObject["age"]); // output: 30 44 | console.log(myObject["city"]); // output : New York 45 | 46 | 47 | ``` 48 | 49 | **Adding New Properties to an Object:** 50 | You can add new properties to an object by using the dot notation or the bracket notation. The dot notation is used when you know the name of the property you want to add. The bracket notation is used when you want to add a property using a variable. 51 | 52 | Here is an example of adding a new property to an object using the dot notation: 53 | 54 | ```javascript 55 | let myObject = { 56 | name : "John", 57 | age : 30, 58 | city : "New York" 59 | }; 60 | 61 | // Adding a new property to an object using the dot notation 62 | myObject.country = "USA"; 63 | console.log(myObject.country); // output: USA 64 | 65 | myObject["age"] = "50"; 66 | console.log(myObject.age); // output: 50 67 | 68 | myObject["name"] = "Clifford"; 69 | console.log(myObject.name); // output: Clifford 70 | 71 | 72 | // Adding a new property to an object using the bracket notation 73 | myObject["country"] = "UK"; 74 | console.log(myObject.country); // output: UK 75 | 76 | myObject["age"] = "60"; 77 | console.log(myObject.age); // output: 60 78 | 79 | 80 | myObject["name"] = "Isaiah"; 81 | console.log(myObject.name); // output: Isaiah 82 | 83 | ``` 84 | 85 | 86 | **Deleting Properties from an Object:** 87 | You can delete properties from an object by using the delete operator. 88 | 89 | Here is an example of deleting a property from an object: 90 | 91 | ```javascript 92 | let myObject = { 93 | name : "John", 94 | age : 30, 95 | city : "New York" 96 | }; 97 | 98 | // Deleting a property from an object 99 | 100 | delete myObject.city; 101 | console.log(myObject.city); // output: undefined 102 | 103 | console.log(myObject); // output: {name: "John", age: 30} 104 | 105 | // now we are getting a new object with only 2 properties because the city property was deleted 106 | 107 | ``` 108 | 109 | **Looping Through an Object:** 110 | You can loop through the properties of an object using the for...in loop. 111 | 112 | Here is an example of looping through an object: 113 | 114 | ```javascript 115 | let myObject = { 116 | name : "John", 117 | age : 30, 118 | city : "New York" 119 | }; 120 | 121 | // Looping through an object 122 | for (let key in myObject) { 123 | console.log(key + " : " + myObject[key]); 124 | } 125 | 126 | // output: name : John 127 | // output: age : 30 128 | // output: city : New York 129 | 130 | ``` 131 | 132 | 133 | Conclusion: 134 | In summary, JavaScript objects are a powerful tool for storing and manipulating data in web development. They allow you to create complex data structures and access properties using dot notation or bracket notation. By mastering the concepts of JavaScript objects, you will be well on your way to becoming a proficient web developer. 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /07.Events/README.md: -------------------------------------------------------------------------------- 1 | ## JavaScript events 2 | 3 | **Introduction:** 4 | JavaScript events are actions or occurrences that happen in the browser, such as a user clicking a button or typing into a text field. Events can be triggered by the user or by the browser, and JavaScript provides a way to respond to these events. 5 | 6 | **Types of JavaScript Events:** 7 | There are many types of JavaScript events, but they can generally be categorized into three types: user events, browser events, and system events. 8 | 9 | **_User events:_** are events that are initiated by the user, such as clicking a button, typing into a text field, or scrolling the page. These events are the most common type of events in JavaScript. 10 | 11 | Here are some examples of user events in JavaScript: 12 | 13 | - Click Event: 14 | The most common user event in JavaScript is the click event. This event is triggered when the user clicks on an element, such as a button or a link. Here is an example of how to handle a click event: 15 | 16 | ```javascript 17 | const button = document.querySelector("button"); 18 | 19 | button.addEventListener("click", function () { 20 | console.log("Button clicked!"); 21 | }); 22 | ``` 23 | 24 | In this example, an event listener is added to a button element. When the button is clicked, the function inside the event listener is executed and the message "Button clicked!" is logged to the console. 25 | 26 | - Keydown Event: 27 | Another common user event is the keydown event. This event is triggered when the user presses a key on the keyboard. Here is an example of how to handle a keydown event: 28 | 29 | ```javascript 30 | document.addEventListener("keydown", function (event) { 31 | console.log("Key pressed: " + event.key); 32 | }); 33 | ``` 34 | 35 | In this example, an event listener is added to the entire document. When the user presses a key, the function inside the event listener is executed and the message "Key pressed: [key]" is logged to the console, where [key] is replaced with the actual key that was pressed. 36 | 37 | - Mousemove Event: Another common user event is the mousemove event. This event is triggered when the user moves the mouse. Here is an example of how to handle a mousemove event: 38 | 39 | ```javascript 40 | const container = document.querySelector(".container"); 41 | 42 | container.addEventListener("mousemove", function (event) { 43 | console.log("Mouse position: " + event.clientX + ", " + event.clientY); 44 | }); 45 | ``` 46 | 47 | In this example, an event listener is added to a container element. When the user moves the mouse over the container, the function inside the event listener is executed and the message "Mouse position: [x], [y]" is logged to the console, where [x] and [y] are replaced with the x and y coordinates of the mouse cursor. 48 | 49 | These are just a few examples of the many user events that can be handled in JavaScript. There are many more events that can be handled, such as the keyup event, the keypress event, the mousedown event, the mouseup event, the mouseover event, the mouseout event, the scroll event, the resize event, the focus event, the blur event, and many more. 50 | 51 | **_Browser events:_** are events that are triggered by the browser, such as when a page is loaded or when an image is loaded. 52 | 53 | Here are some examples of browser events in JavaScript: 54 | 55 | - Load Event: 56 | The most common browser event in JavaScript is the load event. This event is triggered when the browser has finished loading the page. Here is an example of how to handle a load event: 57 | 58 | ```javascript 59 | window.addEventListener("load", function () { 60 | console.log("Page loaded!"); 61 | }); 62 | ``` 63 | 64 | In this example, an event listener is added to the window object. When the browser has finished loading the page, the function inside the event listener is executed and the message "Page loaded!" is logged to the console. 65 | 66 | - Beforeunload Event: 67 | Another common browser event is the beforeunload event. This event is triggered when the user is about to leave the page. Here is an example of how to handle a beforeunload event: 68 | 69 | ```javascript 70 | window.addEventListener("beforeunload", function (event) { 71 | event.preventDefault(); 72 | event.returnValue = ""; 73 | }); 74 | ``` 75 | 76 | In this example, an event listener is added to the window object. When the user is about to leave the page, the function inside the event listener is executed and the message "Are you sure you want to leave?" is displayed in the browser. 77 | 78 | - Resize Event: 79 | Another common browser event is the resize event. This event is triggered when the browser window is resized. Here is an example of how to handle a resize event: 80 | 81 | ```javascript 82 | window.addEventListener("resize", function () { 83 | console.log("Window resized!"); 84 | }); 85 | ``` 86 | 87 | In this example, an event listener is added to the window object. When the browser window is resized, the function inside the event listener is executed and the message "Window resized!" is logged to the console. 88 | 89 | - Scroll Event: 90 | Another common browser event is the scroll event. This event is triggered when the user scrolls the page. Here is an example of how to handle a scroll event: 91 | 92 | ```javascript 93 | window.addEventListener("scroll", function () { 94 | console.log("Page scrolled!"); 95 | }); 96 | ``` 97 | 98 | In this example, an event listener is added to the window object. When the user scrolls the page, the function inside the event listener is executed and the message "Page scrolled!" is logged to the console. 99 | 100 | - Error Event: 101 | Another common browser event is the error event. This event is triggered when an error occurs while loading a script or an image. Here is an example of how to handle an error event: 102 | 103 | ```javascript 104 | window.addEventListener("error", function (event) { 105 | console.log("Error: " + event.message); 106 | }); 107 | ``` 108 | 109 | In this example, an event listener is added to the window object. When an error occurs while loading a script or an image, the function inside the event listener is executed and the message "Error: [message]" is logged to the console, where [message] is replaced with the actual error message. 110 | 111 | These are just a few examples of the many browser events that can be handled in JavaScript. There are many more events that can be handled, such as the unload event, the hashchange event, the popstate event, the offline event, the online event, the message event, the storage event, and many more. 112 | 113 | 114 | ## **_Event Listeners:_** 115 | 116 | To respond to JavaScript events, you can use event listeners. An event listener is a function that is called when an event occurs. You can attach an event listener to an element using the addEventListener() method. Here is an example of how to attach an event listener to an element: 117 | 118 | ```javascript 119 | element.addEventListener("click", function () { 120 | console.log("Element clicked!"); 121 | }); 122 | ``` 123 | 124 | In this example, an event listener is added to the element. When the element is clicked, the function inside the event listener is executed and the message "Element clicked!" is logged to the console. 125 | 126 | You can also attach an event listener to the window object. Here is an example of how to attach an event listener to the window object: 127 | 128 | ```javascript 129 | window.addEventListener("resize", function () { 130 | console.log("Window resized!"); 131 | }); 132 | ``` 133 | 134 | In this example, an event listener is added to the window object. When the browser window is resized, the function inside the event listener is executed and the message "Window resized!" is logged to the console. 135 | 136 | 137 | ## **_Event Propagation::_** 138 | 139 | JavaScript events have a concept called event propagation, which refers to the order in which events are handled by elements in the DOM tree. When an event occurs on an element, the event is first handled by the element itself, then its parent element, and so on until the event reaches the document object. 140 | 141 | There are two types of event propagation: bubbling and capturing. Bubbling is the default propagation type and it means that the event starts at the element where it occurred and then bubbles up the DOM tree. Capturing is the opposite, it starts at the top of the DOM tree and moves down until it reaches the element where the event occurred. 142 | ```javascript 143 | const container = document.querySelector('.container'); 144 | const button = document.querySelector('button'); 145 | 146 | container.addEventListener('click', function() { 147 | alert('Container clicked!'); 148 | }, true); 149 | 150 | button.addEventListener('click', function() { 151 | alert('Button clicked!'); 152 | }, true); 153 | ``` 154 | 155 | In this example, the event listeners are attached with the true parameter, which means they are using capturing propagation. When the button is clicked, the container event listener is called first, followed by the button event listener. 156 | 157 | 158 | **Conclusion:** 159 | In summary, JavaScript events are actions or occurrences that happen in the browser, and there are many types of events that can be triggered by the user, the browser, or the system. You can respond to these events using event listeners, which are functions that are called when an event occurs. Additionally, event propagation is an important concept to understand when working with JavaScript events, as it determines the order in which events are handled by elements in the DOM tree. 160 | -------------------------------------------------------------------------------- /08.DOM-manipulation/README.md: -------------------------------------------------------------------------------- 1 | # Javascript DOM Manipulation 2 | 3 | **What is DOM Manipulation?** 4 | The DOM in dom manipulation in javascript stands for Document Object Model. The Document Object Model (DOM) is a tree-like structure illustrating the hierarchical relationship between various HTML elements.In the DOM, every element, attribute, and piece of text in an HTML or XML document is represented as a node. Each node is an object with properties and methods that allow it to be manipulated and interacted with using JavaScript. 5 | 6 | A visual representation of the DOM tree is shown in the image below. 7 | ![dom](/images/1-1.jpg) 8 | 9 | - **Document** is the core/foundation of the DOM. 10 | - **HTML** Root element is the child of the document object. 11 | - **Body** and **Head** are the children of the HTML element and siblings to each other. 12 | - **Title** Element is the parent to the text node: "my text” and the child of the head element. 13 | - **a** and **h1** tag are the children of the body element and siblings to each other. 14 | - **herf** attribute is the children of the a(anchor) tag. 15 | 16 | The DOM is referred to as a programming API for XML and HTML documents. DOM defines the logical structure of documents and the methods for accessing and changing them are specified by the DOM. 17 | 18 | ### How to Select Elements in the DOM? 19 | 20 | n JavaScript, you can select elements in the DOM (Document Object Model) using various methods. Here are some commonly used methods for selecting elements in the DOM .There are several ways to select elements in the DOM. The most common ways are: 21 | 22 | - **document.getElementById()**: This method selects an element by its id attribute. 23 | - Example: 24 | 25 | ```javascript 26 | const element = document.getElementById("myId"); 27 | ``` 28 | 29 | - **document.getElementsByClassName()**: This method selects elements by their class attribute. 30 | 31 | Example: 32 | 33 | ```javascript 34 | const elements = document.getElementsByClassName("myClass"); 35 | ``` 36 | 37 | - **document.getElementsByTagName()**: This method selects elements by their tag name. 38 | 39 | Example: 40 | 41 | ```javascript 42 | const elements = document.getElementsByTagName("p"); 43 | ``` 44 | 45 | - **document.querySelector()**: This method selects the first element that matches a specified CSS selector(s). 46 | 47 | Example: 48 | 49 | ```javascript 50 | const element = document.querySelector("p"); 51 | ``` 52 | 53 | - **document.querySelectorAll()**: This method selects all elements that match a specified CSS selector(s). 54 | 55 | Example: 56 | 57 | ```javascript 58 | const elements = document.querySelectorAll("p"); 59 | ``` 60 | 61 | The querySelector() and querySelectorAll() methods are especially useful because they allow you to select elements using CSS selectors, which gives you a lot of flexibility in terms of selecting specific elements or groups of elements based on their attributes, classes, or structure. 62 | 63 | - **ParentNode :** This property returns the parent node of an element. 64 | 65 | Example: 66 | 67 | ```javascript 68 | const myElement = document.getElementById("my-id"); 69 | const parentElement = myElement.parentNode; 70 | ``` 71 | 72 | - **ChildNodes :** This property returns a collection of an element's child nodes, as a NodeList object. 73 | 74 | Example: 75 | 76 | ```javascript 77 | const myElement = document.getElementById("my-id"); 78 | const childNodes = myElement.childNodes; 79 | ``` 80 | 81 | - **FirstChild** and **LastChild:** These properties return the first and last child nodes of an element. 82 | 83 | ```javascript 84 | const myElement = document.getElementById("my-id"); 85 | const firstChild = myElement.firstChild; 86 | const lastChild = myElement.lastChild; 87 | ``` 88 | 89 | - **PreviousSibling** and **NextSibling:** These properties return the previous and next sibling nodes of an element. 90 | 91 | ```javascript 92 | const myElement = document.getElementById("my-id"); 93 | const nextSibling = myElement.nextSibling; 94 | const previousSibling = myElement.previousSibling; 95 | ``` 96 | 97 | - **appendChild() :** This method adds a new child node to an element. 98 | 99 | ```js 100 | const myElement = document.getElementById("my-id"); 101 | const newChild = document.createElement("div"); 102 | myElement.appendChild(newChild); 103 | ``` 104 | 105 | - **removeChild() :** This method removes a child node from an element. 106 | 107 | ```js 108 | const myElement = document.getElementById("my-id"); 109 | const childToRemove = myElement.firstChild; 110 | myElement.removeChild(childToRemove); 111 | ``` 112 | 113 | - **insertBefore() :** This method inserts a new node before an existing child node of an element. 114 | 115 | ```js 116 | const myElement = document.getElementById("my-id"); 117 | const newChild = document.createElement("div"); 118 | const referenceChild = myElement.firstChild; 119 | myElement.insertBefore(newChild, referenceChild); 120 | ``` 121 | 122 | - **replaceChild() :** This method replaces a child node of an element with a new node. 123 | 124 | ```js 125 | const myElement = document.getElementById("my-id"); 126 | 127 | const newChild = document.createElement("div"); 128 | 129 | const oldChild = myElement.firstChild; 130 | 131 | myElement.replaceChild(newChild, oldChild); 132 | ``` 133 | 134 | By using these methods, you can traverse and manipulate the DOM tree in a flexible and powerful way. With some practice, you can use these methods to create dynamic and interactive web pages that respond to user input and provide a rich user experience. 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /09.Callbacks/README.md: -------------------------------------------------------------------------------- 1 | ## Callback function in JavaScript 2 | 3 | - **What is a callback function in javascript?** 4 | A callback function is a function that is passed as an argument to another function, which then invokes the callback function at a later time. In other words, the callback function is a way to execute code after some other code has finished executing. 5 | 6 | - **Why do we need callback functions?** 7 | Callback functions are commonly used in JavaScript to handle asynchronous tasks, such as fetching data from an API or processing user input events. When you make an asynchronous call, the code continues to execute, and the callback function is called when the response is received. 8 | Here is the benefits of using callback functions in javascript: 9 | 10 | - To make sure that a function is not going to run before a task is completed. 11 | - To make sure that a function is going to run after a task has been completed. 12 | - To keep the order of execution in asynchronous callbacks. 13 | 14 | - **How to write a callback function in javascript?** 15 | A callback function is defined like any other function, but it is usually passed as an argument to another function. 16 | 17 | ```javascript 18 | // callback function Example 19 | function myCallbackFunction() { 20 | console.log("Callback function executed!"); 21 | } 22 | 23 | function myFunction(callback) { 24 | console.log("My function is executing..."); 25 | callback(); 26 | } 27 | 28 | myFunction(myCallbackFunction); 29 | ``` 30 | 31 | In this example, the myCallbackFunction function is defined first, and then it is passed as an argument to the myFunction function. The myFunction function logs a message to the console and then calls the callback function. The callback function is executed after the myFunction function has finished executing. 32 | 33 | - **How to use callback functions in javascript?** 34 | 35 | ```javascript 36 | // callback function Example 37 | function myCallbackFunction() { 38 | console.log("Callback function executed!"); 39 | } 40 | 41 | function myFunction(callback) { 42 | console.log("My function is executing..."); 43 | callback(); 44 | } 45 | 46 | myFunction(myCallbackFunction); 47 | ``` 48 | 49 | In this example, the myCallbackFunction function is defined first, and then it is passed as an argument to the myFunction function. The myFunction function logs a message to the console and then calls the callback function. The callback function is executed after the m 50 | 51 | - **What is the difference between synchronous and asynchronous callback functions?** 52 | 53 | - Synchronous callback functions are executed immediately after the function that calls them has finished executing. 54 | - Asynchronous callback functions are executed after the function that calls them has finished executing, but not necessarily immediately. 55 | - Synchronous callback functions are executed in the order in which they are called. 56 | - Asynchronous callback functions are executed in the order in which they are called, but not necessarily in the order in which they are defined. 57 | 58 | 59 | ```javascript 60 | // Synchronous callback function Example 61 | function myCallbackFunction() { 62 | console.log("Callback function executed!"); 63 | } 64 | 65 | function myFunction(callback) { 66 | console.log("My function is executing..."); 67 | callback(); 68 | } 69 | 70 | myFunction(myCallbackFunction); 71 | ``` 72 | 73 | In this example, the myCallbackFunction function is defined first, and then it is passed as an argument to the myFunction function. The myFunction function logs a message to the console and then calls the callback function. The callback function is executed after the myFunction function has finished executing. 74 | 75 | 76 | ```javascript 77 | 78 | // Asynchronous callback function Example 79 | function myCallbackFunction() { 80 | console.log("Callback function executed!"); 81 | } 82 | 83 | function myFunction(callback) { 84 | console.log("My function is executing..."); 85 | setTimeout(callback, 3000); 86 | } 87 | 88 | myFunction(myCallbackFunction); 89 | ``` 90 | 91 | In this example, the myCallbackFunction function is defined first, and then it is passed as an argument to the myFunction function. The myFunction function logs a message to the console and then calls the callback function. The callback function is executed after the myFunction function has finished executing, but not necessarily immediately. 92 | 93 | 94 | In summary, callback functions are a powerful tool in JavaScript that allow you to handle asynchronous tasks and execute code after some other code has finished executing. When used correctly, they can make your code more efficient and easier to read. However, it's important to be aware of the common pitfalls and to use best practices when using callback functions. 95 | 96 | 97 | -------------------------------------------------------------------------------- /10.Asynchronous-programming/README.md: -------------------------------------------------------------------------------- 1 | ## Asynchronous programming in javascript 2 | 3 | In this section, we will learn about asynchronous programming in JavaScript. We will learn about the following topics: 4 | 5 | - Asynchronous programming 6 | - What is asynchronous programming in javascript? 7 | - Callback functions in javascript for asynchronous programming 8 | - Promises in javascript for asynchronous programming 9 | - Async/await in javascript for asynchronous programming 10 | 11 | ### Asynchronous programming 12 | 13 | Asynchronous programming in JavaScript allows you to execute code without blocking the main thread, which can improve the performance of your application. In this type of programming, you can perform multiple operations simultaneously, which can make your application more responsive. 14 | 15 | ### What is asynchronous programming in javascript? 16 | 17 | Asynchronous programming is a programming pattern that allows you to perform multiple operations simultaneously. JavaScript is single-threaded, which means that only one operation can be executed at a time. Asynchronous programming enables you to execute code without blocking the main thread, so your application remains responsive. 18 | 19 | ### Callback functions in javascript for asynchronous programming 20 | 21 | In JavaScript, callbacks are functions that are passed as arguments to other functions. When the function completes its task, it calls the callback function. Callbacks are commonly used in asynchronous programming to handle the results of asynchronous operations. 22 | 23 | For example, the following code snippet shows a callback function that is passed as an argument to a setTimeout function: 24 | 25 | ```javascript 26 | // callback function Example 27 | setTimeout(() => { 28 | console.log("Hello, javascript !"); 29 | }, 1000); 30 | ``` 31 | 32 | In this code, the setTimeout function will wait for 1000 milliseconds before calling the callback function, which will log "Hello, javascript!" to the console. 33 | 34 | ### Promises in javascript for asynchronous programming 35 | 36 | Promises are a more recent addition to JavaScript, and they provide a cleaner way to handle asynchronous operations. A promise represents the result of an asynchronous operation, and it can be in one of three states: 37 | 38 | - **Pending**: The initial state of a promise. 39 | - **Fulfilled**: The state of a promise representing a successful operation. 40 | - **Rejected**: The state of a promise representing a failed operation. 41 | 42 | You can use the then() method to handle the fulfilled state of a promise, and the catch() method to handle the rejected state. 43 | For example, the following code snippet shows a Promise that is used to load a JSON file: 44 | 45 | ```javascript 46 | const DataJson = "data.json"; 47 | fetch(DataJson) 48 | .then((response) => response.json()) 49 | .then((data) => console.log(data)) 50 | .catch((error) => console.error(error)); 51 | ``` 52 | 53 | In this code, the fetch() function returns a Promise that resolves with the response object. The first then() method converts the response object to JSON, and the second then() method logs the data to the console. The catch() method logs any errors to the console. 54 | Promises are most useful for API implementations in javascript. 55 | 56 | ### Async/await in javascript for asynchronous programming 57 | 58 | Async/await is a more recent addition to JavaScript, and it provides a more readable way to write asynchronous code. Async/await is built on top of Promises, and it allows you to write code that looks synchronous, even though it's asynchronous under the hood. 59 | 60 | For example, the following code snippet shows an async function that is used to load a JSON file: 61 | 62 | ```javascript 63 | async function loadJSON() { 64 | try { 65 | const response = await fetch("data.json"); 66 | const data = await response.json(); 67 | console.log(data); 68 | } catch (error) { 69 | console.error(error); 70 | } 71 | } 72 | 73 | loadJSON(); 74 | ``` 75 | 76 | In this code, the loadJSON() function is declared as async, which allows us to use the await keyword inside the function. The try/catch block is used to handle errors. The await keyword is used to wait for the fetch() and response.json() functions to complete before continuing. 77 | 78 | ### Conclusion 79 | 80 | Asynchronous programming is an essential concept in JavaScript, and it's critical to understand it if you want to write efficient, responsive applications. Callbacks, Promises, and async/await are three ways to handle asynchronous operations in JavaScript, and each has its advantages and disadvantages. 81 | 82 | ## Resources 83 | 84 | You can find more information about asynchronous programming in JavaScript in the following resources: 85 | 86 | - [Asynchronous JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous) 87 | - [JavaScript Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) 88 | 89 | - [Async/Await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) 90 | -------------------------------------------------------------------------------- /11.Closures/README.md: -------------------------------------------------------------------------------- 1 | ## Closures in javascript 2 | 3 | - **What is a closure in javascript?** 4 | 5 | Closures are a fundamental concept in JavaScript that allow for powerful and flexible programming techniques. Essentially, a closure is created whenever a function is defined inside another function, and the inner function retains access to the variables and scope of the outer function, even after the outer function has completed execution. A closure is a function that has access to the parent scope, even after the parent function has closed. 6 | 7 | Here is a simple example: 8 | 9 | ```javascript 10 | // closure Example 11 | function outer() { 12 | var x = 10; 13 | 14 | function inner() { 15 | console.log(x); 16 | } 17 | 18 | return inner; 19 | } 20 | 21 | var innerFn = outer(); 22 | innerFn(); // output: 10 23 | ``` 24 | 25 | In this example, the outer function creates a variable x and a nested function inner. outer then returns inner, and the variable innerFn is assigned the result of calling outer. Finally, innerFn is called, which prints out the value of x (which is 10) to the console. 26 | 27 | What's happening here is that the inner function forms a closure over the variables and scope of outer. Even though outer has completed execution and its variables should no longer be accessible, the closure ensures that inner retains access to those variables. 28 | 29 | One of the key benefits of closures is that they allow for data privacy and encapsulation. In the example above, the variable x is not accessible from outside the outer function - it can only be accessed by calling the inner function, which has access to the closure. 30 | 31 | 32 | Closures are also commonly used in functional programming techniques such as currying and partial application. Here's an example of how closures can be used to create a curried function: 33 | ```javascript 34 | // closure Example 35 | function add(a) { 36 | return function(b) { 37 | return a + b; 38 | } 39 | } 40 | 41 | var add5 = add(5); 42 | console.log(add5(3)); // output: 8 43 | 44 | if(love === ) 45 | ``` 46 | 47 | In this example, the add function returns a new function that takes a single argument b and returns the sum of a and b. The value of a is retained in the closure, allowing the returned function to be "curried" with a specific value of a. The add5 variable is assigned the result of calling add(5), which creates a new function that adds 5 to its argument. When add5 is called with an argument of 3, it returns 8. 48 | 49 | Overall, closures are a powerful and important concept in JavaScript that enable a wide range of programming techniques. By understanding how closures work and how to use them effectively, you can write more flexible, expressive, and maintainable code. 50 | 51 | 52 | 53 | ### Resources 54 | You can find more information about closures in the following resources: 55 | 56 | - [MDN: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) 57 | 58 | -------------------------------------------------------------------------------- /12.Prototypal-inheritance/README.md: -------------------------------------------------------------------------------- 1 | ### Prototype and inheritance in javascript 2 | 3 | Prototypal inheritance is a key feature of JavaScript that allows objects to inherit properties and methods from other objects. In JavaScript, every object has an internal [[Prototype]] property, which can be thought of as a reference to another object. When a property or method is accessed on an object and it's not found on the object itself, JavaScript will look up the prototype chain to find it on the object's prototype or one of its ancestors. 4 | 5 | Here's an example: 6 | 7 | ```javascript 8 | var person = { 9 | firstName: "John", 10 | lastName: "Doe", 11 | fullName: function() { 12 | return this.firstName + " " + this.lastName; 13 | } 14 | }; 15 | 16 | var employee = { 17 | jobTitle: "Developer" 18 | }; 19 | 20 | employee.__proto__ = person; 21 | 22 | console.log(employee.fullName()); // output: "John Doe" 23 | 24 | 25 | ``` 26 | 27 | In this example, person is an object with properties firstName, lastName, and fullName. employee is another object with a property jobTitle. The __proto__ property of employee is set to person, which means that employee inherits all of person's properties and methods. 28 | 29 | When employee.fullName() is called, JavaScript first looks for the fullName property on employee, but it's not found. So it looks up the prototype chain to person, where it finds the fullName method. The this keyword inside the fullName method refers to employee, because that's the object the method is being called on. 30 | 31 | 32 | One thing to note is that while __proto__ is supported in all major browsers, it's not part of the official JavaScript specification. Instead, you can use the Object.create method to create an object with a specified prototype: 33 | 34 | ```javascript 35 | 36 | var employee = Object.create(person); 37 | employee.jobTitle = "Developer"; 38 | 39 | ``` 40 | 41 | In this example, employee is created using Object.create(person), which sets the prototype of employee to person. The jobTitle property is then added to employee. 42 | 43 | Prototypal inheritance is a powerful and flexible way to organize and reuse code in JavaScript. By defining common properties and methods on a prototype, you can create a hierarchy of objects that share behavior and functionality. 44 | 45 | There's also a related concept in JavaScript called classical inheritance, which emulates the class-based inheritance found in languages like Java or C++. However, classical inheritance in JavaScript is based on prototypal inheritance under the hood, and it can be less flexible and more verbose than prototypal inheritance. Some frameworks like ES6 classes and TypeScript add syntax sugar over classical inheritance for programmers who are more familiar with class-based inheritance. 46 | 47 | Overall, understanding prototypal inheritance is essential for writing effective and maintainable JavaScript code. By using prototypes and inheritance effectively, you can create reusable, modular code that's easy to reason about and extend. 48 | -------------------------------------------------------------------------------- /13.Scoping-and-hoisting/README.md: -------------------------------------------------------------------------------- 1 | ## Scoping and Hosting 2 | 3 | In this section, we'll look at how JavaScript handles variable scoping and function hosting. We'll also look at the difference between global and local variables, and how to use the let and const keywords to declare variables. 4 | 5 | - _Scoping and hoisting_: 6 | Scoping and hoisting are two important concepts in JavaScript that affect how variables and functions are defined and used within a program. Understanding these concepts is crucial for writing efficient and effective JavaScript code. 7 | 8 | ## Scoping in javascript 9 | 10 | Scoping is the set of rules that determines where and how a variable can be accessed in a program. In JavaScript, variables can be declared at the global level or within a function. Variables declared at the global level are called global variables, and variables declared within a function are called local variables. Global variables can be accessed from anywhere within a program, while local variables can only be accessed from within the function they were declared in. 11 | 12 | There are two types of scopes in JavaScript: Global scope and Local scope. 13 | 14 | - _Global scope_: 15 | Global scope refers to the context in which variables are accessible to any part of your code. In JavaScript, global scope refers to the top-level scope, which is the outermost scope in your code. Variables declared in the global scope can be accessed from any other scope in your code. 16 | Here's an example: 17 | 18 | ```javascript 19 | // global variable 20 | var globalVar = "I'm global!"; // global variable 21 | ``` 22 | 23 | in javascript, variables declared with the var keyword are automatically added to the global scope. This means that if you declare a variable in the global scope, it's accessible from any other scope in your code. However, variables declared with the let and const keywords are not automatically added to the global scope. Instead, they are only accessible within the block they were declared in. 24 | 25 | - _Local scope_: 26 | Local scope refers to the context in which variables are accessible only within the current scope. In JavaScript, local scope refers to the scope of a function. Variables declared in a local scope can only be accessed from within the function they were declared in. 27 | 28 | ```javascript 29 | function myFunction() { 30 | // local variable 31 | const localVar = "I'm local!"; 32 | let localVar2 = "I'm also local!"; 33 | } 34 | ``` 35 | 36 | In this example, localVar and localVar2 are local variables. They can only be accessed from within the myFunction function. If you try to access them from outside the function, you'll get a ReferenceError. 37 | 38 | ## Hoisting in javascript 39 | 40 | Hoisting is a mechanism in JavaScript where variables and function declarations are moved to the top of their respective scopes during compilation. This means that you can use a variable or function before it is declared. 41 | The following is the JavaScript lifecycle and indicative of the sequence in which variable declaration and initialization occurs. 42 | ![Hosting](/images/hositing.png) 43 | 44 | ```javascript 45 | console.log(x); // Output: undefined 46 | var x = 5; 47 | ``` 48 | 49 | In the above example, the variable x is declared after it is used in the console.log statement. However, JavaScript hoists the variable declaration to the top of its scope, which means that the code is interpreted as follows: 50 | 51 | ```javascript 52 | var x; 53 | console.log(x); // Output: undefined 54 | x = 5; 55 | ``` 56 | 57 | This means that you can use a variable before it is declared. However, if you try to use a variable before it is declared and initialized, you'll get a ReferenceError. 58 | 59 | ```javascript 60 | console.log(x); // Output: ReferenceError: x is not defined 61 | let x = 5; 62 | ``` 63 | 64 | In the above example, the variable x is declared with the let keyword, which means that it is not hoisted. This means that the code is interpreted as follows: 65 | 66 | - **Function declarations** are also hoisted in JavaScript, which means that you can use a function before it is declared. 67 | 68 | ```javascript 69 | myFunction(); // Output: "Hello!"` 70 | function myFunction() { 71 | console.log("Hello!"); 72 | } 73 | ``` 74 | In the above example, the myFunction function is declared after it is used in the myFunction() function call. However, JavaScript hoists the function declaration to the top of its scope, which means that the code is interpreted as follows: 75 | 76 | 77 | ```javascript 78 | function myFunction() { 79 | console.log("Hello, World!"); 80 | } 81 | 82 | myFunction(); // Output: "Hello, World!" 83 | 84 | ``` 85 | 86 | - **Function expressions** are not hoisted in JavaScript, which means that you cannot use a function before it is declared. 87 | 88 | ```javascript 89 | myFunction(); // Output: TypeError: myFunction is not a function 90 | const myFunction = function () { 91 | console.log("Hello, World!"); 92 | }; 93 | ``` 94 | 95 | In the above example, the myFunction function is defined using a function expression, which means that it is not hoisted. When the function is called before it is defined, JavaScript throws a TypeError because myFunction is not yet a function. 96 | 97 | ### Resources 98 | You can Read further in Below links: 99 | 100 | - [Scoping and hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) 101 | 102 | 103 | -------------------------------------------------------------------------------- /14.Regular-expressions/README.md: -------------------------------------------------------------------------------- 1 | # Regular Expression in JavaScript 2 | 3 | Regular expressions are a powerful tool for manipulating and validating strings in JavaScript. They allow you to specify patterns of text that you want to match, search for, or replace within a larger string. Regular expressions are represented by a special syntax that is enclosed within forward slashes (/.../). 4 | 5 | The syntax of a regular expression consists of a combination of characters and special characters that represent specific rules for matching text. For example, the following regular expression matches any string that contains the word "cat": 6 | 7 | ```javascript 8 | / cat /; 9 | ``` 10 | 11 | This regular expression matches any string that contains the letters "c", "a", and "t" in that order. 12 | 13 | Regular expressions can also include special characters that represent certain types of characters or groups of characters. 14 | 15 | For example : 16 | 17 | - The ^ character matches the beginning of a string. So, the regular expression /^cat/ matches any string that starts with the letters "c", "a", and "t" in that order. 18 | - The $ character matches the end of a string. So, the regular expression /cat$/ matches any string that ends with the letters "c", "a", and "t" in that order. 19 | 20 | - The . character matches any single character except for a newline. So, the regular expression /c.t/ matches any string that contains the letters "c", "t", and any single character in between them. 21 | 22 | - The * character matches zero or more occurrences of the previous character. So, the regular expression /ca*t/ matches any string that contains the letters "c", "a", and zero or more occurrences of the letter "t". 23 | - The + character matches one or more occurrences of the previous character. So, the regular expression /ca+t/ matches any string that contains the letters "c", "a", and one or more occurrences of the letter "t". 24 | - The ? character matches zero or one occurrence of the previous character. So, the regular expression /ca?t/ matches any string that contains the letters "c", "a", and zero or one occurrence of the letter "t". 25 | 26 | In addition to these special characters, regular expressions can also include character classes that represent sets of characters, such as: 27 | 28 | - \d : Matches any digit (0-9). 29 | - \w : Matches any word character (letter, digit, or underscore). 30 | - \s : Matches any whitespace character (space, tab, newline, etc.). 31 | - [abc] : Matches any single character within the specified set (in this case, "a", "b", or "c"). 32 | - [^abc] : Matches any single character that is not within the specified set (in this case, any character that is not "a", "b", or "c"). 33 | 34 | Here's an example of a regular expression that matches any string that starts with a digit and ends with a letter: 35 | 36 | ```javascript 37 | / \d + [a-z] /; 38 | ``` 39 | 40 | This regular expression uses the ^ character to match the beginning of the string, \d to match any digit, .\* to match any number of characters in between, and [a-zA-Z] to match any letter (upper or lowercase) at the end of the string. 41 | 42 | In JavaScript, regular expressions can be used with methods such as test(), match(), replace(), and search() to perform various operations on strings. 43 | 44 | - The test() method returns true if a string matches a regular expression, and false otherwise. 45 | - The match() method returns an array containing all matches of a regular expression within a string, or null if no matches are found. 46 | - The replace() method replaces all occurrences of a regular expression within a string with a specified replacement string. 47 | - The search() method returns the index of the first occurrence of 48 | 49 | Certainly! Here are a few examples of how to use regular expressions in JavaScript: 50 | 51 | - ### Validating an email address 52 | 53 | Regular expressions can be used to validate whether an email address is formatted correctly. Here's an example: 54 | 55 | ```javascript 56 | const email = "example@example.com"; 57 | const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; 58 | 59 | if (emailRegex.test(email)) { 60 | console.log("Valid email address"); 61 | } else { 62 | console.log("Invalid email address"); 63 | } 64 | ``` 65 | 66 | In this example, the regular expression /^[^\s@]+@[^\s@]+\.[^\s@]+$/ matches any string that starts with one or more characters that are not whitespace or "@" (^[^\s@]+), followed by "@" (@), followed by one or more characters that are not whitespace or "@" ([^\s@]+), followed by a dot (\.), followed by one or more characters that are not whitespace or "@" ([^\s@]+), and ends with the end of the string ($). 67 | 68 | - ### Extracting numbers from a string 69 | 70 | Regular expressions can be used to extract numbers from a string. Here's an example: 71 | 72 | ```javascript 73 | const text = "The total is $123.45"; 74 | const numberRegex = /\d+/g; 75 | 76 | const numbers = text.match(numberRegex); 77 | console.log(numbers); // [123, 45] 78 | ``` 79 | 80 | In this example, the regular expression /\d+/g matches any string that contains one or more digits (\d+) and ends with the end of the string ($). The g flag indicates that the regular expression should be matched globally, so that all occurrences of the pattern are matched, rather than just the first occurrence. 81 | 82 | - ### Replacing all occurrences of a string 83 | 84 | Regular expressions can be used to replace all occurrences of a string. Here's an example: 85 | 86 | ```javascript 87 | const text = "The total is $123.45"; 88 | const numberRegex = /\d+/g; 89 | 90 | const newText = text.replace(numberRegex, "0"); 91 | console.log(newText); // The total is $0.00 92 | ``` 93 | 94 | In this example, the regular expression /\d+/g matches any string that contains one or more digits (\d+) and ends with the end of the string ($). The g flag indicates that the regular expression should be matched globally, so that all occurrences of the pattern are matched, rather than just the first occurrence. 95 | 96 | - ### Searching for a string 97 | 98 | Regular expressions can be used to search for a string. Here's an example: 99 | 100 | ```javascript 101 | const text = "The total is $123.45"; 102 | const numberRegex = /\d+/g; 103 | const index = text.search(numberRegex); 104 | console.log(index); // 12 105 | ``` 106 | 107 | In this example, the regular expression /\d+/g matches any string that contains one or more digits (\d+) and ends with the end of the string ($). The g flag indicates that the regular expression should be matched globally, so that all occurrences of the pattern are matched, rather than just the first occurrence. 108 | 109 | ## Resources 110 | 111 | - [Regular Expressions in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) 112 | 113 | - [Regular Expressions in JavaScript](https://www.w3schools.com/js/js_regexp.asp) 114 | 115 | -------------------------------------------------------------------------------- /15.Error-handling/README.md: -------------------------------------------------------------------------------- 1 | ## Error Handling in javascript 2 | 3 | - **What is Error Handling in javascript?** 4 | 5 | Error handling in JavaScript is the process of anticipating, detecting, and resolving errors that may occur during the execution of a JavaScript program. There are several ways to handle errors in JavaScript: using try...catch, throw, finally, Error object, error handling in async functions, error handling in promises, error handling in callbacks, error handling in event listeners, and error handling in event handlers. 6 | 7 | - **Using try...catch** 8 | try-catch: The try-catch statement is used to handle exceptions that may occur in a block of code. The code that may throw an exception is enclosed in a try block, and the exception is caught and handled in the catch block. 9 | 10 | ```js 11 | 12 | // Example 1 13 | // try-catch example 14 | try { 15 | // code that may throw an exception 16 | } catch (err) { 17 | // code that handles the exception 18 | } 19 | 20 | // Example 2 21 | // try-catch example 22 | const asyncFunction = async () => { 23 | try { 24 | await Promise.reject('Error'); 25 | } catch (error) { 26 | console.log(error); 27 | } 28 | ``` 29 | 30 | - **Using throw** 31 | 32 | The throw statement is used to manually throw an exception. This is useful when you want to create your own custom error message. 33 | 34 | ```js 35 | // Example 1 36 | // throw example 37 | throw new Error('Something went wrong'); 38 | 39 | // Example 2 40 | // throw example 41 | function myFunction() { 42 | try { 43 | throw 'myException'; // generates an exception 44 | } 45 | catch (e) { 46 | // statements to handle any exceptions 47 | logMyErrors(e); // pass exception object to error handler 48 | } 49 | } 50 | ``` 51 | 52 | - **Using finally** 53 | 54 | The finally block is used to execute code after the try and catch blocks, regardless of whether an exception was thrown or not. 55 | 56 | ```js 57 | // Example 1 58 | // finally example 59 | try { 60 | // code that may throw an exception 61 | } catch (err) { 62 | // code that handles the exception 63 | } finally { 64 | // code that will always execute 65 | } 66 | 67 | // Example 2 68 | // finally example 69 | function myFunction() { 70 | try { 71 | throw 'myException'; // generates an exception 72 | } 73 | catch (e) { 74 | // statements to handle any exceptions 75 | logMyErrors(e); // pass exception object to error handler 76 | } 77 | finally { 78 | // statements to be executed 79 | // regardless of exception thrown or not 80 | } 81 | } 82 | ``` 83 | 84 | - **Error object** 85 | 86 | JavaScript provides several built-in error objects, such as Error, RangeError, TypeError, etc., which can be used to create custom error messages. 87 | 88 | ```js 89 | 90 | // Example 1 91 | // Error object example 92 | const error = new Error('Something went wrong'); 93 | 94 | // Example 2 95 | // RangeError object example 96 | const error = new RangeError('Something went wrong'); 97 | 98 | // Example 3 99 | // TypeError object example 100 | const error = new TypeError('Something went wrong'); 101 | ``` 102 | 103 | - **Error handling in async functions** 104 | 105 | The try-catch statement can be used to handle errors in async functions. The await keyword is used to wait for a promise to be resolved or rejected. 106 | 107 | ```js 108 | // Example 1 109 | // Error handling in async functions 110 | const asyncFunction = async () => { 111 | try { 112 | await Promise.reject('Error'); 113 | } catch (error) { 114 | console.log(error); 115 | } 116 | } 117 | 118 | ``` 119 | 120 | 121 | - **Error handling in promises** 122 | 123 | The catch() method is used to handle errors in promises. The catch() method returns a Promise and deals with rejected cases only. It behaves the same as the try-catch block for errors. 124 | 125 | ```js 126 | 127 | // Example 1 128 | // Error handling in promises 129 | const promise = new Promise((resolve, reject) => { 130 | reject('Error'); 131 | }); 132 | 133 | promise.catch((error) => { 134 | console.log(error); 135 | }); 136 | 137 | // Example 2 138 | 139 | // Error handling in promises 140 | const promise = new Promise((resolve, reject) => { 141 | reject('Error'); 142 | }); 143 | 144 | promise 145 | .then((data) => { 146 | console.log(data); 147 | }) 148 | .catch((error) => { 149 | console.log(error); 150 | }); 151 | ``` 152 | 153 | 154 | - **Error handling in callbacks** 155 | 156 | The callback function is the last argument of the function. The callback function is called after the function is executed. The callback function is used to handle errors in callbacks. 157 | 158 | ```js 159 | // Example 1 160 | 161 | // Error handling in callbacks 162 | const callbackFunction = (error, data) => { 163 | if (error) { 164 | console.log(error); 165 | } else { 166 | console.log(data); 167 | } 168 | }; 169 | 170 | const asyncFunction = (callback) => { 171 | callback('Error', null); 172 | }; 173 | 174 | asyncFunction(callbackFunction); 175 | 176 | // Example 2 177 | 178 | // Error handling in callbacks 179 | const callbackFunction = (error, data) => { 180 | if (error) { 181 | console.log(error); 182 | } else { 183 | console.log(data); 184 | } 185 | }; 186 | 187 | const asyncFunction = (callback) => { 188 | callback(null, 'Data'); 189 | }; 190 | 191 | 192 | ``` 193 | 194 | 195 | - **Error handling in event listeners** 196 | 197 | The addEventListener() method is used to handle errors in event listeners. The addEventListener() method attaches an event handler to the specified element. 198 | 199 | ```js 200 | 201 | // Example 1 202 | // Error handling in event listeners 203 | const button = document.querySelector('button'); 204 | 205 | button.addEventListener('click', () => { 206 | throw new Error('Something went wrong'); 207 | }); 208 | 209 | // Example 2 210 | 211 | // Error handling in event listeners 212 | const button = document.querySelector('button'); 213 | 214 | button.addEventListener('click', () => { 215 | console.log('Button clicked'); 216 | }); 217 | ``` 218 | 219 | - **Error handling in event handlers** 220 | 221 | The event handler is a function that is called when an event occurs. The event handler is used to handle errors in event handlers. 222 | 223 | ```js 224 | 225 | // Example 1 226 | // Error handling in event handlers 227 | const button = document.querySelector('button'); 228 | 229 | button.onclick = () => { 230 | throw new Error('Something went wrong'); 231 | }; 232 | 233 | 234 | ``` 235 | 236 | 237 | 238 | - **What is the difference between throw and reject?** 239 | 240 | The throw statement is used to manually throw an exception. The reject() method is used to reject a promise. The throw statement is used to create custom error messages. The reject() method is used to create custom error messages for promises. 241 | 242 | ```js 243 | 244 | // Example 1 245 | // throw example 246 | throw new Error('Something went wrong'); 247 | 248 | // Example 2 249 | // reject example 250 | const promise = new Promise((resolve, reject) => { 251 | reject('Error'); 252 | }); 253 | 254 | promise.catch((error) => { 255 | console.log(error); 256 | }); 257 | ``` 258 | 259 | 260 | Error is important in javascript and you must know how to handle it. I hope this article will help you to understand error handling in javascript. If you have any questions, please leave a comment below. Thank you for reading this article. Happy coding! 261 | 262 | 263 | You can find the source code of this article here: 264 | 265 | ## Resources 266 | 267 | - [Error handling in JavaScript](https://www.freecodecamp.org/news/error-handling-in-javascript/) 268 | 269 | - [Error handling in JavaScript](https://www.javascripttutorial.net/javascript-error-handling/) 270 | 271 | - [Error handling in JavaScript](https://www.tutorialsteacher.com/javascript/error-handling-in-javascript) 272 | -------------------------------------------------------------------------------- /16.Promises/README.md: -------------------------------------------------------------------------------- 1 | ## Javascript Promises 2 | JavaScript Promise is a powerful feature that allows asynchronous operations in JavaScript to be handled in a more organized and efficient way. Promises are a way to handle the results of asynchronous operations, such as network requests, file I/O, or database queries. 3 | 4 | A Promise represents a value that is not yet available, but will be available at some point in the future. It is a placeholder for a future value, or the result of an asynchronous operation. A Promise can be in one of three states: 5 | 6 | 7 | * **Pending**: The initial state of a Promise. The Promise is neither fulfilled nor rejected. 8 | 9 | * **Fulfilled**: The state of a Promise representing a successful operation. 10 | 11 | * **Rejected**: The state of a Promise representing a failed operation. 12 | 13 | Here is and example of a how to create promise : 14 | 15 | ```javascript 16 | let promise = new Promise(function(resolve, reject) { 17 | // executor (the producing code, "singer") 18 | }); 19 | ``` 20 | 21 | 22 | A Promise is an object that represents the eventual result of an asynchronous operation. It is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. 23 | 24 | Here is a simple example of a Promise: 25 | 26 | ```javascript 27 | let promise = new Promise(function(resolve, reject) { 28 | setTimeout(() => resolve("done!"), 1000) 29 | }); 30 | 31 | // resolve runs the first function in .then 32 | promise.then( 33 | result => alert(result), // shows "done!" after 1 second 34 | error => alert(error) // doesn't run 35 | ); 36 | ``` 37 | 38 | 39 | The Promise constructor takes one argument, a function, with two parameters, resolve and reject. These are functions that are pre-defined by JavaScript. The resolve function is called when the asynchronous operation is successful and the reject function is called when the asynchronous operation fails. The resolve and reject functions are called with a single argument, which is the value with which the promise is fulfilled or rejected. In the example above, the promise is fulfilled with the string "done!" after one second 40 | 41 | 42 | 43 | 44 | The then method takes two arguments, callback functions for the success and failure cases of the Promise. The first callback is called when the promise is resolved and the second callback is called when the promise is rejected. In the example above, the promise is resolved with the string "done!" after one second, so the first callback is called and the alert shows "done!". 45 | 46 | Here is an example of a Promise that is rejected with an error: 47 | 48 | ```javascript 49 | 50 | // the function is executed automatically when the promise is constructed 51 | 52 | // after 1 second signal that the job is finished with an error 53 | 54 | let promise = new Promise(function(resolve, reject) { 55 | setTimeout(() => reject(new Error("Whoops!")), 1000); 56 | }); 57 | 58 | 59 | // reject runs the second function in .then 60 | promise.then( 61 | result => alert(result), // doesn't run 62 | error => alert(error) // shows "Error: Whoops!" after 1 second 63 | ); 64 | ``` 65 | 66 | Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Promises provide a better way of handling asynchronous operations that are easier to read and maintain. 67 | 68 | 69 | 70 | ```javascript 71 | let promise = new Promise(function(resolve, reject) { 72 | // executor (the producing code, "singer") 73 | }); 74 | ``` 75 | 76 | 77 | To handle the result of a Promise, you can attach callbacks to the Promise using the then and catch methods. The then method is called when the Promise is fulfilled, and the catch method is called when the Promise is rejected. 78 | 79 | 80 | Here is an example of using then and catch to handle the result of a Promise: 81 | 82 | ```javascript 83 | 84 | promise 85 | .then(result => { 86 | // Handle the result of the successful operation 87 | }) 88 | .catch(error => { 89 | // Handle the error from the failed operation 90 | }); 91 | 92 | ``` 93 | 94 | 95 | Promises can also be chained together using the then method, which returns a new Promise. This allows for a sequence of asynchronous operations to be performed in order. 96 | 97 | Here is an example of chaining Promises: 98 | 99 | ```javascript 100 | promise1 101 | .then(result1 => { 102 | // Perform another asynchronous operation using result1 103 | return promise2; 104 | }) 105 | .then(result2 => { 106 | // Perform another asynchronous operation using result2 107 | return promise3; 108 | }) 109 | .then(result3 => { 110 | // Handle the final result of the asynchronous operations 111 | }) 112 | .catch(error => { 113 | // Handle any errors from the asynchronous operations 114 | }); 115 | 116 | ``` 117 | 118 | Let take look some core concepts of Promises: 119 | 120 | ## Pending Promises: 121 | 122 | A pending Promise is a Promise that is not yet settled, meaning that it has neither fulfilled nor rejected. It represents an asynchronous operation that is still in progress and has not yet produced a result or an error. 123 | 124 | When you create a Promise, it starts out in the pending state. The Promise remains in this state until it is either fulfilled or rejected. During this time, you can attach callbacks to the Promise using the then method. These callbacks will be executed when the Promise is settled, whether it is fulfilled or rejected. 125 | 126 | Here is an example of a pending Promise: 127 | 128 | ```javascript 129 | const promise = new Promise((resolve, reject) => { 130 | // Perform some asynchronous operation 131 | // If the operation is successful, call resolve with the result 132 | // If the operation fails, call reject with an error object 133 | }); 134 | 135 | // The Promise is now in the pending state 136 | 137 | ``` 138 | 139 | In the above example, the Promise is created but it is still in the pending state because the asynchronous operation has not yet completed. Once the operation is complete, the Promise will either be fulfilled or rejected, depending on whether it was successful or not. 140 | 141 | To handle the result of the Promise when it is settled, you can attach callbacks to it using the then method. Here is an example: 142 | 143 | ```javascript 144 | 145 | 146 | promise 147 | .then(result => { 148 | // Handle the result of the successful operation 149 | }) 150 | .catch(error => { 151 | // Handle the error from the failed operation 152 | }); 153 | 154 | ``` 155 | 156 | 157 | 158 | ## Fulfilled Promises: 159 | 160 | A fulfilled Promise is a Promise that has been successfully completed. It represents an asynchronous operation that has completed successfully and produced a result. 161 | 162 | When you create a Promise, it starts out in the pending state. The Promise remains in this state until it is either fulfilled or rejected. If the asynchronous operation is successful, the Promise is fulfilled with the result of the operation. If the asynchronous operation fails, the Promise is rejected with an error object. 163 | 164 | 165 | Here is an example of a fulfilled Promise: 166 | 167 | ```javascript 168 | 169 | const promise = new Promise((resolve, reject) => { 170 | // Perform some asynchronous operation 171 | // If the operation is successful, call resolve with the result 172 | // If the operation fails, call reject with an error object 173 | resolve('Success!'); 174 | }); 175 | 176 | 177 | 178 | // The Promise is now in the pending state 179 | 180 | // The Promise is now in the fulfilled state 181 | 182 | ``` 183 | 184 | In the above example, the Promise is created but it is still in the pending state because the asynchronous operation has not yet completed. Once the operation is complete, the Promise is fulfilled with the result of the operation. 185 | 186 | 187 | To handle the result of the Promise when it is settled, you can attach callbacks to it using the then method. Here is an example: 188 | 189 | ```javascript 190 | 191 | promise 192 | .then(result => { 193 | // Handle the result of the successful operation 194 | }) 195 | .catch(error => { 196 | // Handle the error from the failed operation 197 | }); 198 | 199 | ``` 200 | 201 | 202 | ## Rejected Promises: 203 | 204 | A rejected Promise is a Promise that has been rejected. It represents an asynchronous operation that has failed and produced an error. 205 | 206 | When you create a Promise, it starts out in the pending state. The Promise remains in this state until it is either fulfilled or rejected. If the asynchronous operation is successful, the Promise is fulfilled with the result of the operation. If the asynchronous operation fails, the Promise is rejected with an error object. 207 | 208 | 209 | Here is an example of a rejected Promise: 210 | 211 | ```javascript 212 | 213 | const promise = new Promise((resolve, reject) => { 214 | // Perform some asynchronous operation 215 | // If the operation is successful, call resolve with the result 216 | // If the operation fails, call reject with an error object 217 | reject(new Error('Error!')); 218 | }); 219 | 220 | 221 | 222 | // The Promise is now in the pending state 223 | 224 | // The Promise is now in the rejected state 225 | 226 | ``` 227 | 228 | 229 | In the above example, the Promise is created but it is still in the pending state because the asynchronous operation has not yet completed. Once the operation is complete, the Promise is rejected with the error object. 230 | 231 | 232 | To handle the result of the Promise when it is settled, you can attach callbacks to it using the then method. Here is an example: 233 | 234 | ```javascript 235 | 236 | promise 237 | .then(result => { 238 | // Handle the result of the successful operation 239 | }) 240 | .catch(error => { 241 | // Handle the error from the failed operation 242 | }); 243 | 244 | ``` 245 | 246 | ## Promise Chaining: 247 | 248 | Promises can be chained together using the then method, which returns a new Promise. This allows for a sequence of asynchronous operations to be performed in order. 249 | 250 | Here is an example of chaining Promises: 251 | 252 | ```javascript 253 | 254 | promise1 255 | .then(result1 => { 256 | // Perform another asynchronous operation using result1 257 | return promise2; 258 | }) 259 | .then(result2 => { 260 | // Perform another asynchronous operation using result2 261 | return promise3; 262 | }) 263 | .then(result3 => { 264 | // Handle the final result of the asynchronous operations 265 | }) 266 | .catch(error => { 267 | // Handle any errors from the asynchronous operations 268 | }); 269 | 270 | ``` 271 | 272 | 273 | In the above example, the first then method is called when the promise1 is fulfilled. The result of the promise1 is passed to the first then method as the result1 parameter. The first then method performs another asynchronous operation using the result1 and returns a new Promise, promise2. The second then method is called when the promise2 is fulfilled. The result of the promise2 is passed to the second then method as the result2 parameter. The second then method performs another asynchronous operation using the result2 and returns a new Promise, promise3. The third then method is called when the promise3 is fulfilled. The result of the promise3 is passed to the third then method as the result3 parameter. The third then method handles the final result of the asynchronous operations. If any of the asynchronous operations fail, the catch method is called with the error object. 274 | 275 | 276 | ## Promise.all: 277 | 278 | The Promise.all method takes an array of Promises as an argument and returns a single Promise. The single Promise returned by the Promise.all method is fulfilled when all of the Promises in the argument array are fulfilled. The single Promise returned by the Promise.all method is rejected when any of the Promises in the argument array are rejected. 279 | 280 | 281 | Here is an example of using the Promise.all method: 282 | 283 | ```javascript 284 | 285 | const promise1 = new Promise((resolve, reject) => { 286 | setTimeout(resolve, 1000, 'one'); 287 | }); 288 | 289 | const promise2 = new Promise((resolve, reject) => { 290 | setTimeout(resolve, 2000, 'two'); 291 | }); 292 | 293 | const promise3 = new Promise((resolve, reject) => { 294 | setTimeout(resolve, 3000, 'three'); 295 | }); 296 | 297 | 298 | Promise.all([promise1, promise2, promise3]) 299 | .then(values => { 300 | // Handle the result of the asynchronous operations 301 | }) 302 | .catch(error => { 303 | // Handle any errors from the asynchronous operations 304 | }); 305 | 306 | ``` 307 | 308 | 309 | In the above example, three Promises are created, promise1, promise2, and promise3. The Promise.all method is called with an array containing the three Promises as an argument. The Promise returned by the Promise.all method is fulfilled when all of the Promises in the argument array are fulfilled. The Promise returned by the Promise.all method is rejected when any of the Promises in the argument array are rejected. The then method is called when the Promise returned by the Promise.all method is fulfilled. The values parameter contains an array of the results of the asynchronous operations. The catch method is called when the Promise returned by the Promise.all method is rejected. The error parameter contains the error object. 310 | 311 | 312 | 313 | In conclusion, Promises are a great way to handle asynchronous operations in JavaScript. They are a great alternative to using callbacks and they make your code easier to read and maintain. I hope you found this article helpful. If you have any questions or comments, please leave them below. Thanks for reading! 314 | 315 | 316 | You can find more Resources below: 317 | 318 | ## Resources: 319 | 320 | * [MDN - Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 321 | 322 | * [MDN - Promise.prototype.then](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) 323 | 324 | * [MDN - Promise.prototype.catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) 325 | 326 | * [MDN - Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) 327 | 328 | * [MDN - Promise.resolve](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve) 329 | 330 | * [MDN - Promise.reject](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject) 331 | 332 | 333 | ## Other Articles: 334 | 335 | * [JavaScript Promises for Dummies](https://medium.com/@stasonmars/%D0%BF%D1%80%D0%BE%D0%BC%D0%B8%D1%81%D1%8B-%D0%B2-javascript-%D0%B4%D0%BB%D1%8F-%D0%BD%D0%B0%D1%87%D0%B8%D0%BD%D0%B0%D1%8E%D1%89%D0%B8%D1%85-1a8b0d9a8b0d) 336 | 337 | * [JavaScript Promises for Dummies - Part 2](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-2-3f1b4b0b0d5a) 338 | 339 | * [JavaScript Promises for Dummies - Part 3](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-3-4f2a5e6a3f1b) 340 | 341 | * [JavaScript Promises for Dummies - Part 4](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-4-5f1b4b0b0d5a) 342 | 343 | * [JavaScript Promises for Dummies - Part 5](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-5-6f1b4b0b0d5a) 344 | 345 | * [JavaScript Promises for Dummies - Part 6](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-6-7f1b4b0b0d5a) 346 | 347 | * [JavaScript Promises for Dummies - Part 7](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-7-8f1b4b0b0d5a) 348 | 349 | * [JavaScript Promises for Dummies - Part 8](https://medium.com/@stasonmars/javascript-promises-for-dummies-part-8-9f1b4b0b0d5a) 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | -------------------------------------------------------------------------------- /17.ES6+-features/README.md: -------------------------------------------------------------------------------- 1 | ## Javascript ES6+ features 2 | 3 | - **What is ES6?** 4 | ES6 or the ECMAScript 2015 is the 6th and major edition of the ECMAScript language specification standard. It defines the standard for the implementation of JavaScript and it has become much more popular than the previous edition ES5. 5 | 6 | ES6 comes with significant changes to the JavaScript language. It brought several new features like, let and const keyword, rest and spread operators, template literals, classes, modules and many other enhancements to make JavaScript programming easier and more fun. In this article, we will discuss some of the best and most popular ES6 features that we can use in your everyday JavaScript coding. 7 | 8 | let take a look at some of the most popular ES6 features. 9 | 10 | - **let and const** 11 | The let and const keywords are used to declare variables in ES6. The let keyword is used to declare a variable that can be reassigned later in the program. The const keyword is used to declare a variable that cannot be reassigned later in the program. 12 | 13 | ```js 14 | let name = "Clifford"; 15 | name = "Isaiah"; 16 | console.log(name); // Isaiah 17 | 18 | // let and const are block scoped 19 | // let can be redeclare 20 | // let must be initialized during declaration 21 | // let can be object but cant be reassigned 22 | 23 | const age = 25; 24 | age = 30; // TypeError: Assignment to constant variable. 25 | 26 | // let and const are block scoped 27 | // const cant be redeclare 28 | // const must be initialized during declaration 29 | // const can be object but cant be reassigned 30 | ``` 31 | 32 | - **Arrow functions** 33 | Arrow functions are a new way to write functions in ES6. Arrow functions are a shorter way to write functions in JavaScript. Arrow functions are always anonymous. They cannot be named. Arrow functions are also called fat arrow functions. 34 | 35 | ```js 36 | // Define a function using the arrow function syntax 37 | const myFunction = (name) => { 38 | console.log(`Hello, ${name}!`); 39 | }; 40 | 41 | myFunction("Alice"); // Output: "Hello, Alice!" 42 | 43 | // ES5 44 | function add(a, b) { 45 | return a + b; 46 | } 47 | 48 | add(1, 2); // 3 49 | // ES6 50 | 51 | const add = (a, b) => { 52 | return a + b; 53 | }; 54 | add(4, 2); // 6 55 | 56 | // ES6 57 | const add = (a, b) => a + b; 58 | 59 | add(4, 2); // 6 60 | 61 | // ES6 62 | 63 | // if the function has only one parameter, you can omit the parentheses 64 | // if the function has only one statement, you can omit the curly braces and the return keyword 65 | // if the function has no parameter, you must include the parentheses 66 | ``` 67 | 68 | - **Template literals** 69 | Template literals are a new way to create strings in ES6. Template literals are enclosed by backticks (`) instead of single or double quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). 70 | 71 | ```js 72 | // Use template literals to create a multiline string with variables 73 | const name = "Bob"; 74 | const age = 42; 75 | const greeting = `Hello, my name is ${name} and I am ${age} years old.`; 76 | console.log(greeting); // Output: "Hello, my name is Bob and I am 42 years old." 77 | 78 | // ES5 79 | var name = "Clifford"; 80 | var age = 25; 81 | var message = "Hello, my name is " + name + " and I am " + age + " years old."; 82 | console.log(message); // Output: "Hello, my name is Clifford and I am 25 years old." 83 | 84 | // ES6 85 | 86 | const name = "Clifford"; 87 | const age = 25; 88 | const message = `Hello, my name is ${name} and I am ${age} years old.`; 89 | 90 | console.log(message); // Output: "Hello, my name is Clifford and I am 25 years old." 91 | 92 | // Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). 93 | // Template literals are enclosed by backticks (`) instead of single or double quotes. 94 | ``` 95 | 96 | - **Destructuring** 97 | Destructuring is a new way to extract data from arrays and objects in ES6. Destructuring is a convenient way to extract data from arrays and objects. It allows you to assign the values of an array or object to variables in a single line of code. 98 | 99 | ```js 100 | // Destructuring arrays 101 | const names = ["Alice", "Bob", "Charlie", "Dave"]; 102 | const [name1, name2, name3, name4] = names; 103 | console.log(name1); // Output: "Alice" 104 | 105 | // Destructuring objects 106 | 107 | const person = { 108 | name: "Alice", 109 | age: 25, 110 | address: { 111 | city: "New York", 112 | state: "NY", 113 | }, 114 | }; 115 | 116 | const { name, age, address } = person; 117 | console.log(name); // Output: "Alice" 118 | console.log(age); // Output: 25 119 | console.log(address); // Output: {city: "New York", state: "NY"} 120 | 121 | // Destructuring nested objects 122 | 123 | const person = { 124 | name: "Alice", 125 | age: 25, 126 | address: { 127 | city: "New York", 128 | state: "NY", 129 | }, 130 | }; 131 | 132 | const { 133 | name, 134 | age, 135 | address: { city, state }, 136 | } = person; 137 | 138 | console.log(name); // Output: "Alice" 139 | console.log(age); // Output: 25 140 | console.log(city); // Output: "New York" 141 | console.log(state); // Output: "NY" 142 | 143 | // destructuring is a convenient way to extract data from arrays and objects. It allows you to assign the values of an array or object to variables in a single line of code. 144 | ``` 145 | 146 | - **Rest and spread operators** 147 | The rest and spread operators are used to work with arrays in ES6. The rest operator allows you to represent an indefinite number of arguments as an array. The spread operator allows you to expand an array into its elements. 148 | 149 | ```js 150 | // Use the rest operator to represent an indefinite number of arguments as an array 151 | 152 | function sum(...numbers) { 153 | return numbers.reduce((total, number) => total + number, 0); 154 | } 155 | 156 | console.log(sum(1, 2, 3, 4, 5)); // Output: 15 157 | 158 | // Use the spread operator to expand an array into its elements 159 | 160 | const numbers = [1, 2, 3, 4, 5]; 161 | 162 | console.log(...numbers); // Output: 1 2 3 4 5 163 | 164 | // The rest operator allows you to represent an indefinite number of arguments as an array. 165 | 166 | // The spread operator allows you to expand an array into its elements. 167 | ``` 168 | 169 | - **Classes** 170 | Classes are a new way to create objects in ES6. Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in ES6 are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics. 171 | 172 | ```js 173 | 174 | 175 | // Define a class 176 | class Person { 177 | constructor(name) { 178 | this.name = name; 179 | } 180 | 181 | greet() { 182 | console.log(`Hello, my name is ${this.name}!`); 183 | } 184 | } 185 | 186 | // Create an object from a class 187 | const person = new Person("Alice"); 188 | 189 | person.greet(); // Output: "Hello, my name is Alice!" 190 | 191 | // Define a class 192 | class Person { 193 | constructor(name) { 194 | this.name = name; 195 | } 196 | 197 | greet() { 198 | console.log(`Hello, my name is ${this.name}!`); 199 | } 200 | } 201 | 202 | // Create an object from a class 203 | const person = new Person("Alice"); 204 | 205 | person.greet(); // Output: "Hello, my name is Alice!" 206 | 207 | 5 class-like semantics. 208 | 209 | ``` 210 | 211 | Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in ES6 are built on prototypes but also have some syntax and semantics that are not shared with ES 212 | 213 | - **Modules** 214 | Modules are a new way to organize code in ES6. Modules are reusable pieces of code that can be exported from one program and imported for use in another program. Modules are declared using the export and import keywords. 215 | 216 | ```js 217 | // Export a module 218 | export const name = "Alice"; 219 | 220 | // Import a module 221 | import { name } from "./module.js"; 222 | 223 | console.log(name); // Output: "Alice" 224 | 225 | // Export a module default 226 | export default function add(a, b) { 227 | return a + b; 228 | } 229 | 230 | // Import a module default 231 | 232 | import add from "./module.js"; 233 | 234 | console.log(add(1, 2)); // Output: 3 235 | 236 | // i 237 | ``` 238 | 239 | - **Promises** 240 | Promises are a new way to handle asynchronous operations in ES6. Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. A Promise has three states: pending, resolved, and rejected. 241 | 242 | ```js 243 | // Create a promise 244 | const promise = new Promise((resolve, reject) => { 245 | const number = Math.floor(Math.random() * 10); 246 | 247 | if (number % 2 === 0) { 248 | resolve(number); 249 | } else { 250 | reject(number); 251 | } 252 | }); 253 | 254 | // Consume a promise 255 | 256 | promise 257 | .then((number) => { 258 | console.log(`Success: ${number} is even.`); 259 | }) 260 | .catch((number) => { 261 | console.log(`Error: ${number} is odd.`); 262 | }); 263 | ``` 264 | 265 | Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. A Promise has three states: pending, resolved, and rejected. 266 | 267 | - **Generators** 268 | Generators are a new way to create iterators in ES6. Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generators are declared using the function\* syntax. 269 | 270 | ```js 271 | // Define a generator 272 | 273 | function* idMaker() { 274 | let index = 0; 275 | 276 | while (index < 3) { 277 | yield index++; 278 | } 279 | } 280 | 281 | // Create an iterator from a generator 282 | 283 | const iterator = idMaker(); 284 | 285 | console.log(iterator.next().value); // Output: 0 286 | console.log(iterator.next().value); // Output: 1 287 | ``` 288 | 289 | Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generators are declared using the function\* syntax. 290 | 291 | - **Map and Set** 292 | Map and Set are new data structures in ES6. Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type. Set is a collection of values, where each value may occur only once. It’s just like an Array of unique values, but the main difference is that Set doesn’t allow to store the same value twice. 293 | 294 | ```js 295 | // Create a map 296 | 297 | const map = new Map(); 298 | 299 | map.set("name", "Alice"); 300 | map.set("age", 25); 301 | 302 | console.log(map.get("name")); // Output: "Alice" 303 | 304 | // Create a set 305 | 306 | const set = new Set(); 307 | 308 | set.add("name"); 309 | set.add("age"); 310 | 311 | console.log(set.has("name")); // Output: true 312 | ``` 313 | 314 | Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type. Set is a collection of values, where each value may occur only once. It’s just like an Array of unique values, but the main difference is that Set doesn’t allow to store the same value twice. 315 | 316 | You can read more about ES6 in the below links: 317 | 318 | ## Resource 319 | 320 | - [ES6](https://www.w3schools.com/js/js_es6.asp) 321 | -------------------------------------------------------------------------------- /18.Generators-and-async-await/README.md: -------------------------------------------------------------------------------- 1 | ## Generators and async/await in JavaScript 2 | 3 | ### What are generators? 4 | 5 | Generators are a type of function in JavaScript that can be paused and resumed, allowing for the generation of a series of values on demand. Generators are declared using the function\* syntax and use the yield keyword to return a value from the generator function. 6 | 7 | Here's an example of a generator function that generates an infinite series of Fibonacci numbers: 8 | 9 | ```js 10 | // Generator function that generates an infinite series of Fibonacci numbers 11 | 12 | function* fibonacci() { 13 | let [prev, curr] = [0, 1]; 14 | while (true) { 15 | [prev, curr] = [curr, prev + curr]; 16 | yield curr; 17 | } 18 | } 19 | ``` 20 | 21 | To use the fibonacci generator, we can create an iterator object and call its next method to get the next value in the sequence: 22 | 23 | ```js 24 | // Create an iterator object from the generator function 25 | 26 | const sequence = fibonacci(); 27 | sequence.next(); // { value: 1, done: false } 28 | sequence.next(); // { value: 2, done: false } 29 | sequence.next(); // { value: 3, done: false } 30 | sequence.next(); // { value: 5, done: false } 31 | sequence.next(); // { value: 8, done: false } 32 | sequence.next(); // { value: 13, done: false } 33 | ``` 34 | 35 | Generators are useful for creating custom iterators and for implementing lazy evaluation, where values are generated only when needed. 36 | 37 | ### async/await function in javascript ? 38 | 39 | async/await is a language feature introduced in ECMAScript 2017 that simplifies asynchronous code by allowing developers to write asynchronous code that looks and behaves like synchronous code. 40 | 41 | The async keyword is used to declare a function that returns a promise, and the await keyword is used to pause the execution of the function until a promise is resolved. 42 | 43 | Here's an example of an async function that retrieves data from an API: 44 | 45 | ```js 46 | 47 | // Async function that retrieves data from an API 48 | 49 | async function getData() { 50 | 51 | const response = await fetch('https://api.example.com/data'); 52 | const data = await response.json(); 53 | return data; 54 | } 55 | 56 | ``` 57 | 58 | In the getData function, the await keyword is used to pause the function until the response is received from the API and until the data is parsed as JSON. 59 | 60 | To use the getData function, we can call it like a regular function and use the then method or the await keyword to retrieve the data: 61 | 62 | ```js 63 | getData().then(data => console.log(data)); 64 | // or 65 | const data = await getData(); 66 | console.log(data); 67 | 68 | ``` 69 | 70 | The async keyword is used to declare a function that returns a promise, and the await keyword is used to pause the execution of the function until a promise is resolved. 71 | 72 | async/await makes it easier to write asynchronous code that is easier to read, write, and maintain. It also allows for better error handling, as any errors that occur in an async function can be caught using a try-catch block. 73 | 74 | 75 | ### What is the difference between async/await and generators? 76 | 77 | async/await and generators are both used to write asynchronous code in JavaScript. However, there are some key differences between the two: 78 | 79 | - Generators are functions that can be paused and resumed, while async functions are functions that return promises. 80 | - Generators can be used to create custom iterators, while async functions can only be used to create promises. 81 | 82 | ### What are the benefits of async/await? 83 | 84 | Async/await is a language feature that was introduced in ECMAScript 2017. It simplifies asynchronous code by allowing developers to write asynchronous code that looks and behaves like synchronous code. 85 | 86 | -------------------------------------------------------------------------------- /19.Higher-order-functions/README.md: -------------------------------------------------------------------------------- 1 | ## Higher order functions in javascript 2 | 3 | ### What is a higher order function? 4 | 5 | In JavaScript, a higher order function is a function that takes one or more functions as arguments or returns a function as its result. This makes it possible to create more flexible and reusable code. 6 | 7 | Here are some examples of higher order functions in JavaScript: 8 | 9 | - map() 10 | 11 | The map() function is used to apply a function to each element in an array and return a new array with the results. Here's an example: 12 | 13 | ```js 14 | const numbers = [1, 2, 3, 4, 5]; 15 | 16 | const doubled = numbers.map((number) => number * 2); 17 | 18 | console.log(doubled); // [2, 4, 6, 8, 10] 19 | ``` 20 | 21 | in the above example, the map() function is used to apply the function number => number \* 2 to each element in the numbers array. The result is a new array with the doubled values. 22 | 23 | - filter() 24 | 25 | The filter() function is used to filter out elements from an array that don't meet a certain condition. Here's an example: 26 | 27 | ```js 28 | const numbers = [ 29 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30 | ]; 31 | 32 | const even = numbers.filter((number) => number % 2 === 0); 33 | 34 | console.log(even); // [2, 4, 6, 8, 10] 35 | ``` 36 | 37 | in the above example, the filter() function is used to filter out the odd numbers from the numbers array. The result is a new array with the even numbers. 38 | 39 | - reduce() 40 | 41 | The reduce() function is used to reduce an array to a single value by applying a function to each element in the array. 42 | 43 | Here's an example: 44 | 45 | ```js 46 | const numbers = [1, 2, 3, 4, 5]; 47 | 48 | const sum = numbers.reduce((total, number) => total + number, 0); 49 | 50 | console.log(sum); // 15 51 | ``` 52 | 53 | 54 | in the above example, the reduce() function is used to sum all the numbers in the numbers array. The result is a single value. 55 | 56 | 57 | - forEach() 58 | 59 | The forEach() function is used to apply a function to each element in an array. Here's an example: 60 | 61 | ```js 62 | 63 | const numbers = [1, 2, 3, 4, 5]; 64 | const numberAdd = 2 65 | 66 | numbers.forEach((number) => number * numberAdd); 67 | console.log(numbers); // [2, 4, 6, 8, 10] 68 | ``` 69 | 70 | 71 | 72 | in the above example, the forEach() function is used to apply the function number => number \* 2 to each element in the numbers array. The result is a new array with the doubled values. 73 | 74 | 75 | - every() 76 | 77 | The every() function is used to check if all elements in an array meet a certain condition. Here's an example: 78 | 79 | ```js 80 | 81 | const numbers = [1, 2, 3, 4, 5]; 82 | 83 | const allEven = numbers.every((number) => number % 2 === 0); 84 | 85 | console.log(allEven); // false 86 | ``` 87 | 88 | 89 | in the above example, the every() function is used to check if all the numbers in the numbers array are even. The result is a boolean value. 90 | 91 | 92 | - some() 93 | 94 | The some() function is used to check if at least one element in an array meets a certain condition. Here's an example: 95 | 96 | ```js 97 | 98 | const numbers = [1, 2, 3, 4, 5]; 99 | 100 | const someEven = numbers.some((number) => number % 2 === 0); 101 | 102 | console.log(someEven); // true 103 | ``` 104 | 105 | 106 | 107 | in the above example, the some() function is used to check if at least one of the numbers in the numbers array is even. The result is a boolean value. 108 | 109 | 110 | - find() 111 | 112 | The find() function is used to find the first element in an array that meets a certain condition. Here's an example: 113 | 114 | ```js 115 | 116 | const numbers = [1, 2, 3, 4, 5]; 117 | 118 | const firstEven = numbers.find((number) => number % 2 === 0); 119 | 120 | console.log(firstEven); // 2 121 | ``` 122 | 123 | 124 | in the above example, the find() function is used to find the first even number in the numbers array. The result is the first even number. 125 | 126 | 127 | - findIndex() 128 | 129 | The findIndex() function is used to find the index of the first element in an array that meets a certain condition. Here's an example: 130 | 131 | ```js 132 | 133 | const numbers = [1, 2, 3, 4, 5]; 134 | 135 | const firstEvenIndex = numbers.findIndex((number) => number % 2 === 0); 136 | 137 | console.log(firstEvenIndex); // 1 138 | ``` 139 | 140 | 141 | in the above example, the findIndex() function is used to find the index of the first even number in the numbers array. The result is the index of the first even number. 142 | 143 | 144 | 145 | ### Why use higher order functions? 146 | 147 | Higher order functions are useful because they allow you to create more flexible and reusable code. Here are some examples of how you can use higher order functions to create more flexible and reusable code: 148 | 149 | - You can use the map() function to apply a function to each element in an array and return a new array with the results. This makes it possible to create a function that returns a new array with the doubled values of the numbers in an array: 150 | 151 | 152 | 153 | You can read more about higher oder functions in javascrpt at below link 154 | 155 | 156 | ## Resources 157 | 158 | - [freecodecamp](https://www.freecodecamp.org/news/higher-order-functions-in-javascript-d9101f9cf528/) 159 | 160 | - [javascript.info](https://javascript.info/higher-order-functions) 161 | 162 | - [javascripttutorial.net](https://www.javascripttutorial.net/javascript-higher-order-functions/) 163 | -------------------------------------------------------------------------------- /20.Functional-programming/README.md: -------------------------------------------------------------------------------- 1 | ## Function Pogroming in Javascript 2 | 3 | Functional programming is a programming paradigm that emphasizes the use of functions to write programs. In functional programming, functions are treated as first-class citizens, meaning that they can be passed as arguments to other functions, returned as values from functions, and stored in variables or data structures. JavaScript is a multi-paradigm language that supports functional programming, among other programming paradigms. 4 | 5 | Functional programming in JavaScript involves writing code that focuses on creating pure functions and avoiding side effects. A pure function is a function that always returns the same output for the same input and does not modify any state outside of its scope. This makes it easier to reason about the behavior of the code and helps avoid bugs caused by unexpected changes to state. 6 | 7 | - Higher-order functions : A higher-order function is a function that takes a function as an argument or returns a function as a return value. Higher-order functions are often used to abstract or isolate actions, effects, or async flow control using callback functions, promises, or monads. 8 | 9 | here is an example of a higher-order function that takes a function as an argument: 10 | 11 | ```js 12 | // Higher-order function 13 | 14 | function higherOrderFunction(callback) { 15 | return callback(); 16 | } 17 | function callbackFunction() { 18 | console.log("I am a callback function!"); 19 | } 20 | higherOrderFunction(callbackFunction); // Output: I am a callback function! 21 | ``` 22 | 23 | - Pure functions : A pure function is a function that always returns the same output for the same input and does not modify any state outside of its scope. This makes it easier to reason about the behavior of the code and helps avoid bugs caused by unexpected changes to state. 24 | 25 | ```js 26 | // Pure function 27 | 28 | function sum(a, b) { 29 | return a + b; 30 | } 31 | sum(1, 2); // Output: 3 32 | ``` 33 | 34 | - Immutability : Immutability is a concept that is often used in functional programming. In JavaScript, this means that data structures cannot be modified after they are created. Instead, new data structures are created that contain the modified values. This makes it easier to reason about the state of the program and helps avoid bugs caused by unexpected changes to state. 35 | Here is an example of an immutable array: 36 | 37 | ```js 38 | // Immutable array 39 | 40 | const numbers = [1, 2, 3]; 41 | const newNumbers = [...numbers, 4]; // Output: [1, 2, 3, 4] 42 | ``` 43 | 44 | - Recursion : Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. Recursion is often used to traverse data structures such as trees and graphs. Here is an example of a recursive function that traverses a tree: 45 | 46 | ```js 47 | // Recursive function 48 | 49 | function traverseTree(node) { 50 | if (node === null) { 51 | return; 52 | } 53 | traverseTree(node.left); 54 | traverseTree(node.right); 55 | } 56 | ``` 57 | 58 | - Currying : Currying is a technique for transforming a function that takes multiple arguments into a sequence of functions that each take a single argument. Currying is often used to create higher-order functions. Here is an example of a curried function: 59 | 60 | ```js 61 | // Curried function 62 | 63 | function curriedAdd(a) { 64 | return function (b) { 65 | return a + b; 66 | }; 67 | } 68 | const addOne = curriedAdd(1); 69 | const addTen = curriedAdd(10); 70 | addOne(2); // Output: 3 addTen(2); // Output: 12 71 | ``` 72 | 73 | - Partial application : Partial application is a technique for creating a new function by fixing some of the arguments of an existing function. This can be useful when you want to create a new function with some of the arguments already set. Here is an example of a partially applied function: 74 | 75 | ```js 76 | // Partially applied function 77 | 78 | function add(a, b) { 79 | return a + b; 80 | } 81 | const addOne = add.bind(null, 1); 82 | addOne(2); // Output: 3 83 | ``` 84 | 85 | - Memoization : Memoization is a technique for caching the results of a function based on its arguments. This can be useful when you want to avoid doing expensive calculations multiple times. Here is an example of a memoized function: 86 | 87 | ```js 88 | // Memoized function 89 | 90 | function memoizedAddTo25() { 91 | let cache = {}; 92 | return function (n) { 93 | if (n in cache) { 94 | console.log("Fetching from cache"); 95 | return cache[n]; 96 | } else { 97 | console.log("Calculating result"); 98 | let result = n + 25; 99 | cache[n] = result; 100 | return result; 101 | } 102 | }; 103 | } 104 | const memoized = memoizedAddTo25(); 105 | memoized(10); // Output: Calculating result // Output: 35 memoized(10); // Output: Fetching from cache // Output: 35 106 | ``` 107 | 108 | - Composing functions : Composing functions is a technique for combining two or more functions to produce a new function. This can be useful when you want to abstract a complex operation into a series of simpler steps. Here is an example of a composed function: 109 | 110 | ```js 111 | // Composed function 112 | 113 | function compose(f, g) { 114 | return function (x) { 115 | return f(g(x)); 116 | }; 117 | } 118 | function addOne(x) { 119 | return x + 1; 120 | } 121 | function addFive(x) { 122 | return x + 5; 123 | } 124 | const addSix = compose(addOne, addFive); 125 | addSix(0); // Output: 6 126 | ``` 127 | 128 | - Point-free style : Point-free style is a technique for writing functions without explicitly mentioning the arguments. This can be useful when you want to abstract a complex operation into a series of simpler steps. Here is an example of a point-free function: 129 | 130 | ```js 131 | // Point-free function 132 | 133 | function compose(f, g) { 134 | return function (x) { 135 | return f(g(x)); 136 | }; 137 | } 138 | function addOne(x) { 139 | return x + 1; 140 | } 141 | function addFive(x) { 142 | return x + 5; 143 | } 144 | const addSix = compose(addOne, addFive); 145 | addSix(0); // Output: 6 146 | ``` 147 | 148 | - Function composition : Function composition is a technique for combining two or more functions to produce a new function. This can be useful when you want to abstract a complex operation into a series of simpler steps. Here is an example of a composed function: 149 | 150 | ```js 151 | // Composed function 152 | 153 | function compose(f, g) { 154 | return function (x) { 155 | return f(g(x)); 156 | }; 157 | } 158 | function addOne(x) { 159 | return x + 1; 160 | } 161 | function addFive(x) { 162 | return x + 5; 163 | } 164 | const addSix = compose(addOne, addFive); 165 | addSix(0); // Output: 6 166 | ``` 167 | -------------------------------------------------------------------------------- /21.Module-pattern-and-module-loaders/README.md: -------------------------------------------------------------------------------- 1 | ### Module pattern and module loaders in JavaScript 2 | 3 | The module pattern and module loaders are important concepts in JavaScript that help to organize and structure code, improve maintainability, and prevent naming collisions. 4 | 5 | The module pattern refers to a design pattern that encapsulates code within a single, self-contained unit or module. This helps to prevent global namespace pollution and allows developers to break down a large application into smaller, more manageable parts. The module pattern can be implemented in several ways, including using Immediately Invoked Function Expressions (IIFE) and closures. 6 | 7 | Module loaders are tools that allow developers to load modules into their applications. JavaScript has several built-in module loaders, including CommonJS, AMD, and ES6 modules. CommonJS is commonly used in server-side JavaScript environments like Node.js, while AMD and ES6 modules are more commonly used in browser-based applications. 8 | 9 | Module loaders provide features like lazy loading, dependency management, and code optimization. They allow developers to write modular code that can be loaded on demand, reducing the amount of code that needs to be loaded upfront and improving performance. 10 | 11 | Overall, the module pattern and module loaders are important concepts in modern JavaScript development and are essential for building scalable, maintainable applications. 12 | 13 | Here is an example of a curried function: 14 | 15 | ```js 16 | // Module Pattern Example 17 | var myModule = (function () { 18 | // Private variables and functions 19 | var privateVar = "I am a private variable"; 20 | 21 | function privateFunction() { 22 | console.log("I am a private function"); 23 | } 24 | 25 | // Public variables and functions 26 | return { 27 | publicVar: "I am a public variable", 28 | publicFunction: function () { 29 | console.log("I am a public function"); 30 | }, 31 | getPrivateVar: function () { 32 | return privateVar; 33 | }, 34 | setPrivateVar: function (value) { 35 | privateVar = value; 36 | }, 37 | }; 38 | })(); 39 | 40 | myModule.publicFunction(); // Output: "I am a public function" 41 | console.log(myModule.publicVar); // Output: "I am a public variable" 42 | console.log(myModule.getPrivateVar()); // Output: "I am a private variable" 43 | myModule.setPrivateVar("New private variable value"); 44 | console.log(myModule.getPrivateVar()); // Output: "New private variable value" 45 | ``` 46 | 47 | n this example, we create a module using an immediately invoked function expression (IIFE) that returns an object with public properties and methods. The private properties and methods are enclosed within the function's scope and can only be accessed by the public methods. 48 | 49 | ## CommonJS Module 50 | 51 | CommonJS is a module specification that is commonly used in server-side JavaScript environments like Node.js. It is based on the module pattern and uses the require() function to load modules. The require() function takes a module name as an argument and returns an object that contains the module's public properties and methods. 52 | 53 | Here is an example of a CommonJS module: 54 | 55 | ```js 56 | // CommonJS Module Example 57 | // math.js module 58 | function sum(a, b) { 59 | return a + b; 60 | } 61 | 62 | function subtract(a, b) { 63 | return a - b; 64 | } 65 | 66 | module.exports = { 67 | sum: sum, 68 | subtract: subtract, 69 | }; 70 | 71 | // app.js module 72 | 73 | // app.js module 74 | var math = require("./math"); 75 | 76 | console.log(math.sum(1, 2)); // Output: 3 77 | console.log(math.subtract(4, 2)); // Output: 2 78 | ``` 79 | 80 | In this example, we define a math module that exports two functions using the module.exports object. We then use the require function to import the math module in the app module and use its functions. 81 | 82 | This example uses the CommonJS module loader, which is used in server-side JavaScript environments like Node.js. 83 | 84 | ## ES6 Module 85 | 86 | ES6 modules are a new module specification that is part of the ECMAScript 2015 (ES6) standard. They are based on the module pattern and use the import and export keywords to load modules. The import keyword is used to import a module, and the export keyword is used to export a module's public properties and methods. 87 | 88 | Here is an example of an ES6 module: 89 | 90 | ```js 91 | // ES6 Module Example 92 | 93 | // math.js module 94 | export function sum(a, b) { 95 | return a + b; 96 | } 97 | 98 | export function subtract(a, b) { 99 | return a - b; 100 | } 101 | 102 | // app.js module 103 | 104 | // app.js module 105 | import { sum, subtract } from "./math"; 106 | 107 | console.log(sum(1, 2)); // Output: 3 108 | console.log(subtract(4, 2)); // Output: 2 109 | ``` 110 | 111 | In this example, we define a math module that exports two functions using the export keyword. We then use the import keyword to import the math module in the app module and use its functions. 112 | 113 | ## AMD Module 114 | 115 | AMD is a module specification that is commonly used in browser-based JavaScript applications. It is based on the module pattern and uses the require() function to load modules. The require() function takes an array of module names as an argument and returns an array of objects that contain the modules' public properties and methods. 116 | 117 | Here is an example of an AMD module: 118 | 119 | ```js 120 | // AMD Module Example 121 | 122 | // math.js module 123 | define(function () { 124 | function sum(a, b) { 125 | return a + b; 126 | } 127 | 128 | function subtract(a, b) { 129 | return a - b; 130 | } 131 | 132 | return { 133 | sum: sum, 134 | subtract: subtract, 135 | }; 136 | }); 137 | 138 | // app.js module 139 | 140 | // app.js module 141 | require(["./math"], function (math) { 142 | console.log(math.sum(1, 2)); // Output: 3 143 | console.log(math.subtract(4, 2)); // Output: 2 144 | }); 145 | ``` 146 | 147 | In this example, we define a math module that exports two functions using the return statement. We then use the require function to import the math module in the app module and use its functions. 148 | 149 | ## SystemJS Module 150 | 151 | SystemJS is a module loader that is commonly used in browser-based JavaScript applications. It is based on the module pattern and uses the System.import() function to load modules. The System.import() function takes a module name as an argument and returns a promise that resolves to an object that contains the module's public properties and methods. 152 | 153 | Here is an example of a SystemJS module: 154 | 155 | ```js 156 | // SystemJS Module Example 157 | // math.js module 158 | export function sum(a, b) { 159 | return a + b; 160 | } 161 | 162 | export function subtract(a, b) { 163 | return a - b; 164 | } 165 | 166 | // app.js module 167 | // app.js module 168 | System.import("./math.js").then((math) => { 169 | console.log(math.sum(1, 2)); // Output: 3 170 | console.log(math.subtract(4, 2)); // Output: 2 171 | }); 172 | ``` 173 | 174 | In this example, we use the SystemJS module loader to load the math module and use its functions. SystemJS is a universal module loader that supports multiple module formats, including CommonJS, AMD, and ES6 modules. 175 | 176 | ## UMD Module 177 | 178 | UMD is a module specification that is commonly used in browser-based JavaScript applications. It is based on the module pattern and uses the define() function to load modules. The define() function takes a module name as an argument and returns an object that contains the module's public properties and methods. 179 | 180 | Here is an example of a UMD module: 181 | 182 | ```js 183 | // UMD Module Example 184 | (function (root, factory) { 185 | if (typeof define === "function" && define.amd) { 186 | // AMD 187 | define(["jquery"], factory); 188 | } else if (typeof module === "object" && module.exports) { 189 | // CommonJS 190 | module.exports = factory(require("jquery")); 191 | } else { 192 | // Global 193 | root.myModule = factory(root.jQuery); 194 | } 195 | })(this, function ($) { 196 | // Module code here 197 | }); 198 | ``` 199 | 200 | In this example, we define a module using the Universal Module Definition (UMD) format, which can be used to create modules that work with multiple module loaders and environments. The UMD format checks for the presence of CommonJS, AMD, and global environment variables to determine the appropriate loading mechanism for the module. 201 | 202 | ## TypeScript Module 203 | 204 | TypeScript is a superset of JavaScript that adds static typing and object-oriented programming features to JavaScript. TypeScript modules are based on the module pattern and use the import and export keywords to load modules. The import keyword is used to import a module, and the export keyword is used to export a module's public properties and methods. 205 | 206 | Here is an example of a TypeScript module: 207 | 208 | ```js 209 | // TypeScript Module Example 210 | // math.ts module 211 | export function sum(a: number, b: number): number { 212 | return a + b; 213 | } 214 | 215 | export function subtract(a: number, b: number): number { 216 | return a - b; 217 | } 218 | 219 | // app.ts module 220 | // app.ts module 221 | // app.ts module 222 | import { sum, subtract } from "./math"; 223 | 224 | console.log(sum(1, 2)); // Output: 3 225 | console.log(subtract(4, 2)); // Output: 2 226 | ``` 227 | 228 | In this example, we define a math module using TypeScript syntax and export two functions using the export keyword. We then use the import keyword to import the math module in the app module and use its functions. TypeScript is a superset of JavaScript that adds optional static typing and other features to the language. 229 | 230 | ## Conclusion 231 | 232 | JavaScript modules are a great way to organize your code and make it easier to maintain. In this article, we looked at the different types of JavaScript modules and how to use them in your applications. We also looked at the different module loaders that are commonly used in JavaScript applications. 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | -------------------------------------------------------------------------------- /22.Web-Workers/README.md: -------------------------------------------------------------------------------- 1 | ## Web Workers in Javascript 2 | 3 | Web Workers are a feature in JavaScript that allows developers to execute scripts in the background, freeing up the main thread of execution and preventing it from becoming unresponsive. 4 | 5 | Web Workers allow for multi-threading in web applications, which is especially useful for CPU-intensive tasks such as image manipulation or data processing. They work by creating a separate thread of execution, which runs in parallel to the main thread. This allows the application to continue to respond to user input while the Web Worker performs its tasks. 6 | 7 | Web Workers communicate with the main thread through a messaging system. They can send messages to and receive messages from the main thread, but they cannot directly access the DOM or other resources that are managed by the main thread. 8 | 9 | Overall, Web Workers are a powerful tool for improving the performance and responsiveness of web applications. 10 | 11 | 12 | 13 | 14 | ## How to use Web Workers 15 | 16 | Web Workers are created using the `Worker()` constructor. This constructor takes a single argument, which is the path to the script that will be executed in the worker thread. The script is loaded and executed in the background, and the worker thread is created. 17 | 18 | ```js 19 | const worker = new Worker('worker.js'); 20 | ``` 21 | 22 | The `Worker()` constructor returns a reference to the worker thread, which can be used to send messages to the worker thread and receive messages from it. 23 | 24 | ```js 25 | 26 | const worker = new Worker('worker.js'); 27 | 28 | worker.onmessage = function(event) { 29 | console.log('Message received from worker'); 30 | }; 31 | 32 | worker.postMessage('Hello World'); 33 | ``` 34 | 35 | 36 | ## Sending and receiving messages 37 | 38 | Web Workers communicate with the main thread through a messaging system. Messages are sent using the `postMessage()` method, and received using the `onmessage` event handler. 39 | 40 | ```js 41 | 42 | 43 | const worker = new Worker('worker.js'); 44 | 45 | worker.onmessage = function(event) { 46 | console.log('Message received from worker'); 47 | }; 48 | 49 | 50 | worker.postMessage('Hello World'); 51 | ``` 52 | 53 | The `postMessage()` method takes a single argument, which is the message to be sent to the worker thread. The message can be any JavaScript object, including strings, numbers, arrays, and objects. 54 | 55 | 56 | ## Terminating a worker 57 | 58 | Web Workers can be terminated using the `terminate()` method. This method terminates the worker thread and frees up the resources it was using. 59 | 60 | ```js 61 | 62 | const worker = new Worker('worker.js'); 63 | 64 | worker.terminate(); 65 | ``` 66 | 67 | -------------------------------------------------------------------------------- /23.Service-Workers/README.md: -------------------------------------------------------------------------------- 1 | ## Service Workers in JavaScript 2 | 3 | Service workers are a type of web worker that are designed to run in the background and intercept network requests. They are intended to be used as a network proxy, allowing developers to intercept network requests and take control of the response. This allows developers to create applications that work offline and load faster. 4 | 5 | 6 | ## How to use Service Workers 7 | 8 | Service workers are created using the `ServiceWorkerContainer.register()` method. This method takes two arguments: the path to the service worker script, and an options object. The options object can be used to specify the scope of the service worker, which is the path that the service worker will control. 9 | 10 | ```js 11 | 12 | navigator.serviceWorker.register('service-worker.js', { scope: '/app/' }); 13 | ``` 14 | 15 | 16 | ## Sending and receiving messages 17 | 18 | Service workers communicate with the main thread through a messaging system. Messages are sent using the `postMessage()` method, and received using the `onmessage` event handler. 19 | 20 | ```js 21 | 22 | 23 | const worker = new Worker('worker.js'); 24 | 25 | worker.onmessage = function(event) { 26 | console.log('Message received from worker'); 27 | }; 28 | 29 | 30 | worker.postMessage('Hello World'); 31 | ``` 32 | 33 | The `postMessage()` method takes a single argument, which is the message to be sent to the service worker. The message can be any JavaScript object, including strings, numbers, arrays, and objects. 34 | 35 | 36 | ## Terminating a worker 37 | 38 | Service workers can be terminated using the `ServiceWorkerContainer.unregister()` method. This method terminates the service worker and frees up the resources it was using. 39 | 40 | ```js 41 | 42 | 43 | navigator.serviceWorker.unregister(); 44 | ``` 45 | 46 | ## Resources 47 | 48 | - [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/) 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /24.Data structures-and-algorithms/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Clifftech123/JavaScript-for-beginners/128c6c5a16ed1fac9bfbc4a363d62b8a06f66df6/24.Data structures-and-algorithms/README.md -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [Javascript for Beginners] 2 | 3 | Thank you for your interest in contributing to this project! We welcome contributions of all kinds, including bug reports, feature requests, documentation improvements, and code contributions. 4 | 5 | ## How to Contribute 6 | 7 | To contribute to this project, please follow these steps: 8 | 9 | 1. Fork this repository to your own GitHub account. 10 | 2. Clone the forked repository to your local machine. 11 | 3. Create a new branch for your changes. 12 | 4. Make your changes and commit them with descriptive commit messages. 13 | 5. Push your changes to your forked repository. 14 | 6. Submit a pull request to the original repository. 15 | 16 | ## Corrections Guidelines 17 | Please follow these guidelines when contributing to make corrections to this project: 18 | 19 | - Use javascript for all new code. 20 | - Write clear and concise code with appropriate comments and documentation. 21 | - Follow the existing code style and formatting. 22 | 23 | 24 | 25 | ## Contact 26 | If you have any questions or concerns about contributing to this project, please contact [Isaiah Clifford Opoku](https://twitter.com/Clifftech_Dev). 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2023] [Isaiah Clifford Opoku] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## JavaScript for Beginners [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/docdis/javascript-best-practice/issues) 3 | 4 | 5 | ## Contributions 6 | *Contributions are welcome! Feel free to contribute to this repository to make it easier for others to master JavaScript. Please follow the [contribution](https://github.com/Clifftech123/JavaScript-for-beginners/blob/main/CONTRIBUTING.md) instructions provided to ensure a smooth and efficient contribution process.* 7 | 8 | 9 | This repository contains a collection of JavaScript resources specifically designed for beginners. Whether you're new to programming or just getting started with JavaScript, these resources can provide a solid foundation for your learning. 10 | 11 | However, even if you're an experienced developer, you can still benefit from reviewing these resources to refresh your knowledge of JavaScript basics and ensure that you're following best practices. These resources cover a range of topics, from syntax and data types to object-oriented programming and advanced concepts like closures and asynchronous programming. 12 | 13 | Regardless of your level of experience, starting with these JavaScript resources can help you build a strong foundation in the language and make it easier to progress to more complex concepts. 14 | 15 | 16 | 17 | ![javascript](images/javascript.png) 18 | ## Introduction to JavaScript 19 | JavaScript is a programming language that is primarily used to add interactive and dynamic elements to web pages. It is a high-level, interpreted language that is integrated with HTML and CSS. JavaScript can be used for a wide range of applications, including building web and mobile applications, game development, and creating browser extensions. 20 | 21 | JavaScript was first developed by Brendan Eich at Netscape in 1995, and has since become one of the most widely used programming languages in the world. It is supported by all major web browsers, including Chrome, Firefox, Safari, and Internet Explorer/Edge, and has a large community of developers who create and maintain libraries and frameworks for the language. 22 | 23 | Some common features of JavaScript include: 24 | 25 | 1.Dynamic HTML manipulation: JavaScript can be used to manipulate the HTML and CSS of a web page, allowing developers to create dynamic and interactive content. 26 | 27 | 2.Event handling: JavaScript can respond to user actions such as mouse clicks, keystrokes, and form submissions, allowing for interactive user interfaces. 28 | 29 | 3.Asynchronous programming: JavaScript allows for non-blocking code execution, which can improve performance by allowing multiple tasks to run concurrently. 30 | 31 | 4.Client-side scripting: JavaScript can be executed on the client-side, which means that it runs in the user's web browser rather than on a server. 32 | 33 | 34 | JavaScript can also be used in the backend of web applications through the use of server-side JavaScript frameworks, such as Node.js. With Node.js, developers can use JavaScript to build server-side applications that can handle tasks such as handling HTTP requests, interacting with databases, and performing other backend functions. This is made possible through the use of the V8 JavaScript engine, which is the same engine used by the Google Chrome web browser. 35 | 36 | Using JavaScript in the backend provides a number of benefits for web developers, including the ability to use a single language (JavaScript) for both the frontend and backend of their application, which can help streamline development and improve code consistency. Additionally, JavaScript has a large and active community of developers, which has resulted in the development of a number of useful libraries and frameworks for building server-side applications. 37 | 38 | Overall, using JavaScript in the backend allows developers to build scalable and efficient web applications using a language that is already familiar to many frontend developers. This can help reduce the learning curve and make it easier to build high-quality web applications. 39 | 40 | Overall, JavaScript is a powerful and versatile language that is essential for modern web development. It is constantly evolving and improving, with new features and capabilities being added with each new version. 41 | ## Table of Contents 42 | 1. [Variables and data types](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/01.Variables-and-data-types) 43 | 2. [Operators and expressions](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/02.Operators-and-expressions) 44 | 3. [Conditionals and loops](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/03.Conditionals-and-loops) 45 | 4. [Functions](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/04.Functions) 46 | 5. [Arrays](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/05.Arrays) 47 | 6. [Objects](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/06.Objects) 48 | 7. [ Event ](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/07.Events) 49 | 8. [DOM-manipulation](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/08.DOM-manipulation) 50 | 9. [Callbacks](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/09.Callbacks) 51 | 10. [Asynchronous programming](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/10.Asynchronous-programming) 52 | 11. [Closure](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/11.Closures) 53 | 12. [Prototype Inheritance](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/12.Prototypal-inheritance) 54 | 13. [Scoping and hosting](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/13.Scoping-and-hoisting) 55 | 14. [Regular expressions](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/14.Regular-expressions) 56 | 15. [Error handling](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/15.Error-handling) 57 | 16. [Promises](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/16.Promises) 58 | 17. [ES6 features ](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/17.ES6%2B-features) 59 | 18. [Generators and async await](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/18.Generators-and-async-await) 60 | 19. [High order functions](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/19.Higher-order-functions) 61 | 20. [Modules Pattern and module loaders](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/21.Module-pattern-and-module-loaders) 62 | 21. [Web Workers](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/22.Web-Workers) 63 | 22. [service workers](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/23.Service-Workers) 64 | 23. [Data Structures and Algorithms](https://github.com/Clifftech123/JavaScript-for-beginners/tree/main/24.Data%20structures-and-algorithms) 65 | -------------------------------------------------------------------------------- /images/1-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Clifftech123/JavaScript-for-beginners/128c6c5a16ed1fac9bfbc4a363d62b8a06f66df6/images/1-1.jpg -------------------------------------------------------------------------------- /images/hositing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Clifftech123/JavaScript-for-beginners/128c6c5a16ed1fac9bfbc4a363d62b8a06f66df6/images/hositing.png -------------------------------------------------------------------------------- /images/javascript.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Clifftech123/JavaScript-for-beginners/128c6c5a16ed1fac9bfbc4a363d62b8a06f66df6/images/javascript.png --------------------------------------------------------------------------------