Skip to content

JavaScript

External tools

Run prettier and then eslint

prettier --write src
npm run lint -- --fix

Console API

https://developer.chrome.com/docs/devtools/console/api/

console.log("%cMessage", "color: orange; background-color: blue");

Objects

Destructure 3 levels down

match = obj?.props?.match;

If you know the property will exist

const {
    props: { match },
} = obj;
const {
    a: {
        b: {c}
    }
} = obj

Default Dict

(obj['key'] || obj['key'] = []).push('value')

(obj['key'] || obj['key'] = 0) += 1

new keyword

  1. Creates a new object 2. type: object
  2. It sets this new object's internal, inaccessible, [[prototype]] (proto) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
  3. Variable points to the newly created object.
  4. Executes the constructor function
  5. Return the new object
    1. unless the constructor function returns a non-null object reference.
    2. In this case, that object reference is returned instead.

How do you know if they used new?

function Foo() {
    if (!new.target) {
        throw "Foo() must be called with new";
    }
}

Why Set() returns an error without new

  • without the new, the constructor will get called as a regular function
  • it will use this from the caller's context and not from Set and it might break

Arrays

Only getting the second value in an array

[count, setCount];
[, setCount];

Conditional values in an array

const arr = [flag && value].filter(Boolean);

2 arrays: check identical? (same order)

Arr1.length === arr2.length && arr1.every((item, i) => arr2[i] === item);

Sorting

mutates the existing array

  • Alphabetically
    • arr.sort()
  • numerically ascending
    • arr.sort((a, b) => a - b)

Strings

Template Literals

Feels like Python f"formatted_string"

myTag`A${1}B${2}C${3}D${4}E${5}F`;

function myTag(strings, ...args) {
    console.log(strings); // ['A', 'B', 'C', 'D', 'E', 'F']
    console.log(args); // [1,2,3,4,5]
    return strings;
}

Converting anything into a string

String()

String(anyThing)

might not work on older JS versions?

Dates

> date.toLocaleDateString();
'2022-09-08'

Handle month offset

Example * Fiscal year starts in April (month offset = 3)

Useful for getting the quarter

date = new Date('Jan 17, 1995')  // Jan is actually Q4
offset = 3
date.setMonth(date.getMonth() - offset)

> date
1994-10-17

Temporal API

Numbers

NaN

Number.isNaN("a"); // false
isNaN("a"); // true

Number.isNaN(Number(input)) === isNan(input);

Functions

kwargs (obj --> params)

const sum = (a, b) => a+b;

How do I pass this in args = {a: 1, "1": 2}?

Can't destructure

// sum(args)  // a = args, b = undefined
// sum(...args)  // TypeError: Found non-callable @@iterator

Solution: get the object values as an array

// order: [Does JavaScript guarantee object property order?](https://stackoverflow.com/a/23202095)
// 1. integer keys (like "11")
// 2. string keys
// 3. Symbol keys
argValues = Object.values(args)  // [2,1]
c = sum(...argValues)
console.log(c)

Last update: 2022-09-23