├── JavaScript-Quick-Reference.md ├── LICENSE ├── README.md └── images ├── JS-cover-photo.png ├── JS-icon.png ├── cog.png ├── js.png ├── list.png ├── list2.png ├── question.png ├── react.png ├── stack.png ├── tech.png └── webdev.png /JavaScript-Quick-Reference.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # ![JavaScript Icon](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/JS-icon.png) JavaScript Simplified: An Efficient Learning Guide 4 | 5 | ![JavaScript Version](https://img.shields.io/badge/JavaScript-ES6-yellow) 6 | ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg) 7 | ![Contributions Welcome](https://img.shields.io/badge/Contributions-Welcome-brightgreen.svg) 8 | 9 | A comprehensive yet concise quick-reference and overview of JavaScript fundamentals. Designed as both an efficient learning tool and a rapid reference. This guide bridges the gap between learning and practical application, making JavaScript more accessible. 10 | 11 | [Back to README](https://github.com/george-GPT/JavaScript-Quick-Reference/blob/main/README.md) 12 | 13 | ## Introduction to JavaScript 14 | 15 | - [1.1 Overview of JavaScript](#11-overview-of-javascript) 16 | - [1.2 JavaScript Code Order](#12-javascript-code-order) 17 | 18 | ## Variables and Declarations 19 | 20 | - [2.1 Understanding var, let, and const](#21-understanding-var-let-and-const) 21 | - [2.2 Basic Data Types](#22-basic-data-types) 22 | - [2.3 Syntax and Examples](#23-syntax-and-examples) 23 | - [2.4 Operators](#24-operators) 24 | - [2.5 Type Conversion and Coercion](#25-type-conversion-and-coercion) 25 | 26 | ## Fundamental Programming Concepts 27 | 28 | - [3.1 Functions](#31-functions) 29 | - [3.2 Loops](#32-loops) 30 | - [3.3 Conditional Statements](#33-conditional-statements) 31 | - [3.4 Arrays](#34-arrays) 32 | - [3.5 Objects](#35-objects) 33 | - [3.6 Error Handling](#36-error-handling) 34 | 35 | ## Global JavaScript Objects 36 | 37 | - [4.1 String](#41-string) 38 | - [4.2 Numbers](#42-numbers) 39 | - [4.3 Math](#43-math) 40 | - [4.4 Date](#44-date) 41 | - [4.5 Randomness with Math.random()](#45-randomness-with-mathrandom) 42 | 43 | ## DOM & DOM Manipulation 44 | 45 | - [5.1 Understanding DOM & DOM Manipulation](#51-understanding-dom--dom-manipulation) 46 | - [5.2 Accessing and Modifying DOM Elements](#52-accessing-and-modifying-dom-elements) 47 | - [5.3 DOM Node Properties and Methods](#53-dom-node-properties-and-methods) 48 | - [5.4 DOM Event Handling](#54-dom-event-handling) 49 | 50 | ## Asynchronous JavaScript 51 | 52 | - [6.1 Asynchronous Operations in Javascript](#61-asynchronous-operations-in-javascript) 53 | - [6.2 Callbacks](#62-callbacks) 54 | - [6.3 Promises](#63-promises) 55 | - [6.4 Asnyc/Await](#64-asyncawait) 56 | - [6.5 AJAX](#65-ajax) 57 | - [6.6 WebSockets](#66-websockets) 58 | 59 | ## Working with APIs 60 | 61 | - [7.1 Understanding APIs & JSON](#71-understanding-apis--json) 62 | - [7.2 API Key Management](#72-api-key-management) 63 | - [7.3 Making API Requests](#73-making-api-requests) 64 | - [7.4 Handling JSON Data](#74-handling-json-data) 65 | 66 | ## Object-Oriented Programming (OOP) 67 | 68 | - [8.1 Object-Oriented Programming (OOP)](#81-object-oriented-programming-oop) 69 | 70 | ## Building Projects with JavaScript 71 | 72 | - [9.1 Using HTML Elements in JavaScript](#91-using-html-elements-in-javascript) 73 | - [9.2 Choosing Between Objects and Arrays](#92-choosing-between-objects-and-arrays) 74 | - [9.3 Managing User Input](#93-managing-user-input) 75 | - [9.4 Form Validation](#94-form-validation) 76 | - [9.5 Persisting Data with Web Storage](#95-persisting-data-with-web-storage) 77 | - [9.6 Coding Logic vs Data Retrieval & Execution](#96-coding-logic-vs-data-retrieval--execution) 78 | 79 | ## Tips and Best Practices 80 | 81 | - [10.1 Tips and Best Practices](#101-tips-and-best-practices) 82 | 83 | --- 84 | 85 | ## 1.1 Overview of JavaScript 86 | 87 | Explore the JavaScript language and its versatile capabilities, including: 88 | 89 | - Being a high-level, interpreted programming language. 90 | - Supporting dynamic typing for variables with varying data types. 91 | - Embracing multiple programming paradigms: event-driven, functional, and imperative. 92 | 93 | ### ![JavaScript Core Features](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/cog.png) Core Features 94 | 95 | Discover how JavaScript enhances user interaction on web pages by manipulating HTML and CSS. Learn how it handles asynchronous operations to make web applications more responsive. 96 | 97 | ### ![JavaScript and ECMAScript](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/js.png) JavaScript and ECMAScript 98 | 99 | Understand JavaScript's adherence to ECMAScript (ES) standards, including significant updates introduced in ES6/ES2015, such as let/const, arrow functions, and classes. 100 | 101 | ### ![JavaScript Environments](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/stack.png) Environments 102 | 103 | Explore JavaScript's versatility in both client-side (browser) and server-side (Node.js) development. See how it empowers the creation of dynamic web page content and back-end applications. 104 | 105 | ### ![JavaScript Role in Web Development](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/webdev.png) Role in Web Development 106 | 107 | Understand JavaScript's integral role in web development, including its interactivity, DOM manipulation, and server-side capabilities. 108 | 109 | ### ![Integration with Web Technologies](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/tech.png) Integration with Web Technologies 110 | 111 | Learn how JavaScript collaborates with HTML and CSS to deliver complete web page functionality. It utilizes AJAX alongside other modern methods for asynchronous tasks, such as Promises and Async/Await, to enhance interactivity and efficiency. 112 | 113 | ### ![JavaScript Libraries and Frameworks](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/react.png) Libraries and Frameworks 114 | 115 | Explore libraries like React and frameworks like Angular, Vue.js, and Ember.js that simplify common tasks and provide robust tools for building complex applications. 116 | 117 | ## [🔝 Back to Top](#top) 118 | 119 | ## 1.2 JavaScript Code Order 120 | 121 | The order of your code is vital for logical flow, efficient loading, and readability. 122 | 123 | ### ![JavaScript Libraries and Frameworks](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/question.png) Why It Matters 124 | 125 | - **Logical Flow:** Ensures proper function sequencing. 126 | - **Loading Efficiency:** Affects resource loading and page speed. 127 | - **Readability:** Enhances code comprehension. 128 | - **Maintainability:** Facilitates updates and bug fixes. 129 | - **Collaboration:** Simplifies teamwork and code sharing. 130 | 131 | ### ![JavaScript Libraries and Frameworks](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/list.png) Code Order Variability 132 | 133 | Optimal code order varies based on project needs and best practices: 134 | 135 | - **Library/Framework Integration:** Follow library/framework guidelines (e.g., React prioritizes state and rendering). 136 | - **Event-Driven Applications:** In event-driven apps (e.g., games or chat), focus on event handling and async tasks. 137 | - **Complex Form Validation:** For intricate form validation, focus on form handling and validation early. 138 | - **Performance Optimization:** Adjust the order for performance optimization as per your app's requirements. 139 | - **Team Workflow:** Adapt to your team's workflow and code organization preferences when collaborating. 140 | 141 | ### ![JavaScript Libraries and Frameworks](https://github.com/george-GPT/JavaScript-Quick-Reference/raw/main/images/list2.png) General JavaScript Order 142 | 143 | General structure to use as a baseline: 144 | 145 | 1. **DOM References and Global Variables:** Declare and manage references to HTML elements and global variables. 146 | 2. **Modularization and Code Organization:** Organize code into modules and understand import/export for better maintainability. 147 | 3. **Function Definitions and Local Variables:** Define reusable functions and declare local variables within functions. 148 | 4. **Form Handling, Validation, and State Management:** Efficiently handle forms, validate user input, and manage application state. 149 | 5. **Responsive Design and DOM Manipulations:** Create responsive designs and interact with DOM elements. 150 | 6. **Event Listeners and Additional Initializations:** Attach event listeners and perform setup tasks. 151 | 7. **Asynchronous Operations and API Calls:** Handle asynchronous tasks and make API requests. 152 | 8. **Error Handling and Debugging:** Implement error handling and debugging techniques. 153 | 9. **Performance Optimization and Testing:** Optimize code for performance and introduce testing practices. 154 | 155 | ## [🔝 Back to Top](#top) 156 | 157 | ## 2.1 VARIABLES AND DECLARATIONS 158 | 159 | Understanding variable declaration and scope in JavaScript. 160 | 161 | - **'var':** Function-scoped variable declaration (uncommon in modern JS) 162 | 163 | - `var oldVar = "I am old";` Avoid using 'var' when possible 164 | 165 | - **'let':** Block-scoped variable declaration (can be reassigned) 166 | 167 | - `let newLet = "I am new";` Preferred for variables that can change 168 | 169 | - **'const':** Block-scoped and constant variable declaration (cannot be reassigned) 170 | - `const constantVar = "I am constant";` Use for variables that should not change 171 | 172 | ## [🔝 Back to Top](#top) 173 | 174 | ## 2.2 BASIC DATA TYPES 175 | 176 | Overview of primitive data types in JavaScript. 177 | 178 | - **Number:** Represents both integers and floats 179 | 180 | - `let score = 75;` Integer 181 | - `let price = 9.99;` Float 182 | 183 | - **String:** Represents textual data 184 | 185 | - `let name = "Alice";` 186 | 187 | - **Boolean:** Represents true or false values 188 | 189 | - `let isPassed = score > 50; ` 190 | 191 | - **Undefined:** Variable declared but not assigned 192 | 193 | - `let result;` 194 | 195 | - **Null:** Explicitly signifies no value 196 | - `let data = null;` 197 | 198 | ## 2.3 SYNTAX AND EXAMPLES 199 | 200 | Examples illustrating syntax for variable declarations and data types. 201 | 202 | ### Declaring Multiple Variables 203 | 204 | `let x = 5, y = 10; // Multiple variables in one line` 205 | 206 | ### String Concatenation 207 | 208 | `let greeting = "Hello " + name; // "Hello Alice"` 209 | 210 | ### Template Literals (ES6) 211 | 212 | `` `let greetingTemplate = `Hello ${name}`; // "Hello Alice"` `` 213 | 214 | ### Arithmetic Operations 215 | 216 | - `let sum = x + y;` Addition (15) 217 | - `let diff = y - x;` Subtraction (5) 218 | 219 | ### Boolean Logic 220 | 221 | `let isGreater = x > y;` false 222 | 223 | ### Type Coercion 224 | 225 | `let total = "3" + 4;` "34", number 4 becomes a string 226 | 227 | ### The typeof Operator 228 | 229 | The `typeof` operator is used to determine the type of a variable or expression. It returns a string indicating the data type. 230 | 231 | ```javascript 232 | let num = 42 233 | console.log(typeof num) // Outputs: "number" 234 | 235 | let str = 'Hello, world!' 236 | console.log(typeof str) // Outputs: "string" 237 | 238 | let bool = true 239 | console.log(typeof bool) // Outputs: "boolean" 240 | ``` 241 | 242 | ## [🔝 Back to Top](#top) 243 | 244 | ## 2.4 Operators 245 | 246 | Operators allow you to perform various tasks, such as assigning values to variables, comparing values, performing arithmetic operations, and more. This section provides an overview of the different types of operators in JavaScript. 247 | 248 | ### Assignment Operators 249 | 250 | - `=` Assigns the value on the right to the variable on the left. 251 | - `+=` Adds the value on the right to the variable on the left. 252 | - `-=` Subtracts the value on the right from the variable on the left. 253 | - `*=` Multiplies the variable on the left by the value on the right. 254 | - `/=` Divides the variable on the left by the value on the right. 255 | 256 | ### Comparison Operators 257 | 258 | - `==` Checks if the values of two operands are equal. 259 | - `!=` Checks if the values of two operands are not equal. 260 | - `===` Checks if the values and types of two operands are equal. 261 | - `==` Checks if the values or types of two operands are not equal. 262 | - `>` Checks if the value of the left operand is greater than the value of the right operand. 263 | - `<` Checks if the value of the left operand is less than the value of the right operand. 264 | - `>=` Checks if the value of the left operand is greater than or equal to the value of the right operand. 265 | - `<=` Checks if the value of the left operand is less than or equal to the value of the right operand. 266 | 267 | ### Logical Operators 268 | 269 | - `&&` Returns true if both operands are true. 270 | - `||` Returns true if either of the operands is true. 271 | - `!` Returns true if the operand is false and false if the operand is true. 272 | 273 | ### Arithmetic Operators 274 | 275 | - `+` Adds two operands. 276 | - `-` Subtracts the second operand from the first operand. 277 | - `*` Multiplies two operands. 278 | - `/` Divides the first operand by the second operand. 279 | - `%` Returns the remainder when the first operand is divided by the second operand 280 | 281 | ## [🔝 Back to Top](#top) 282 | 283 | ## 2.5 TYPE CONVERSION AND COERCION 284 | 285 | In JavaScript, the conversion and interpretation of values between different types are critical concepts that enable the effective writing and understanding of code. This section focuses on explicit type conversion, also known as type casting, and implicit type coercion, providing insights into their mechanisms and use cases. 286 | 287 | ### Explicit Type Conversion 288 | 289 | Explicit type conversion, or type casting, involves converting values from one type to another using built-in functions, allowing for controlled and intentional data type changes. 290 | 291 | - **String Conversion**: To convert a value to a string, use the `String()` function. For example, `String(123)` converts the number `123` into the string `"123"`. 292 | 293 | - **Number Conversion**: The `Number()` function is used to convert strings and other types to numbers. For instance, `Number("123")` turns the string `"123"` into the number `123`. Inputs that cannot be converted to a number yield `NaN` (Not-a-Number). 294 | 295 | - **Boolean Conversion**: Using `Boolean()` converts values to booleans. Truthy values (values that are not `0`, `null`, `undefined`, `NaN`, `''`, or `false`) convert to `true`, while falsy values convert to `false`. 296 | 297 | ### Implicit Type Coercion 298 | 299 | Implicit type coercion happens when JavaScript automatically converts types behind the scenes in the context of an operation. 300 | 301 | - **Numeric String and Number**: When a numeric string and a number are used in an operation, the string is coerced into a number. For example, `"5" - 2` results in `3`. 302 | 303 | - **Boolean and Number**: In arithmetic operations, `true` is treated as `1` and `false` as `0`. Thus, `true + 2` equals `3`. 304 | 305 | - **String Concatenation**: When a number is added to a string, the number is converted into a string. For instance, `5 + "3"` yields `"53"`. 306 | 307 | Understanding these conversion and coercion rules is essential for debugging and for writing clear, predictable JavaScript code. 308 | 309 | ```javascript 310 | // Explicit Type Conversion 311 | console.log(String(123)); // "123" - Number to string 312 | console.log(Number("123")); // 123 - String to number 313 | console.log(Boolean(1)); // true - Number to boolean 314 | 315 | // Implicit Type Coercion 316 | console.log("6" - 2); // 4 - Numeric string and number in subtraction operation 317 | console.log("6" + 2); // "62" - Number is converted to string in concatenation 318 | console.log(true + false); // 1 - true is treated as 1, false as 0 in addition 319 | 320 | // More examples 321 | console.log("5" * "4"); // 20 - Strings coerced to numbers in multiplication 322 | console.log("5" * true); // 5 - true is treated as 1 in multiplication 323 | console.log(null + 1); // 1 - null is treated as 0 in addition 324 | console.log(undefined + 1); // NaN - undefined is not converted in numeric operations 325 | ``` 326 | 327 | ## [🔝 Back to Top](#top) 328 | 329 | ## 3.1 FUNCTIONS 330 | 331 | In JavaScript, functions are fundamental building blocks, acting as callable objects to perform tasks or return values. They enhance code organization, reusability, and testability. This section delves into functions, covering declarations, parameters, and advanced concepts. 332 | 333 | ### Function Declarations 334 | 335 | Define functions using the `function` keyword, specifying parameters within parentheses. 336 | 337 | ```javascript 338 | function greet(name) { 339 | return `Hello, ${name}!` 340 | } 341 | console.log(greet('Alice')) 342 | ``` 343 | 344 | Outputs "Hello, Alice!" 345 | 346 | ### Function Parameters and Arguments 347 | 348 | Functions accept inputs called parameters, defined at declaration, and are placeholders for data passed during invocation, called arguments. Parameters are locally scoped within the function, allowing you to reference them even if they haven't been assigned outside. Additionally, you can reference external or existing parameters within the function body. Arguments, on the other hand, are the actual values passed to the function when it's called, allowing for dynamic operation based on the values provided. 349 | 350 | ```javascript 351 | // Variable declared outside the function 352 | let globalVariable = 10 353 | 354 | // Function that takes a parameter which is a variable declared outside the function 355 | function multiplyByGlobal(globalVariable) { 356 | // Perform multiplication using the parameter and the global variable 357 | let result = userInput * globalVariable 358 | return result 359 | } 360 | 361 | // Example usage of the function 362 | let userInput = 5 363 | let multipliedValue = multiplyByGlobal(globalVariable) 364 | console.log(`Result: ${multipliedValue}`) // Output: Result: 50 365 | ``` 366 | 367 | ### When to Use Parameters 368 | 369 | - **Customization:** Parameters enable functions to handle different scenarios by accepting varied inputs, enhancing flexibility. For instance, a function computing rectangle area can take length and width parameters for any rectangle. 370 | 371 | - **Reusability:** Parameterized functions are reusable, executing the same logic with diverse input values, enhancing code efficiency. 372 | 373 | - **Abstraction:** Parameters shield callers from implementation details, necessitating only knowledge of required inputs and outputs, fostering clearer interfaces. 374 | 375 | - **Modularity:** Parameterized functions promote code modularity, encapsulating specific tasks and inputs, facilitating comprehension and maintenance. 376 | 377 | ### What can be used as Parameters 378 | 379 | - **Local Variables:** Scoped within the function, used for internal computations or temporary storage. 380 | 381 | - **Global Variables:** Can be used as parameters, but it's discouraged due to potential dependencies and decreased reusability. 382 | 383 | - **Primitive Data Types:** Accepted as parameters, they're copied when passed into the function (passed by value), ensuring the original value remains unchanged. 384 | 385 | - **Complex Data Types:** Objects and arrays can be passed as parameters, allowing modifications within the function to affect the original data (passed by reference). 386 | 387 | - **Functions:** Can be passed as parameters, enabling advanced programming techniques such as callbacks, higher-order functions, and functional programming paradigms. 388 | 389 | ### Default Parameters (ES6) 390 | 391 | Default parameters provide fallback values for function arguments if no value or undefined is passed when the function is called. 392 | They are specified in the function declaration and assigned using the syntax parameter = defaultValue. 393 | 394 | ```javascript 395 | function say(message = 'Hi') { 396 | console.log(message) 397 | } 398 | ;`say();` // Outputs "Hi" 399 | `say("Hello");` // Outputs "Hello" 400 | ``` 401 | 402 | ### Rest Parameters (ES6) 403 | 404 | Rest parameters allow functions to accept an indefinite number of arguments as an array, providing a more flexible way to handle function arguments. 405 | They are represented by three dots (...) followed by the parameter name and collect multiple arguments into a single array parameter. 406 | 407 | ```javascript 408 | function sumAll(...numbers) { 409 | return numbers.reduce((acc, num) => acc + num, 0) 410 | } 411 | console.log(sumAll(1, 2, 3)) 412 | ``` 413 | 414 | Outputs 6 415 | 416 | ### Arrow Functions (ES6) 417 | 418 | Arrow functions provide a concise syntax for writing function expressions in JavaScript, using the => syntax. 419 | They inherit the this value from the surrounding code context and are commonly used for short, one-liner functions or functions that don't require their own this context. 420 | 421 | ```javascript 422 | const arrowFunction = (parameters) => expression 423 | ``` 424 | 425 | ```javascript 426 | // Traditional function expression to greet a user 427 | function greetUser(userName) { 428 | return 'Hello, ' + userName + '!' 429 | } 430 | 431 | // Arrow function expression for greeting a user 432 | const greetUserArrow = (userName) => `Hello, ${userName}!` 433 | 434 | console.log(greetUser('John')) // Output: Hello, John! 435 | console.log(greetUserArrow('Jane')) // Output: Hello, Jane! 436 | ``` 437 | 438 | In this example, the arrow function addArrow accomplishes the same thing but with a more concise syntax. It omits the function keyword and uses the => arrow syntax to define the function. 439 | 440 | ### Function Expressions 441 | 442 | Function expressions assign an anonymous function to a variable. They offer flexibility, allowing functions to be defined and passed as data. Within these function expressions, parameters can refer to both existing variables and parameters that have not been previously declared or defined. This allows for dynamic behavior based on the values passed to the function when it's invoked. 443 | 444 | ```javascript 445 | const square = function (x) { 446 | return x * x 447 | } 448 | console.log(square(4)) // Outputs 16 449 | ``` 450 | 451 | ### Comparing Function Types 452 | 453 | ```javascript 454 | // Function Declaration 455 | function greetDeclaration(name) { 456 | return 'Hello, ' + name + '!' 457 | } 458 | 459 | // Function Expression 460 | const greetExpression = function (name) { 461 | return 'Hello, ' + name + '!' 462 | } 463 | 464 | // Arrow Function 465 | const greetArrow = (name) => { 466 | return 'Hello, ' + name + '!' 467 | } 468 | 469 | // Test the functions 470 | console.log(greetDeclaration('Alice')) // Output: Hello, Alice! 471 | console.log(greetExpression('Bob')) // Output: Hello, Bob! 472 | console.log(greetArrow('Charlie')) // Output: Hello, Charlie! 473 | ``` 474 | 475 | ### IIFE (Immediately Invoked Function Expression) 476 | 477 | IIFEs are functions that execute immediately upon definition, useful for initializing applications or namespaces. 478 | 479 | ```javascript 480 | ;(function () { 481 | console.log('This function runs right away!') 482 | })() 483 | ``` 484 | 485 | ### Higher-Order Functions 486 | 487 | These functions accept or return other functions, facilitating abstraction and composition in programming. 488 | 489 | ```javascript 490 | function applyOperation(a, b, operation) { 491 | return operation(a, b) 492 | } 493 | ;`const result = applyOperation(4, 2, multiply);` // Using the multiply arrow function 494 | `console.log(result);` // Outputs 8 495 | ``` 496 | 497 | ## [🔝 Back to Top](#top) 498 | 499 | ## 3.2 LOOPS 500 | 501 | Loops enable repetitive execution of code, streamlining tasks like array traversal and conditional iterations. 502 | 503 | ### Choosing the Right Loop Structure 504 | 505 | - **for loop** when you need to repeat a block of code for a known number of iterations, typically defined by a start condition, an end condition, and an increment. 506 | - **while loop** when the number of iterations is uncertain, and you need to continue iterating as long as a specific condition remains true. 507 | - **do...while loop** when you need to execute a block of code at least once before evaluating the loop condition for further iterations. 508 | - **for...in loop** to iterate over all enumerable properties of an object, often useful for iterating through object keys and values. 509 | - **for...of loop (ES6)** when iterating over iterable objects like arrays or strings, providing a simpler syntax without needing to deal with indexes or properties. 510 | 511 | ### for Loop 512 | 513 | Repeatedly runs a block of code a certain number of times. 514 | 515 | ```javascript 516 | for (let i = 0; i < 5; i++) { 517 | console.log(i) // Outputs: 0, 1, 2, 3, 4 518 | } 519 | ``` 520 | 521 | ### while Loop 522 | 523 | Executes code as long as a specified condition is true. 524 | 525 | ```javascript 526 | let j = 0 527 | while (j < 5) { 528 | console.log(j) // Outputs: 0, 1, 2, 3, 4 529 | j++ 530 | } 531 | ``` 532 | 533 | ### do...while Loop 534 | 535 | Executes code once, then repeats the loop as long as the condition is true. 536 | 537 | ```javascript 538 | let k = 0 539 | do { 540 | console.log(k) // Outputs: 0, 1, 2, 3, 4 541 | k++ 542 | } while (k < 5) 543 | ``` 544 | 545 | ### for...in Loop 546 | 547 | Iterates over all enumerable properties of an object. 548 | 549 | ```javascript 550 | const person = { name: 'Alice', age: 30 } 551 | for (const key in person) { 552 | console.log(`${key}: ${person[key]}`) // Outputs: "name: Alice", "age: 30" 553 | } 554 | ``` 555 | 556 | ### for...of Loop (ES6) 557 | 558 | Iterates over iterable objects like arrays, strings. 559 | 560 | ```javascript 561 | const numbers = [1, 2, 3, 4, 5] 562 | for (const number of numbers) { 563 | console.log(number) // Outputs: 1, 2, 3, 4, 5 564 | } 565 | ``` 566 | 567 | ### Array.forEach() 568 | 569 | Executes a specified function for each element within an array. While it's not a traditional loop, it's closely related to the topic of array iteration. 570 | 571 | ```javascript 572 | numbers.forEach((number) => { 573 | console.log(number) // Outputs: 1, 2, 3, 4, 5 574 | }) 575 | ``` 576 | 577 | ## [🔝 Back to Top](#top) 578 | 579 | ## 3.3 CONDITIONAL STATEMENTS 580 | 581 | Quick reference for using conditional logic in JavaScript. 582 | 583 | ### if Statement 584 | 585 | Executes code block if condition is true. 586 | 587 | ```javascript 588 | if (condition) { 589 | // Code to be executed if condition is true 590 | } 591 | ``` 592 | 593 | ### if...else Statement 594 | 595 | Executes one code block if condition is true, another if false. 596 | 597 | ```javascript 598 | if (condition) { 599 | // Code to be executed if condition is true 600 | } else { 601 | // Code to be executed if condition is false 602 | } 603 | ``` 604 | 605 | ### if...else if...else Statement 606 | 607 | Executes multiple conditions. 608 | 609 | ```javascript 610 | if (condition1) { 611 | // Code if condition1 is true 612 | } else if (condition2) { 613 | // Code if condition2 is true 614 | } else { 615 | // Code if neither condition1 nor condition2 is true 616 | } 617 | ``` 618 | 619 | ### switch Statement 620 | 621 | Switch statements provide a way to perform different actions based on different conditions. They allow you to evaluate an expression and execute code blocks based on the matching case. Switch statements offer a more concise alternative to multiple if...else statements when dealing with multiple conditions. 622 | 623 | ```javascript 624 | switch (expression) { 625 | case value1: 626 | // Code block to execute if expression equals value1 627 | break 628 | case value2: 629 | // Code block to execute if expression equals value2 630 | break 631 | // Additional cases as needed 632 | default: 633 | // Code block to execute if expression doesn't match any case 634 | } 635 | ``` 636 | 637 | ```javascript 638 | const day = 'Monday' 639 | 640 | switch (day) { 641 | case 'Monday': 642 | console.log('Today is Monday') 643 | break 644 | case 'Tuesday': 645 | console.log('Today is Tuesday') 646 | break 647 | default: 648 | console.log("It's neither Monday nor Tuesday") 649 | } 650 | ``` 651 | 652 | ### Ternary Operator 653 | 654 | The ternary operator is a concise way to write conditional statements in JavaScript. It takes three operands: a condition, an expression to execute if the condition is true, and an expression to execute if the condition is false. 655 | 656 | ```javascript 657 | condition ? expression1 : expression2 658 | ``` 659 | 660 | ```javascript 661 | const age = 20 662 | const status = age >= 18 ? 'adult' : 'minor' 663 | 664 | console.log(status) // Outputs: 'adult' since age is greater than or equal to 18 665 | ``` 666 | 667 | ## [🔝 Back to Top](#top) 668 | 669 | ## 3.4 ARRAYS 670 | 671 | Detailed guide on JavaScript Arrays, covering array manipulation methods, iteration, and array-specific operations. 672 | 673 | - Use arrays to store a list of items in an ordered manner, where each item can be accessed by its numerical index. 674 | - Arrays are ideal for scenarios where you need to perform operations like looping through elements, as they provide methods for iteration and manipulation. 675 | 676 | ### Properties 677 | 678 | - `array.length` Reflects the number of elements in an array. 679 | - `array.prototype` Represents the prototype for the Array constructor and allows to add new properties and methods to all Array objects. 680 | 681 | ### Methods 682 | 683 | - `array.from(arrayLike[, mapFn[, thisArg]])` Creates a new Array instance from an array-like or iterable object. 684 | - `array.isArray(object)` Returns true if a variable is an array, if not false. 685 | - `array.of("element1", "element2");` Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments. 686 | 687 | ### Mutator Methods 688 | 689 | - `arr.copyWithin(target, start, end)` Copies a sequence of array elements within the array. 690 | - `arr.fill(value, start, end)` Fills all the elements of an array from a start index to an end index with a static value. 691 | - `arr.pop()` Removes the last element from an array and returns that element. 692 | - `arr.flat()` Merges nested array into one single array. 693 | - `arr.push("element1", "element2");` Adds one or more elements to the end of an array and returns the new length of the array. 694 | - `arr.reverse()` Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first. 695 | - `arr.shift()` Removes the first element from an array and returns that element. 696 | - `arr.sort()` Sorts the elements of an array in place and returns the array. 697 | - `array.splice(start, deleteCount, element1, element2)` Adds and/or removes elements from an array. 698 | - `arr.unShift("element1", "element2");` Adds one or more elements to the front of an array and returns the new length of the array. 699 | 700 | ### Example of .sort() & .filter() 701 | 702 | ```javascript 703 | let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] 704 | 705 | let result = numbers 706 | .sort((a, b) => a - b) // Sort in ascending order 707 | .filter((number) => number > 3) // Filter numbers greater than 3 708 | 709 | console.log(result) // [4, 4, 5, 5, 5, 6, 9] 710 | ``` 711 | 712 | ### Accessor Methods 713 | 714 | - `array.filter(callback[, thisArg])` Creates a new array containing elements that meet a specified condition defined by the provided callback function. 715 | - `array.at(index)` Returns the element at the specified index in the array. 716 | - `array.concat(value1, value2, array2)` Returns a new array comprised of this array joined with other array(s) and/or value(s). 717 | - `array.includes(searchElement, fromIndex)` Determines whether an array contains a certain element, returning true or false as appropriate. 718 | - `array.indexOf(searchElement[, fromIndex])` Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. 719 | - `array.join(separator)` Joins all elements of an array into a string. 720 | - `array.lastIndexOf(searchElement, fromIndex)` Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. 721 | - `array.slice(begin, end)` Extracts a section of an array and returns a new array. 722 | - `array.toString()` Returns a string representing the array and its elements. 723 | - Overrides the Object.prototype.toString() method. 724 | - `array.toLocaleString(locales, options)` Returns a localized string representing the array and its elements. 725 | - Overrides the `Object.prototype.toLocaleString()` method. 726 | 727 | ### Example of array.slice(begin, end) 728 | 729 | ```javascript 730 | // Suppose we have an array of months 731 | const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July'] 732 | 733 | // We want to get only the spring months 734 | const springMonths = months.slice(2, 5) 735 | 736 | console.log(springMonths) // Output: ['March', 'April', 'May'] 737 | ``` 738 | 739 | ### Iterating Through Array Elements 740 | 741 | When iterating through array elements, you can use the index notation `[i]` to access a specific element at index `i`: 742 | 743 | ```javascript 744 | const array = [10, 20, 30, 40, 50] 745 | 746 | for (let i = 0; i < array.length; i++) { 747 | console.log(array[i]) // Accesses the element at index i 748 | } 749 | ``` 750 | 751 | ### Iteration Methods 752 | 753 | - `array.every(callback[, thisArg])` Returns true if every element in this array satisfies the provided testing function. 754 | - `array.filter(callback[, thisArg])` Creates a new array with all of the elements of this array for which the provided filtering function returns true. 755 | - `array.find(callback[, thisArg])` Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. 756 | - `array.findIndex(callback[, thisArg])` Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. 757 | - `array.forEach(callback[, thisArg])` Calls a function for each element in the array. 758 | - `array.keys()` Returns a new Array Iterator that contains the keys for each index in the array. 759 | - `array.map(callback[, initialValue])` Creates a new array with the results of calling a provided function on every element in this array. 760 | - `array.reduce(callback[, initialValue])` Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. 761 | - `array.reduceRight(callback[, initialValue])` Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. 762 | - `array.some(callback[, initialValue])` Returns true if at least one element in this array satisfies the provided testing function. 763 | - `array.values()` Returns a new Array Iterator object that contains the values for each index in the array. 764 | 765 | ### Array.forEach() 766 | 767 | Executes a specified function for each element within an array. While it's not a traditional loop, it's closely related to the topic of array iteration. 768 | 769 | ```javascript 770 | numbers.forEach((number) => { 771 | console.log(number) // Outputs: 1, 2, 3, 4, 5 772 | }) 773 | ``` 774 | 775 | ### array.reduce(callback[, initialValue]) 776 | 777 | ```javascript 778 | // Suppose we have an array of numbers 779 | const numbers = [1, 2, 3, 4, 5] 780 | 781 | // We want to find the sum of all numbers in the array 782 | const sum = numbers.reduce((accumulator, currentValue) => { 783 | return accumulator + currentValue 784 | }, 0) // 0 is the initial value 785 | 786 | console.log(sum) // Output: 15 787 | ``` 788 | 789 | ### Array.includes() method 790 | 791 | The includes() method in JavaScript is used to determine whether an array includes a certain value among its elements. It returns true if the array contains the specified element, and false otherwise. This method offers a simple way to check for the presence of a value within an array without needing to iterate through its elements manually. 792 | 793 | ```javascript 794 | array.includes(searchElement, fromIndex) 795 | ``` 796 | 797 | ```javascript 798 | const fruits = ['apple', 'banana', 'orange', 'grape'] 799 | console.log(fruits.includes('banana')) // Output: true 800 | console.log(fruits.includes('watermelon')) // Output: false 801 | ``` 802 | 803 | ### Array Destructuring 804 | 805 | Destructuring arrays provides a more concise and readable way to extract values from an array and assign them to variables. Leading to cleaner code and make it easier to work with arrays, especially when dealing with functions that return arrays or when handling array elements in different parts of your code. 806 | 807 | - **Clarity and readability:** Destructuring makes it clear which elements of the array you are interested in, improving code readability compared to accessing elements by index. 808 | - **Conciseness:** Destructuring allows you to extract multiple values from an array in a single statement, reducing the amount of code needed. 809 | - **Variable naming:** When destructuring, you can assign more meaningful variable names to the extracted values, making your code easier to understand. 810 | - **Avoiding temporary variables:** Destructuring can help you avoid the need for temporary variables when working with array elements, leading to cleaner code. 811 | - **Function return values:** Destructuring can be especially useful when dealing with functions that return arrays, allowing you to easily extract and work with the returned values. 812 | 813 | ```javascript 814 | // Define an array with numerical values 815 | const numbers = [1, 2, 3] 816 | 817 | // Destructure the array into individual variables 818 | const [firstNumber, secondNumber, thirdNumber] = numbers 819 | 820 | // Log the individual variables 821 | console.log(firstNumber) // Output: 1 822 | console.log(secondNumber) // Output: 2 823 | console.log(thirdNumber) // Output: 3 824 | ``` 825 | 826 | ## [🔝 Back to Top](#top) 827 | 828 | ## 3.5 OBJECTS 829 | 830 | Objects are a collection of properties, where a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. 831 | 832 | - Objects are used to store data as key-value pairs, allowing for the organization of data with named properties that can be accessed using keys. 833 | - They are suitable for representing more complex data structures where each item may contain a different set of properties. 834 | 835 | ### What is a Key? 836 | 837 | It is a unique identifier used to access the corresponding value in the object. Keys are often strings (but can be symbols in ES6 and beyond), representing property names. 838 | 839 | ### What is a Value? 840 | 841 | It is the data associated with a key within an object. Values can be of any data type, such as numbers, strings, arrays, functions, or even other objects. 842 | 843 | ### what is a Key Value Pair? 844 | 845 | Together, a key and its associated value form a key-value pair, allowing you to store and organize data in a structured way within an object. For example, in the following object,"name" and "age" are keys, while "John" and 30 are their corresponding values: 846 | 847 | ```javascript 848 | { name: "John", age: 30 }, 849 | ``` 850 | 851 | ### Creating an Object 852 | 853 | - `const myObject = { key1: 'value1', key2: 'value2' };` Object literal with two properties 854 | - `Object.create()` creates a new object with a specified prototype object and properties 855 | 856 | ### Accessing Properties 857 | 858 | In JavaScript, objects are collections of properties, and you can access these properties using either dot notation or bracket notation. 859 | 860 | - `console.log(myObject.key1);` 'value1' 861 | - `console.log(myObject['key2']);` 'value2' 862 | 863 | ### Dot Notation VS Bracket Notation 864 | 865 | Dot notation is preferred for direct and straightforward property access when the property name is known at development time and is a valid JavaScript identifier. On the other hand, bracket notation offers more flexibility and versatility, allowing for dynamic property access, handling special cases, and enabling programmatic property access. 866 | 867 | ### When to Use Dot Notation 868 | 869 | - **Known Property Names:** Use dot notation when you know the property name at development time and it is a valid JavaScript identifier. 870 | - **Clear and Direct Access:** Dot notation is ideal for accessing properties directly and offers a concise syntax for this purpose. 871 | - **Code Readability:** It enhances code readability, especially when accessing well-known properties of objects. 872 | 873 | ### When to Use Bracket Notation 874 | 875 | - **Dynamic Property Access:** Use bracket notation when the property name is determined dynamically at runtime, such as when it's stored in a variable or computed through an expression. 876 | - **Handling Special Cases:** Bracket notation is essential for accessing properties with special characters, spaces, or reserved words in JavaScript. 877 | - **Programmatic Property Access:** It enables programmatic approaches to property access, making it useful for working with data structures, APIs, or situations where property names may vary. 878 | 879 | ### Adding Properties 880 | 881 | - `myObject.key3 = 'value3';` Adding a new property 'key3' 882 | 883 | ### Deleting Properties 884 | 885 | - `delete myObject.key2;` Removing property 'key2' 886 | 887 | ### Methods 888 | 889 | A method in a JavaScript object is a property of the object that is a function. Methods are functions stored as object properties, and they are typically used to define actions or behavior for the object. 890 | 891 | ### Structure for Creating and Using Methods 892 | 893 | ```javascript 894 | const exampleObject = { 895 | property1: 'Value1', 896 | property2: 'Value2', 897 | method1: function () { 898 | return 'Method1 returns: ' + this.property1 899 | }, 900 | method2: function (parameter) { 901 | console.log( 902 | 'Method2 uses ' + parameter + ' and property2: ' + this.property2 903 | ) 904 | }, 905 | } 906 | 907 | console.log(exampleObject.method1()) // Calls method1, outputs: Method1 returns: Value1 908 | exampleObject.method2('Parameter1') // Calls method2 with "Parameter1" as an argument, outputs: Method2 uses Parameter1 and property2: Value2 909 | ``` 910 | 911 | ### Example of Creating and Using Methods 912 | 913 | ```javascript 914 | const person = { 915 | firstName: 'John', 916 | lastName: 'Doe', 917 | fullName: function () { 918 | return this.firstName + ' ' + this.lastName 919 | }, 920 | greet: function (greeting) { 921 | console.log(greeting + ', my name is ' + this.firstName) 922 | }, 923 | } 924 | 925 | console.log(person.fullName()) // Calls the fullName method, outputs: John Doe 926 | person.greet('Hello') // Calls the greet method with "Hello" as an argument, outputs: Hello, my name is John 927 | ``` 928 | 929 | ### Methods of the Object Constructor 930 | 931 | Methods of the Object constructor in JavaScript provide a set of utility functions for creating, manipulating, and working with objects, including methods for object creation, property manipulation, and property enumeration. 932 | 933 | - `Object.assign(target, ...sources)` Copies values from source to target objects. 934 | - `Object.create(proto, propertiesObject)` Creates a new object with the specified prototype and properties. 935 | - `Object.defineProperty(obj, prop, descriptor)` Defines a new property on an object. 936 | - `Object.defineProperties(obj, props)` Defines multiple properties on an object. 937 | - `Object.entries(obj)` Returns an array of a given object's own enumerable string [key, value] pairs. 938 | - `Object.freeze(obj)` Freezes an object, preventing new properties and changes to existing properties. 939 | - `Object.getOwnPropertyDescriptor(obj, prop)` Gets the descriptor for a property. 940 | - `Object.getOwnPropertyDescriptors(obj)` Gets all own property descriptors of an object. 941 | - `Object.getOwnPropertyNames(obj)` Returns an array of all properties (enumerable or not). 942 | - `Object.getOwnPropertySymbols(obj)` Returns an array of all symbol properties. 943 | - `Object.getPrototypeOf(obj)` Returns the prototype of the object. 944 | - `Object.is(value1, value2)` Compares if two values are the same. 945 | - `Object.isExtensible(obj)` Checks if an object can be extended with new properties. 946 | - `Object.isFrozen(obj)` Checks if an object is frozen. 947 | - `Object.isSealed(obj)` Checks if an object is sealed. 948 | - `Object.keys(obj)` Returns an array of a given object's own enumerable properties. 949 | - `Object.preventExtensions(obj)` Prevents any extensions of an object. 950 | - `Object.seal(obj)` Prevents other code from deleting properties of an object. 951 | - `Object.setPrototypeOf(obj, prototype)` Sets the prototype (i.e., the internal [[Prototype]] property). 952 | - `Object.values(obj)` Returns an array of a given object's own enumerable property values. 953 | 954 | ### Example of object.assign() 955 | 956 | ```javascript 957 | // Create a target object 958 | const target = { 959 | name: 'John', 960 | age: 30, 961 | } 962 | 963 | // Create source objects 964 | const source1 = { 965 | age: 25, 966 | profession: 'Engineer', 967 | } 968 | 969 | const source2 = { 970 | city: 'New York', 971 | hobby: 'Guitar', 972 | } 973 | 974 | // Use Object.assign to copy values from sources to the target 975 | Object.assign(target, source1, source2) 976 | 977 | // Display the modified target object 978 | console.log(target) 979 | ``` 980 | 981 | ### Looping Through Properties Using for...in 982 | 983 | for...in loops through an object's properties to access and work with each property and its associated value. 984 | 985 | ```javascript 986 | for (const key in myObject) { 987 | console.log(key, myObject[key]) // Logs key and value of each property 988 | } 989 | ``` 990 | 991 | ### Object Destructuring 992 | 993 | Destructuring objects in JavaScript allows you to extract properties from objects and assign them to variables, providing a concise and readable way to work with object data. This feature enhances code clarity and reduces redundancy, especially when dealing with functions that return objects or when accessing object properties in different parts of your code. 994 | 995 | - **Clarity and readability:** Destructuring makes it explicit which properties of the object you are interested in, improving code readability compared to accessing properties by their keys. 996 | - **Conciseness:** Destructuring allows you to extract multiple properties from an object in a single statement, reducing the verbosity of your code. 997 | - **Variable naming:** When destructuring, you can assign more descriptive variable names to the extracted properties, enhancing code comprehension. 998 | - **Avoiding repetition:** Destructuring helps you avoid repeating object property access, leading to cleaner and more maintainable code. 999 | - **Function return values:** Destructuring can be particularly useful when dealing with functions that return objects, enabling you to easily extract and utilize the returned properties. 1000 | 1001 | ```javascript 1002 | // Define an object with properties 1003 | const person = { 1004 | firstName: 'John', 1005 | lastName: 'Doe', 1006 | age: 30, 1007 | } 1008 | 1009 | // Destructure the object into individual variables 1010 | const { firstName, lastName, age } = person 1011 | 1012 | // Log the individual variables 1013 | console.log(firstName) // Output: John 1014 | console.log(lastName) // Output: Doe 1015 | console.log(age) // Output: 30 1016 | ``` 1017 | 1018 | ## [🔝 Back to Top](#top) 1019 | 1020 | ## 3.6 ERROR HANDLING 1021 | 1022 | Overview of error handling mechanisms in JavaScript. 1023 | 1024 | ### try...catch Statement 1025 | 1026 | Handles exceptions by testing a block of code for errors. 1027 | 1028 | ```javascript 1029 | try { 1030 | // Code that may throw an error 1031 | } catch (error) { 1032 | console.log(error) // Handling the error 1033 | } 1034 | ``` 1035 | 1036 | ### try...catch...finally Statement 1037 | 1038 | Includes a block that runs regardless of the result. 1039 | 1040 | ```javascript 1041 | try { 1042 | // Code that may throw an error 1043 | } catch (error) { 1044 | console.log(error) // Handling the error 1045 | } finally { 1046 | // Code that will run regardless of try / catch outcome 1047 | } 1048 | ``` 1049 | 1050 | ### throw Statement 1051 | 1052 | Creates a custom error. 1053 | 1054 | ```javascript 1055 | function checkNumber(num) { 1056 | if (isNaN(num)) { 1057 | throw new Error('Input is not a number') // Custom error 1058 | } 1059 | } 1060 | ``` 1061 | 1062 | ### Example Usage of throw 1063 | 1064 | ```javascript 1065 | try { 1066 | checkNumber('A') 1067 | } catch (e) { 1068 | console.log(e.message) // Output: Input is not a number 1069 | } 1070 | ``` 1071 | 1072 | ## [🔝 Back to Top](#top) 1073 | 1074 | ## 4.1 STRINGS 1075 | 1076 | Overview of commonly used methods of the String object. 1077 | 1078 | ### Properties 1079 | 1080 | - `str.length` Returns the length of the string. 1081 | - `str.[index]` Allows you to access characters in the string using bracket notation 1082 | 1083 | ### Methods 1084 | 1085 | - `str.charAt(index)` Returns the character at the specified index. 1086 | - `str.charCodeAt(index)` Returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. 1087 | - `str.concat(string2, string3[, ..., stringN])` Concatenates the string arguments to the calling string and returns a new string. 1088 | - `str.includes(searchString, position)` Determines whether one string may be found within another string, returning true or false. 1089 | - `str.indexOf(searchValue[, fromIndex])` Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 1090 | - `str.lastIndexOf(searchValue[, fromIndex])` Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 1091 | - `str.match(regexp)` Used to match a regular expression against a string. 1092 | - `str.repeat(count)` Constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. 1093 | - `str.replace(searchFor, replaceWith)` Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. 1094 | - `str.search(regexp)` Executes a search for a match between a regular expression and this String object. 1095 | - `str.split(separator[, limit])` Splits a String object into an array of strings by separating the string into substrings. 1096 | - `str.substr(start[, length])` Returns the characters in a string beginning at the specified location through the specified number of characters. 1097 | - `str.substring(indexStart[, indexEnd])` Returns a new string containing the specified part of the given string. 1098 | - `str.toLowerCase()` Returns the calling string value converted to lowercase. 1099 | - `str.toUpperCase()` Returns the calling string value converted to uppercase. 1100 | - `str.trim()` Trims whitespace from the beginning and end of the string. 1101 | - `str.valueOf()` Returns the primitive value of a String object. 1102 | 1103 | ### String Interpolation (Template Literals) 1104 | 1105 | - `const name = "Alice";` 1106 | - `` `const greeting = `Hello, ${name}!`;` `` Hello, Alice! 1107 | 1108 | ### Multi-line Strings using Template Literals 1109 | 1110 | ```javascript 1111 | const multiLineString = `This is a string 1112 | that spans across 1113 | multiple lines` 1114 | console.log(multiLineString) 1115 | ``` 1116 | 1117 | ## [🔝 Back to Top](#top) 1118 | 1119 | ## 4.2 NUMBERS 1120 | 1121 | Fundamental number-related functionalities in JavaScript. 1122 | 1123 | ### What is an Integer? 1124 | 1125 | An integer is a whole number without any fractional or decimal parts, such as -1, 0, or 42. It's used in scenarios requiring countable quantities, like loop counters, array indexes, or any situation where partial values don't make sense. 1126 | 1127 | ### What is a Floating-Point Number? 1128 | 1129 | A floating-point number includes decimal parts, allowing for the representation of fractions and precise measurements, like 3.14 or -0.01. Useful in calculations requiring high precision, such as financial transactions, scientific computations, or any scenario where small, incremental values matter. 1130 | 1131 | ### parseInt(string, radix) 1132 | 1133 | The `parseInt()` function in JavaScript is used to convert a string to an integer (whole number). It takes two parameters: 1134 | 1135 | - The string to be converted (which should represent a number) 1136 | - The base (or radix) of the numerical system to which the string belongs 1137 | 1138 | When using `parseInt()`, it's crucial to specify the radix to ensure accurate conversion. 1139 | 1140 | - For decimal numbers (the usual number system), use base 10. 1141 | - For binary numbers (0s and 1s), use base 2. 1142 | 1143 | - **Decimal (Base 10):** `parseInt("10", 10);` - Converts the string "10" to an integer in the decimal numerical system (base 10). 1144 | - **Binary (Base 2):** `parseInt("10", 2);` - Converts the string "10" to an integer in the binary numerical system (base 2). 1145 | 1146 | ### parseInt Example 1147 | 1148 | ```javascript 1149 | // Sample input from the user 1150 | const userInput = '42' 1151 | 1152 | // Using parseInt to convert the string to an integer 1153 | const parsedNumber = parseInt(userInput) 1154 | 1155 | // Checking if the conversion was successful 1156 | if (!isNaN(parsedNumber)) { 1157 | console.log(`Parsed number: ${parsedNumber}`) 1158 | console.log(`Type of parsedNumber: ${typeof parsedNumber}`) 1159 | } else { 1160 | console.log('Conversion failed. Please enter a valid number.') 1161 | } 1162 | ``` 1163 | 1164 | ### parseFloat(string) 1165 | 1166 | `parseFloat("3.14");` Converts the string "3.14" to a floating-point number. 1167 | 1168 | ### toFixed(digits) 1169 | 1170 | ```javascript 1171 | const num = 123.456 1172 | num.toFixed(2) // Returns "123.46" - formats the number using fixed-point notation. 1173 | ``` 1174 | 1175 | ### Array Destructuring 1176 | 1177 | ```javascript 1178 | const fruits = ['Apple', 'Banana', 'Cherry'] 1179 | const [firstFruit, secondFruit] = fruits 1180 | console.log(firstFruit) // 'Apple' 1181 | console.log(secondFruit) // 'Banana' 1182 | ``` 1183 | 1184 | ### Spread Operator in Arrays 1185 | 1186 | ```javascript 1187 | const primeNumbers = [2, 3, 5] 1188 | const morePrimes = [7, ...primeNumbers, 11] 1189 | console.log(morePrimes) // [7, 2, 3, 5, 11] 1190 | ``` 1191 | 1192 | ### Additional Number Properties and Methods 1193 | 1194 | - `Number.isFinite(1000);` true 1195 | - `Number.isNaN(NaN);` true 1196 | - `Number.isInteger(10);` true 1197 | - `Number.isSafeInteger(10);` true 1198 | - `Number.MAX_VALUE;` The largest positive representable number 1199 | - `Number.MIN_VALUE;` The smallest positive representable number 1200 | 1201 | ## [🔝 Back to Top](#top) 1202 | 1203 | ## 4.3 MATH 1204 | 1205 | Essential guide to JavaScript's Math object, covering basic constants and mathematical functions. 1206 | 1207 | ### Math Constants 1208 | 1209 | - `Math.PI; π:` Approximately 3.14159 1210 | - `Math.E; Euler's constant, e:` Approximately 2.718 1211 | 1212 | ### Basic Math Methods 1213 | 1214 | - `Math.abs(-5);` Absolute value: Returns 5 1215 | - `Math.ceil(4.2);` Ceiling: Rounds up to 5 1216 | - `Math.floor(4.8);` Floor: Rounds down to 4 1217 | - `Math.round(4.5);` Round: Rounds to 5 1218 | - `Math.max(1, 3, 5);` Maximum value: Returns 5 1219 | - `Math.min(1, 3, 5);` Minimum value: Returns 1 1220 | - `Math.trunc(5.4);` Removes the decimal (.4): Returns 5 1221 | 1222 | ### Exponential and Logarithmic Functions 1223 | 1224 | - `Math.exp(1);` e^1: Returns Euler's number raised to the power of 1 1225 | - `Math.log(10);` Natural logarithm of 10 1226 | 1227 | ### Trigonometric Functions (Basic) 1228 | 1229 | - `Math.sin(0)` Sine: Returns 0 (sin of 0 degrees) 1230 | - `Math.cos(Math.PI);` Cosine: Returns -1 (cos of 180 degrees) 1231 | 1232 | ### Power and Square Root Functions 1233 | 1234 | - `Math.pow(2, 3);` 2 to the power of 3: Returns 8 1235 | - `Math.sqrt(16);` Square root of 16: Returns 4 1236 | 1237 | ## [🔝 Back to Top](#top) 1238 | 1239 | ## 4.4 DATES 1240 | 1241 | Introduction to JavaScript's Date object, focusing on creating, manipulating, and formatting dates. 1242 | 1243 | ### Creating Date Objects 1244 | 1245 | - `const now = new Date();` Current date and time 1246 | - `const specificDate = new Date('2024-01-24');` Specific date (YYYY-MM-DD) 1247 | - `const specificDateTime = new Date('2024-01-24T12:00:00');` Specific date and time (YYYY-MM-DDTHH:MM:SS) 1248 | 1249 | ### Date Methods 1250 | 1251 | - `now.getFullYear();` Get the year as a four digit number (yyyy) 1252 | - `now.getMonth();` Get the month as a zero-based value (0-11) 1253 | - `now.getDate();` Get the day as a number (1-31) 1254 | - `now.getDay();` Get the weekday as a number (0-6) 1255 | - `now.getHours();` Get the hour (0-23) 1256 | - `now.getMinutes();` Get the minute (0-59) 1257 | - `now.getSeconds();` Get the second (0-59) 1258 | - `now.getMilliseconds();` Get the milliseconds (0-999) 1259 | - `now.getTime();` Get the time (milliseconds since January 1, 1970) 1260 | 1261 | ### Setting Date Values 1262 | 1263 | - `now.setFullYear(2024);` Set the year (optionally month, day) 1264 | - `now.setMonth(0);` Set the month (0-11) 1265 | - `now.setDate(24);` Set the day as a number (1-31) 1266 | - `now.setHours(12);` Set the hour (0-23) 1267 | - `now.setMinutes(30);` Set the minute (-59) 1268 | - `now.setSeconds(30);` Set the second (0-59) 1269 | - `now.setMilliseconds(123);` Set the milliseconds (0-999) 1270 | 1271 | ### Formatting Dates 1272 | 1273 | - `now.toDateString();` Converts the date portion to a readable string 1274 | - `now.toTimeString();` Converts the time portion to a readable string 1275 | - `now.toLocaleDateString();` Returns the date portion in a locale-sensitive format 1276 | - `now.toLocaleTimeString();` Returns the time portion in a locale-sensitive format 1277 | - `now.toISOString();` Returns the date in ISO format (YYYY-MM-DDTHH:MM:SS.sssZ) 1278 | 1279 | ### Comparing Dates 1280 | 1281 | - `const earlier = new Date('2024-01-01');` 1282 | - `const later = new Date('2024-12-31');` 1283 | - `const isLater = later > earlier;` true if 'later' is a later date than 'earlier' 1284 | 1285 | ## [🔝 Back to Top](#top) 1286 | 1287 | ## 4.5 RANDOMNESS WITH Math.random() 1288 | 1289 | `Math.random()` is a powerful JavaScript function that generates a pseudo-random number between 0 (inclusive) and 1 (exclusive). This function is widely used in various programming scenarios, from simple tasks like randomizing UI elements to complex simulations and algorithms. Understanding how to effectively use `Math.random()` can add a dynamic and unpredictable element to your applications. 1290 | 1291 | ### Generating a Random Number 1292 | 1293 | ```javascript 1294 | const randomNumber = Math.random() 1295 | console.log(randomNumber) // Any number between 0 and 1 1296 | ``` 1297 | 1298 | ### Selecting a Random Item from an Array 1299 | 1300 | Often, you need to pick an item randomly from a list. Here's how you can do it: 1301 | 1302 | ```javascript 1303 | const items = ['Apple', 'Banana', 'Cherry', 'Date'] 1304 | const randomIndex = Math.floor(Math.random() * items.length) 1305 | const randomItem = items[randomIndex] 1306 | console.log(randomItem) // Randomly selected item 1307 | ``` 1308 | 1309 | ### Generating an integer with Math.random() 1310 | 1311 | When it comes to generating a random integer between two values you can use either `Math.trunc()` or `Math.floor()`. The distinction between the two only matters for negative numbers, as `Math.random()` always returns a positive number. 1312 | 1313 | ### Math.trunc 1314 | 1315 | - Math.trunc can be paired with `Math.random()` for generating zero-based index values, useful in selecting random elements from an array. For example, `Math.trunc(Math.random() * array.length)` can randomly index into an array, ensuring the index starts at 0 and is within the array bounds. 1316 | 1317 | ### Math.floor 1318 | 1319 | - Math.floor, on the other hand, can be utilized with `Math.random()` to create inclusive upper-bound random integers. For instance, `Math.floor(Math.random() * (max - min + 1)) + min` generates a random integer between min and max, inclusively, catering to situations where the starting integer is 1 and the upper limit must be part of the outcome range. 1320 | 1321 | ### Advanced Applications 1322 | 1323 | `Math.random()` can be adapted for more complex scenarios, enhancing its utility beyond simple random selection. 1324 | 1325 | ### Randomizing Within a Range 1326 | 1327 | To generate a random number within a specific range, you can modify the output of `Math.random()`: 1328 | 1329 | ```javascript 1330 | function getRandomInRange(min, max) { 1331 | return Math.random() * (max - min) + min 1332 | } 1333 | console.log(getRandomInRange(1, 100)) // Random number between 1 and 100 1334 | ``` 1335 | 1336 | ### Weighted Random Selection 1337 | 1338 | In situations where options have different probabilities of being chosen, a weighted random selection algorithm can be implemented: 1339 | 1340 | ```javascript 1341 | function weightedRandom(options) { 1342 | let i, 1343 | sum = 0, 1344 | r = Math.random() 1345 | for (i in options) { 1346 | sum += options[i] 1347 | if (r <= sum) return i 1348 | } 1349 | } 1350 | const choices = { A: 0.1, B: 0.3, C: 0.6 } 1351 | console.log(weightedRandom(choices)) // "C" has a higher chance of being selected 1352 | ``` 1353 | 1354 | ### Dynamic Randomness 1355 | 1356 | `Math.random()` can be particularly useful in scenarios where the data is dynamic or the exact values are not known in advance. For example, in game development for spawning items at random locations or in simulations where random factors influence outcomes. 1357 | 1358 | ```javascript 1359 | // Function to simulate rolling a six-sided die 1360 | function rollDice() { 1361 | // Generate a random number between 1 and 6 1362 | let result = Math.floor(Math.random() * 6) + 1 1363 | 1364 | return result 1365 | } 1366 | 1367 | // Example usage 1368 | console.log('Rolling the dice...') 1369 | let rollResult = rollDice() 1370 | console.log('The result is:', rollResult) 1371 | ``` 1372 | 1373 | ## [🔝 Back to Top](#top) 1374 | 1375 | ## 5.1 UNDERSTANDING DOM & DOM MANIPULATION 1376 | 1377 | The DOM (Document Object Model) is a JavaScript programming interface for web documents. It represents web pages as a tree of nodes and objects, allowing you to change their structure, style, and content. 1378 | 1379 | ### The DOM Basics 1380 | 1381 | - **Introduction to the DOM**: The DOM is a way to interact with web documents using JavaScript. It represents the page as a tree, enabling you to modify its content and structure. 1382 | 1383 | - **window Object**: The `window` object represents the browser window and provides functions and properties for window control and event handling. 1384 | 1385 | - **document Object**: The `document` object represents the web page's content. It allows JavaScript to add, modify, and interact with elements on the page. 1386 | 1387 | ### Dom Manipulation Process 1388 | 1389 | To manipulate the DOM, you begin by selecting the desired DOM element(s) using methods like getElementById, querySelector, or getElementsByClassName. Once you've selected the element(s), you can directly apply modifications, such as changing content or styling. While it's common to assign elements to variables for convenience and reusability, it's not mandatory. You can select elements and perform modifications without the need for intermediate variable declarations. 1390 | 1391 | ### Example: Basic interaction with the DOM using JavaScript 1392 | 1393 | ```javascript 1394 | // Access an element by its ID 1395 | const element = document.getElementById('example-element') 1396 | 1397 | // Modify the element's content 1398 | element.innerHTML = 'This is the new content.' 1399 | 1400 | // This updates the HTML content of the element. 1401 | ``` 1402 | 1403 | ## [🔝 Back to Top](#top) 1404 | 1405 | ## 5.2 ACCESSING AND MODIFYING DOM ELEMENTS 1406 | 1407 | Methods for selecting, creating, and modifying DOM elements. 1408 | 1409 | ### Primary Methods of Accessing Elements 1410 | 1411 | - `document.getElementById(id);` Gets an element by its ID. 1412 | - `document.querySelector(selector);` Returns the first element matching the specified CSS selector. 1413 | - `document.querySelectorAll(selector);` Returns a NodeList of all elements matching the specified CSS selector. 1414 | 1415 | ## Other Methods of Accessing elements 1416 | 1417 | - `document.getElementsByTagName(name);` Returns a live HTMLCollection of elements with the given tag name. 1418 | - `document.getElementsByClassName(className);` Returns a live HTMLCollection of elements with the given class name. 1419 | 1420 | ### Creating and Inserting Elements 1421 | 1422 | - `const newElement = document.createElement(tagName);` Creates a new element with the specified tag name. 1423 | - `element.appendChild(newElement);` Appends the new element as the last child of the parent element. 1424 | 1425 | ### Removing Elements 1426 | 1427 | - `element.removeChild(child);` Removes a child node from the DOM. 1428 | 1429 | ### Modifying Elements 1430 | 1431 | - `element.innerHTML = '

New HTML content

';` Changes the HTML content of an element. 1432 | - `element.textContent = 'New text content';` Changes the text content of an element. 1433 | - `element.setAttribute(name, value);` Sets a new value for an attribute on the element. 1434 | - `element.getAttribute(attributeName);` Gets the current value of an attribute on the element. 1435 | - `element.removeAttribute(attributeName);` Removes an attribute from the element. 1436 | - `element.classList.add(className);` Adds a class to the element. 1437 | - `element.classList.remove(className);` Removes a class from the element. 1438 | - `element.classList.toggle(className);` Toggles a class on the element. 1439 | - `element.style.property = "value";` Changes the style of an element. 1440 | 1441 | ### Methods For Acessesing Various HTML Element Types 1442 | 1443 | - `` .value, .disabled, .checked 1444 | - `
` .innerText, .innerHTML, .textContent, .style 1445 | - `` .innerText, .innerHTML, .textContent, .style 1446 | - `

` .innerText, .innerHTML, .textContent, .style 1447 | - ``**(Anchor):** .innerText, .innerHTML, .textContent, .href, .target, .style 1448 | - `