JavaScript Cheatsheet

repository·master·Indexed 20 days ago

https://github.com/wilfredinni/javascript-cheatsheet

A comprehensive reference guide for JavaScript syntax and methods. It provides quick lookups for core language features including array manipulations (such as map, reduce, and slice), regular expressions, control flow, and asynchronous programming with async/await and try/catch blocks.

Tokens
32.3K
Snippets
168
Records
177
Agent score
69%

What's inside javascript-cheatsheet

  1. Overview of the JavaScript Cheatsheet

    master

    The javascript-cheatsheet is a reference resource designed for both beginner and advanced developers. It provides quick syntax references for common JavaScript tasks to lower the entry barrier for newcomers and serve as a refresher for experienced developers.

    Key topics covered include:

    • Regular Expressions (e.g., making character classes)
    • Array Methods (e.g., slice)
    • Control Flow (e.g., for loops)
  2. Check for HTTP errors in fetch()

    master

    A critical detail of the Fetch API is that the promise only rejects on network failure. HTTP error statuses (like 404 Not Found or 500 Internal Server Error) do not cause the promise to reject; instead, the promise resolves normally. To handle these cases, you must manually check the response.ok property (which is true if the status is in the 200-299 range) or inspect response.status.

    async function checkStatus() {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts/invalid-id');
      
      if (!response.ok) {
        console.log('Network response was not ok:', response.status);
        return;
      }
      
      const data = await response.json();
      console.log(data);
    }
    
    checkStatus();
  3. Compare for loops and array methods

    master

    When iterating over data, you can choose between a standard for loop or declarative array methods (like map, filter, reduce, or forEach).

    When to use a For Loop:

    • Control: When you need fine-grained control over initialization, conditions, or increments.
    • Performance: Can be more efficient for very large datasets.
    • Flow Control: When you need to use the break statement to exit the loop early (array methods like forEach do not support break).
    • Mutation: When you want to mutate the original array in place.

    When to use Array Methods:

    • Readability: They provide a declarative syntax that is often easier to read.
    • Immutability: Methods like map, filter, and reduce return new arrays instead of mutating the original.
    • Composition: They can be chained together to perform complex transformations in a clean way.
    // For Loop (Mutates original array)
    let arr = [1, 2, 3, 4, 5];
    for (let i = 0; i < arr.length; i++) {
      arr[i] = arr[i] * 2;
      console.log(arr[i]);
    }
    
    // Map Method (Returns new array, preserves immutability)
    let arr = [1, 2, 3, 4, 5];
    let doubled = arr.map(num => num * 2);
    console.log(doubled);
  4. Understand the `async` keyword

    master

    Declaring a function with the async keyword transforms it into an asynchronous function. A key characteristic of async functions is that they always return a promise, even if you return a non-promise value like a number or a string. The caller will receive a promise that resolves to that value.

    async function getNumber() {
      return 7;
    }
    
    // The caller receives a promise that resolves to 7
    getNumber().then((value) => console.log(value));
  5. Use `await` to handle promises

    master

    The await keyword pauses the execution of an async function until a promise settles (resolves or rejects). This allows you to write asynchronous logic that reads like synchronous, step-by-step code.

    Constraints:

    • await can only be used inside an async function, or at the top-level of an ES module.
    async function getUser() {
      const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
      const user = await response.json();
      return user.name;
    }
    
    getUser().then((name) => console.log(name));
  6. Understand error propagation

    master

    When an error is thrown and not caught within the current function, it 'propagates' up the call stack to the calling function. This continues until an error handler is found. If no handler catches the error, the program will typically crash with an unhandled exception.

    function function1() {
      function2();
    }
    
    function2() {
      throw new Error("An error occurred");
    }
    
    try {
      function1();
    } catch (error) {
      console.log("Caught an error: " + error.message);
    }
  7. Use function parameters and arguments

    master

    Parameters are the names listed in the function definition. Arguments are the actual values passed to the function when it is called.

    • Extra arguments: If you pass more arguments than parameters, the extra ones are ignored.
    • Missing arguments: If you pass fewer arguments than parameters, the missing ones are set to undefined.
    function add(a, b) {
      return a + b;
    }
    
    let sum = add(1, 2); // 1 and 2 are arguments; a and b are parameters
    console.log(sum); // 3
  8. Understand the JavaScript Math object

    master

    The Math object is a built-in object used to perform mathematical tasks on numbers.

    Key Concept: The Math object is not a constructor. All its properties and methods are static. You do not use the new keyword. Instead, you access properties directly (e.g., Math.PI) or call methods directly (e.g., Math.sin(x)).

  9. Access and modify array elements using indexes

    master

    JavaScript arrays use zero-based indexing. Each element has a numeric position starting at 0 and incrementing by 1 for each subsequent element. You can use these indexes to both retrieve values and update them.

    let fruits = ['apple', 'banana', 'cherry'];
    
    // Accessing elements
    console.log(fruits[0]); // 'apple'
    console.log(fruits[1]); // 'banana'
    
    // Modifying elements
    fruits[1] = 'blueberry';
    console.log(fruits[1]); // 'blueberry'
  10. Declare variables using var, let, or const

    master

    There are three ways to declare variables in JavaScript, each with different scoping and reassignment rules:

    1. var: The legacy way to declare variables. It is function-scoped and subject to hoisting (the variable can be accessed before its declaration in the code).
    2. let: Introduced in ES6. It is block-scoped (only available within the {} block where it is defined) and is not hoisted in the same way as var.
    3. const: Introduced in ES6. It is block-scoped and creates a constant that cannot be reassigned.

    Important Note on const: While you cannot reassign a const variable itself, if the variable holds an object or an array, you can still modify the properties or elements inside that object/array.

    var name = "John";
    console.log(name);
    
    let age = 25;
    console.log(age);
    
    const pi = 3.14159;
    console.log(pi);