2024-08-11

JS cheatsheet


JavaScript is typically used either for adding interactivity to HTML documents or on the server side.

Variables

js
let isValid = true;
// ...
isValid = false;
js
const name = "Marcin";

// Can't be changed.
// 🚫 name = "Peter";

Data types

Number

js
let i = 10;
let price = 99.99;

BigInt

js
// notice the 'n' at the end
const bigInt = 1234567890123456789012345678901234567890n;

String

js
let name = 'Marcin';

Boolean

js
let isValid = false;

Undefined

js
let surname;

Null

js
let city = null;

Object

js
const config = {
    url: 'https://msaja.dev/api/',
    port: 8080,
}

Symbol

js
let id = Symbol();

Conditional statements

js
if (isValid) {
    console.log('Valid!');
}
js
if (isValid) {
    console.log('Valid!');
} else {
    console.log('Invalid!');
}
js
if (requestMethod === 'GET') {
    console.log('GET');
} else if (requestMode === 'POST') {
    console.log('POST');
} else if (requestMode === 'PATCH') {
    console.log('PATCH');
} else {
    console.log(requestMode);
}
js
switch (requestMethod) {
    case 'GET':
        console.log('GET');
        break;
    case 'POST':
        console.log('POST');
        break;
    case 'PATCH':
        console.log('PATCH');
        break;
    default:
        console.log('Default value');
}
js
const price = (promotionCode === 'PROM') ? 99.99 : 129.99;

Comparisons

js
console.log(10 > 1); // true
console.log(10 >= 1); // true
console.log(10 <= 1); // false
console.log(10 == 1); // false
console.log(10 != 1); // true

Strict equality

js
console.log('1' === 1); // false
console.log('test' === 'test'); // true

Nullish coalescing operator '??'

If the first argument is not null/undefined, then return it.

js
const label = post.title ?? 'Post title';

Loops

js
while (!isFinished) {
    // loop
}
js
do {
    // loop
} while (!isFinished)
js
for (let i = 1; i <= 10; i++) {
    console.log(i);
}
// 1 2 3 4 5 6 7 8 9 10
js
const names = ['Marcin', 'Peter', 'Robert'];
for (const value of names) {
    console.log(value);
}
// Marcin Peter Robert
js
const names = ['Marcin', 'Peter', 'Robert'];
for (const index in names) {
    console.log(index);
}
// 0 1 2

Error handling

js
try {
    // code
} catch (e) {
    // handle errors
} finally {
    // execute always
}

Functions

js
function sum(a, b) {
    return a + b;
}

console.log(sum(99, 10)); // 109

Arrow function

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

Arrays

js
let years = [2021, 2022, 2023];

console.log(years.length); // 2
console.log(years[0]); // 2021

push() / pop()

js
let animals = ['dog', 'cat', 'bird'];

animals.push('wolf');
console.log(animals); // ['dog', 'cat', 'bird', 'wolf']

const wolf = animals.pop();
console.log(animals); // ['dog', 'cat', 'bird']

unshift() / shift()

js
let thrash = [true, 123, "dog", { name: 'Marcin' }];

thrash.unshift(999);
console.log(thrash); // [999, true, 123, "dog", { name: 'Marcin' }]

thrash.shift();
console.log(thrash); // [true, 123, "dog", { name: 'Marcin' }]

concat()

js
let usCities = ['Los Angeles', 'New York'];
let euCities = ['Warsaw', 'Berlin', 'Paris'];

const cities = usCities.concat(euCities);
console.log(cities); // ["Los Angeles", "New York", "Warsaw", "Berlin", "Paris"]

forEach()

js
let names = ['Marcin', 'Peter', 'Robert'];

names.forEach((item, index, array) => {
    console.log(item);
});

indexOf() / includes()

js
let names = ['Marcin', 'Peter', 'Robert'];

console.log(names.indexOf('Robert')); // 2
console.log(names.indexOf('Joe')); // -1

console.log(names.includes('Robert')); // true

find() / findIndex()

js
let customers = [{
    name: 'Peter',
    age: 60,
}, {
    name: 'Joe',
    age: 12,
}, {
    name: 'Thomas',
    age: 33,
}];

customers.find((customer, index, customers) => {
    return customer.age < 18;
}); // { name: 'Joe', age: 12 }

customers.findIndex((customer, index, customers) => {
    return customer.age < 18;
}); // 1

filter()

js
const results = [33, 99, 5, 88, 123, -890];

results.filter((item, index, array) => item <= 33); // [33, 5, -890]

map()

js
const results = [5, 4, 3, 2, 1];

results.map((item, index, array) => item * item); // [25, 16, 9, 4, 1]

reduce()

js
const results = [5, 4, 3, 2, 1];

results.reduce((sum, current) => sum + current, 0); // 15

sort()

Sorts the elements of an array in place.

js
const results = [4, 5, 1, 3, 2];

results.sort((a, b) => {
    if (a > b) {
        return 1;
    }
    if (a == b) {
        return 0;
    }
    if (a < b) {
        return -1;
    }
}); // [1, 2, 3, 4, 5]

reverse()

Reverses the elements of an array in place.

js
const results = [5, 4, 3, 2, 1];

results.reverse(); // [1, 2, 3, 4, 5]

join()

js
const name = ['Peter', 'Joe', 'Marcin'];

console.log(name.join(', ')); // Peter, Joe, Marcin

Array.isArray()

js
console.log(Array.isArray([1, 2, 3])); // true

Map

js
const cache = new Map();
cache.set('id_1', 'value1');
cache.set(123, 'value2');
cache.set(true, 'value3');

const player = { name: 'Manuel' };
cache.set(player, 'value4');

console.log(cache.size); // 4
console.log(cache.get(123)); // value2
console.log(cache.get(player)); // { name: 'Manuel' }

cache.delete('id_1');

Set

Unique set of values.

js
const cards = new Set();
cards.add(2);
cards.add(3);
cards.add(4);
cards.add(5);
cards.add(4);
cards.add(4);

console.log(cards.size); // 4

cards.delete(4);
console.log(cards.has(4)); // false

Objects

js
const player = {
    name: 'Manuel',
    surname: 'Neuer',
    
    play () {
        // play!
    }
}

console.log(player.name); // Manuel
delete player.name;
console.log(player.name); // undefined

player.play();

Object.keys(), Object.values(), Object.entries()

js
const config = {
    path: 'https://localhost',
    port: 8080,
}

console.log(Object.keys(config)); // path, port
console.log(Object.values(config)); // 'https://localhost', 8080
console.log(Object.entries(config)); // ['path', 'https://localhost'], ['port', 8080]

Object.fromEntries()

js
const config = Object.fromEntries([['path', 'https://localhost'], ['port', 8080]]);

console.log(config); // { path: 'https://localhost', "port": 8080 }

Optional chaining '?.'

js
const post = {
    title: 'Post title',
    author: {
        name: 'Marcin',
        group: {
            id: 'administrator'
        }
    }
}

console.log(post.author.group.id); // administrator
console.log(post?.author?.group?.name); // undefined

Classes

js
class Player {
    constructor(name, surname) {
        this.name = name;
        this.surname = surname;
    }
    
    play() {
        // play!
    }
}
js
const goalkeeper = new Player('Manuel', 'Neuer');
goalkeeper.play();

console.log(goalkeeper.name); // Manuel

Promises

js
const promise = new Promise((resolve, reject) => {
    // resolve(value)
    // reject(error)
});

promise
    .then((value) => console.log('Success!', value))
    .catch((error) => console.log('Error!', error));
js
Pomise.all([
    fetch('/api/post/123'),
    fetch('/api/post/123/comments'),
    fetch('/api/post/123/media'),
]).then(handleAllOrNothing);
js
Pomise.allSettled([
    fetch('/api/post/123'),
    fetch('/api/post/123/comments'),
    fetch('/api/post/123/media'),
]).then(handleRegardlessOfTheResult);

// { status: 'fulfilled', value: '...'' }
// { rejected: 'fulfilled', reason: '...'' }
js
Pomise.race([
    fetch('/api/post/123'),
    fetch('/api/post/123/comments'),
    fetch('/api/post/123/media'),
]).then(handleFirstSettledPromise);
js
Pomise.any([
    fetch('/api/post/123'),
    fetch('/api/post/123/comments'),
    fetch('/api/post/123/media'),
]).then(handleFirstFullfilledPromise);

Async / await

js
async function submit(formData) {
    const response = await fetch('/api/post', { method: 'POST', body: formData })
    const result = await response.json();

    return result;
}

Modules

js
// math.js file:

export default function add(x, y) {
    return x + y;
}
js
import add from './math.js';