JavaScript cheatsheet

Published: 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);


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

/* Remove or add a CSS class depending on if it exists or not */

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

/* Style the HTML element directly */ = "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 = '';
    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) {

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


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 = "";



Create an onclick event on an HTML element

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

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

Accessing in-browser storage

Interface with the Web Storage API

Local Storage

/* Retrieve an item */

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

/* Save an object */
    '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

Christoffer Lybekk

Developer under development

Explore more articles with similar tags


Article stats




1 minread time