JavaScript cheat sheet

Arrow functions

Arrow Functions
// Single argument, single instruction
arg => arg * 2;

// Multiple arguments, single instruction
(arg1, arg2) => arg1 + arg2;

// Multiple arguments, multiple instructions
(arg1, arg2) => {
  arg1 = arg1 * 2;
  return arg1 + arg2;
}
Classic Functions
// Single argument, single instruction
function doubles (arg) {
  return arg * 2;
}

// Multiple arguments, single instruction
function sum (arg1, arg2) {
  return arg1 + arg2;
}

// Multiple arguments, multiple instructions
function sum (arg1, arg2) {
  arg1 = arg1 * 2;
  return arg1 + arg2;
}

IIFE (Immediately Invoking Function Expression)

IIFE
((arg1, arg2) => arg1 + arg2)(3, 6);
Classic function invocation
function sum (arg1, arg2) {
  return arg1 + arg2;
}

sum(3, 6);

Collections

Map
(Collection of key/value pairs)
const m = new Map();    // Creates a new Map
m.set('key', 'value');  // Adds a new key/value pair
m.get('key');           // Retrieves an item by key
m.delete('key');        // Removes an item by key
m.clear();              // Removes all items
m.has('key');           // Returns true/false
m.size;                 // Returns the Map length
m.forEach((value, key) =>  { /* ... */ });  // Iterates all items
Set
(Collection of unique values)
const s = new Set();  // Create a new Set
s.add(23);            // Adds new value
s.has(23);            // Returns true/false
s.delete(23);         // Removes a value
s.clear();            // Removes all values
s.size;               // Returns the Set length
s.forEach((value) => { /* ... */ }); // Iterates all values

Objects & Arrays

Object
const o = new Object();
const o = {};
const o = {
  firstName: 'Chuck',
  lastName: 'Norris',
  age: undefined,
  power: 3000
};

o.age = 23;
o['age'] = 23;

delete o.age;
delete o['age'];
        
Array
// Create arrays
const a = new Array();
const a = [];
const a = [ 1, 1, 2, 3, 5, 8, 13, 21 ];

// Add element(s) to the end
a.push(34);
a.push(34, 55, 89);

// Add element(s) to the beginning
a.unshift(100);
a.unshift(100, 200, 300);

// Add element(s) at index
const i = 3;    /* Index */
const el = 34;  /* Element to be added */
a.splice(i, 0, el);

// Remove last element
a.pop();

// Remove first element
a.shift();

// Remove element(s) by index
const i = 3;  /* Index */
const n = 1;  /* Elements to be removed */
a.splice(i, n);

// Get length
a.length;

// Check if includes element (true/false)
a.includes(2);

// Get index of an element
a.indexOf(5);

// Reverse order
const reversed = a.reverse();
        
 
const a = [
  { title: 'Foo', price: 101 },
  { title: 'Bar', price: 102 },
  { title: 'Baz', price: 103 }
];

// For each
a.forEach((item) => {
  /* ... */
});

// Sort
a.sort((a, b) => {
  if (a.price < b.price) { return -1; }
  if (a.price > b.price) { return 1; }
  return 0;
}

// Filter
const filtered = a.filter((item) => {
  return item.price < 103;
});

// Map
const mapped = a.map((item) => {
  return item.title;
});

// Find
const found = a.find((item) => {
  return item.price === 102;
});

// Has some (true/false)
const hasSome = a.some((item) => {
  return item.price < 103;
});
  
// Has every (true/false)
const hasEvery = a.every((item) => {
  return item.price < 103;
});

// Reduce
const reduced = a.reduce((counter, item) => {
  return item.price + counter;
}, 0);

Accessing Array-like objects

// Accessing an HTMLCollection[]
Array.prototype.forEach.call(document.getElementsByTagName('a'), function (el, index) {
  el.addEventListener('click', function (event) {
    alert(`Hello ${index}`);
    event.preventDefault();
  });
});

// Accessing a NodeList[]
document.querySelectorAll('a').forEach(function (el, index) {
  el.addEventListener('click', function (event) {
    alert(`Hello ${index}`);
    event.preventDefault();
  });
});

// You can use an empty array [] instead of Array.prototype

Store data on Browser

Local Storage
localStorage.setItem('key', 'value');
localStorage.getItem('key');
localStorage.removeItem('key');
Session Storage
sessionStorage.setItem('key1', 'value');
sessionStorage.getItem('key');
sessionStorage.removeItem('key');

Template strings

const arg = 'World';
const template = `Hello ${arg}`;
const sum = `2 + 2 = ${ 2 + 2 }`;
const multiLineString = `To be or not to be
this is the question.`

Optional chaining

const foo = { name: 'Foo', details: { desc: 'Lorem ipsum.' } };
const bar = { name: 'Bar' };

console.log(foo.details.desc); // Returns: Lorem ipsum.
console.log(bar.details.desc); // Throws error and breaks the script execution
console.log(bar?.details?.desc); // Returns 'undefined' and continues the script execution

Best practice: Manipulate virtual DOM in loops by using DocumentFragment

fetch('https://example.com')
  .then(response => response.json())
  .then(data => {

    const fragment = new DocumentFragment();

    data.forEach(item => {

      const li = document.createElement('li');
      const a = document.createElement('a');

      a.href = item.url;
      a.textContent = item.title;

      li.appendChild(a);
      fragment.appendChild(li);

    });

    // Manipulate DOM just at the end
    document.getElementById('foo').appendChild(fragment);

  });

VanillaJS vs JQuery

Document ready

VanillaJS
document.addEventListener('DOMContentLoaded', function () {
  alert('Document ready!');
});
JQuery
$(document).ready(function () {
  alert('Document ready!');
});

Retrieve DOM elements

VanillaJS
Get single element (first match)
document.getElementById('foo');
document.querySelector('.foo');
Get multiple elements (all matches)
document.getElementsByClassName('foo'); // Returns live HTMLCollection[]
document.getElementsByTagName('span'); // Returns live HTMLCollection[]
document.querySelectorAll('.foo'); // Returns static NodeList[]
JQuery
Get single element (first match)
$('#foo');
$('.foo').filter(':first');
$('a').filter(':first');
Get multiple elements (all matches)
$('.foo');
$('a');

Classes manipulation

VanillaJS
document.getElementById('myDiv').classList.add('foo');
document.getElementById('myDiv').classList.add('foo', 'bar');
document.getElementById('myDiv').classList.remove('foo');
document.getElementById('myDiv').classList.remove('foo', 'bar');
document.getElementById('myDiv').classList.toggle('foo');
document.getElementById('myDiv').classList.toggle('foo', i < 10);
document.getElementById('myDiv').classList.replace('foo', 'bar');
JQuery
$('#myDiv').addClass('foo');
$('#myDiv').addClass('foo bar');
$('#myDiv').removeClass('foo');
$('#myDiv').removeClass('foo bar');
$('#myDiv').toggleClass('foo');
$('#myDiv').toggleClass('foo', condition);

Setting click handler

VanillaJS
document.getElementById('foo').addEventListener('click', function (event) {
  alert(`Hello ${index}`);
  event.preventDefault();
});
JQuery
$('#foo').click(function (event) {
  alert('Hello world!');
  event.preventDefault();
});

Manipulate data attributes

VanillaJS
document.getElementById('myDiv').getAttribute('data-foo');
document.getElementById('myDiv').setAttribute('data-foo', 'Hello World!');
document.getElementById('myDiv').removeAttribute('data-foo');

document.getElementById('myDiv').dataset.fooBar = 'Hello World!'; // <div id="myDiv" data-foo-bar="Hello World!"></div>
document.getElementById('myDiv').dataset.fooBar; // Hello World!
JQuery
$('#myDiv').attr('data-foo'); // Get
$('#myDiv').data('foo'); // Get
$('#myDiv').attr('data-foo', 'Hello World!'); // Set
$('#myDiv').data('foo', 'Hello World!'); // Set (not visibile in DOM)

Create DOM element

VanillaJS
var newDiv = document.createElement('div');
console.log(newDiv.outerHTML);
JQuery
var newDiv = $('<div/>');
console.log(newDiv.html());

Append a child element in DOM

VanillaJS
document.getElementById('myDiv').appendChild(newDiv);
JQuery
$('#myDiv').append(newDiv);

Get parent element

VanillaJS
var parent = document.getElementById('myDiv').parentNode;
JQuery
var parent = $('#myDiv').parent();

Async HTTP Request

VanillaJS
XMLHttpRequest
const uri = 'https://example.com';

function AJAX() {
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE) {
      (this.status === 200) ? onSuccess(this) : onError(this);
    }
  }
  xhr.open('GET', uri);
  xhr.responseType = 'json';
  xhr.send();
}

function onSuccess(xhr) {
  console.log('HTTP Response Status Code', xhr.status);
  console.log('HTTP Response Status Text', xhr.statusText);
  console.log('HTTP Response Body', xhr.response);
}

function onError(xhr) {
  console.error('HTTP Response Status Code', xhr.status);
  console.error('HTTP Response Status Text', xhr.statusText);
}

AJAX();
Fetch
const uri = 'https://example.com';
const jsonData = { username: 'example' };
const params = {
  method: 'POST',
  mode: 'cors',
  cache: 'no-cache',
  credentials: 'same-origin',
  headers: { 'Content-Type': 'application/json' },
  referrerPolicy: 'no-referrer',
  body: JSON.stringify(jsonData)
};
fetch(uri, params)
  .then(response => response.json())
  .then(responseBody => console.log('HTTP Response Body', responseBody));
};
fetch(uri, params)
  .then(response => {
    if (!response.ok) { // HTTP Status Code != 2xx
      throw new Error('Server Error');
    }
    return response.json();
  })
  .then(data => console.log('HTTP Response Body', data))
  .catch((err) => console.error(err));
async function AJAX() {
  const response = await fetch(uri, params);
  if (!response.ok) { // HTTP Status Code != 2xx
    throw new Error('Server Error');
  }
  return response.json();
}

AJAX()
  .then(data => console.log('HTTP Response Body', data))
  .catch(err => console.error(err));
(async () => {
  const response = await fetch(uri, params);
  if (!response.ok) { // HTTP Status Code != 2xx
    console.error('Server Error');
  } else {
    const responseBody = await response.json();
    console.log('HTTP Response Body', responseBody);
  }
})();
async function AJAX() {
  const response = await fetch(uri, params);
  if (!response.ok) {
    throw new Error('Server Error');
  }
  return response.json();
}
function onSuccess(data) { console.log('HTTP Response Body', data); }
function onError(err) { console.error(err); }

AJAX().then(onSuccess).catch(onError);
function onDone(response) {
  console.log('HTTP Response Status Code', response.status);
  if (!response.ok) { throw new Error('Server Error'); }
  return response.json();
}

function onSuccess(data) {
  console.log('HTTP Response Body', data);
}

function onError(error) {
  console.error(error);
}

fetch(uri, params).then(onDone).then(onSuccess).catch(onError);
JQuery
$.ajax
const uri = 'https://example.com';
const jsonData = { foo: 'Hello world!' };
const params = {
  url: uri,
  method: 'POST',
  cache: false,
  crossDomain: true,
  dataType: 'json',
  contentType: 'application/json',
  headers: { 'Accept': 'application/json' },
  data: JSON.stringify(jsonData)
};
$.ajax(params)
  .done(data => console.log('Response OK', data) )
  .fail(err => console.error('Network error', err.statusText) )
  .always(() => console.log('Request completed') );
Multiple requests synchronization
var req1 = $.ajax(params).done(onDone).fail(onFail);
var req2 = $.ajax(params).done(onDone).fail(onFail);
$.when(req1, req2).then(() => console.log('Requests completed'));

function onDone(data, textStatus, jqXHR) {
  console.log('HTTP Response Body', data);
}

function onFail(jqXHR, textStatus, errorThrown) {
  console.error('HTTP Request Method', this.type);
  console.error('HTTP Request URL', this.url);
  console.error('HTTP Request Content-Type', this.contentType);
  console.error('HTTP Respose Status Code', jqXHR.status);
  console.error('HTTP Respose Status Text', jqXHR.statusText);
  console.error('HTTP Respose Content-Type', jqXHR.getResponseHeader('Content-Type'));
  console.error('HTTP Respose Body', jqXHR.responseJSON);
}