JavaScript cheatsheet

Published 6 months ago: July 13, 2020


Cheatsheet for JavaScript

This cheatsheet is a small collection of handy snippets for quick reference in tricky situations. Feel free to suggest edits, propose additions, complain about something, disagree with content or such and the like. Every feedback is a welcome one.

Generate UUID (v4)

function uuidv4() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
    return v.toString(16);
    });
}

Styling

let element = document.querySelector("#navbar-foo");

/* Remove or add a CSS class depending on if it exists or not */
element.classList.toggle("is-active");

/* Add multiple CSS classes in one go */
element.classList.add("navbar-item", "is-capitalized");

/* Style the HTML element directly */
element.style.display = "block";

/* Set multiple Style Object Properties Using the generic setAttribute method */
element.setAttribute("style", "position: fixed; bottom: 0; width: 50vw; left: 25%;");

Send and retrieve data using Fetch API

All examples demonstrates Async fetch. Fetch API is also available using promises

(PUT) Update a JSON resource at an endpoint

async function update_document(doc) {
    const url = 'https://example.com/json_endpoint';
    try {
        const response = await fetch(url, {
            method: "PUT",
            body: JSON.stringify(doc), 
            headers: {
                "Content-Type": "application/json"
            }
        });
        const result = await response.json();
        return await result;
    } catch (error) {
        console.log(error);
    }
}

const doc = {
    foo: "bar",
    test: true
};

update_document(doc);

Create HTML elements

const list = document.querySelector("#list");

let element = document.createElement("LI");

/* add another element inside the list item */
let link = document.createElement("A");
link.textContent = "Visit site";
link.href = "https://lybekk.tech";

element.appendChild(link);

list.appendChild(element);

Create an onclick event on an HTML element

const btn = document.getElementById("button");

btn.onclick = function() {
    const popup = document.getElementById("popup");
    popup.style.display = "none";
};

Accessing in-browser storage

Interface with the Web Storage API

Local Storage

/* Retrieve an item */
localStorage.getItem('weather');

/* Save a string*/
localStorage.setItem('weather', 'Snow');

/* Save an object */
localStorage.setItem(
    'weather', JSON.stringify({
        hour: 08,
        type: 'Hail'
    })
);

Session Storage

Session storage interaction works in the same way as Local Storage. Just replace localStorage with sessionStorage

Pick random item from an array

const items = ["Item one", "Another item", "Item, the third"]

function item() {
    const item = items[Math.floor(Math.random() * items.length)];
    return item
}

console.log(item())

includes()

Strings

const str = "Hello world, welcome to the universe.";
const n = str.includes("world");

Array

const numbers = [10, 12, 1, 2, 0]
if (numbers.includes(1) {
    console.log("Exists")
}

some()

const numbers = [10, 12, 1, 2, 0]
const isTrue = numbers.some(number => {
    return number > 2
})
if (isTrue) {
    console.log("This is true")
}

Christoffer Lybekk

Developer under development

Explore more articles with similar tags

JavaScriptSyntaxCheatsheet

Article stats


79words

19sentences

18paragraphs

1 minread time