Skip to content

Latest commit

 

History

History
153 lines (108 loc) · 4.04 KB

javascript.md

File metadata and controls

153 lines (108 loc) · 4.04 KB

JavaScript Cheatsheet

Loops

  1. Loop through array items

    for (let el of arr) {}
  2. Loop through array or object keys

    for (let el in arr) {}

Break out of a loop

  1. Jump out of a loop: break
  2. Jump over one iteration in the loop: continue

Prototypes

  • Old school: const Object = new Prototype()
  • ES6 onwards: Object extends Prototype()

Array methods

  1. Most used ones: array.find & array.filter

  2. Check if a variable is an Array

    const isArray = array instanceof Array;
  3. Check if array includes a certain value among entries

    • If simple check

      array.includes('string');
    • If more complex expression is needed

      const isIncluded = array.some(el => el.name === 'example');
      
      // or for negative check
      const isNotIncluded = !array.some(cb)
  4. Check if all entries of an array match an expression (returns true if all elements returned true)

    const isMatchingAll = array.every(el => el.name)
  5. Crete an array (just as an iterable) with any length necessary

    new Array(5).fill(0)

Arrow functions

  1. Return an object from arrow function

    const function = () => ({ key1: value1, key2: value2 });
  2. To return a multi-line statement from an arrow function, it’s necessary to use () instead of {} to wrap your function body. This ensures the code is evaluated as a single statement.

Using Debuggers

  1. Call stack is debugging's backwards time machine

  2. Right click on the gutter (line numbers) to add an additional condition to the breakpoint

  3. VScode right click on a breakpoint and press log message (instead of console logging)

  4. In Chrome DevTools I can right click anywhere in a file (jQuery Library, Node.js module file) and blackbox it so as I would never get into them when debugging

Node Packages

  1. Apache replacement: http-server

  2. Logging: log4js

  3. Security:

    • Validate and sanitize strings: validator
    • Validate incoming HTTP request body, params etc: joi
    • Secure HTTP headers in express.js: helmet
    • Encrypt-decrypt: crypto or bcrypt
    • Use express-rate-limit to prevent DDOS attacks
    • Easy sanitization:
      data.toString().trim();
  4. Unit tests:

    • mock MongoDB: sinon
    • test express.js without starting it: supertest
    • BONUS terminology: two main types of test doubles used in unit/integration tests are test stubs and mocks.

Misc

  1. Fallback value

    const foo = bar ?? 111;
    // or
    const foo = bar || 111;

    The difference -- when using || all these falsy values result in the return of the fallback value: 0, '', NaN, null, undefined. However, ?? only takes the fallback value only if the first is null or undefined. This is helpful to avoid from skipping 0 or an empty string when they are actually legit values.

  2. Conditional object fields

    const obj = {
        a: 1,
        b: 2,
        ...(foo && { foo: 'bar'})
    }
  3. Bind (TODO make a separate section about it?) function.bind does not run the function, but it can also pre-define first parameter(s):

    const foo = bar.bind(this, setValue)
  4. Operator Precedence in JavaScript makes multiplication (x) run before +

  5. Don't forget to encode and decode query parameters with encodeURIComponent() and decodeURIComponent()

  6. URLSearchParams and URL are useful to construct and pars URLs and query params

  7. Padding strings is now built-in

    7.padStart(3, '0')
    // '007'
  8. Smooth scroll

    document.querySelector(element).scrollIntoView({  behavior: 'smooth' });
  9. Reverse Object.entries with Object.fromEntries()

  10. Browsers have built-in TTS now

    let utterance = new SpeechSynthesisUtterance("Hello world!");
    speechSynthesis.speak(utterance);