Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Vanilla JavaScript Quick Reference / Cheatsheet

Vanilla JavaScript Quick Reference / Cheatsheet

Just migrated it from to markdown. Credit goes to David Conner.

Working with DOM Working with JS Working With Functions
Accessing Dom Elements Add/Remove Array Item Add Default Arguments to Function
Grab Children/Parent Node(s) Add/Remove Object Properties Throttle/Debounce Functions
Create DOM Elements Conditionals
Add Elements to the DOM Loops
Add/Remove/Toggle/Check Classes Events
Type Checking

Accessing Dom Elements

// Returns a reference to the element by its ID.

// Returns an array-like object of all child elements which have all of the given class names.

// Returns an HTMLCollection of elements with the given tag name.

// Returns the first element within the document that matches the specified group of selectors.

// Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes)
// that match the specified group of selectors.
document.querySelectorAll('div.note, div.alert');

Grab Children/Parent Node(s)

// Get child nodes
var stored = document.getElementById('someid');
var children = stored.childNodes;

// Get parent node
var parental = children.parentNode;

Create New DOM Elements

// create new elments
var newHeading = document.createElement('h1');
var newParagraph = document.createElement('p');

// create text nodes for new elements
var h1Text= document.createTextNode('This is a nice header text!');
var pText= document.createTextNode('This is a nice paragraph text!');

// attach new text nodes to new elements

// elements are now created and ready to be added to the DOM.

Add Elements to the DOM

// grab element on page you want to add stuff to
var firstHeading = document.getElementById('firstHeading');

// add both new elements to the page as children to the element we stored in firstHeading.

// can also insert before like so

// get parent node of firstHeading
var parent = firstHeading.parentNode;

// insert newHeading before FirstHeading
parent.insertBefore(newHeading, firstHeading);

Add Elements to the DOM cont.

Suppose you have the following HTML:

<div id='box1'>
  <p>Some example text</p>
<div id='box2'>
  <p>Some example text</p>

You can insert another snippet of HTML between #box1 and #box2:

var box2 = document.getElementById('box2');
box2.insertAdjacentHTML('beforebegin', '<div><p>This gets inserted.</p></div>');

// beforebegin - The HTML would be placed immediately before the element, as a sibling.
// afterbegin - The HTML would be placed inside the element, before its first child.
// beforeend - The HTML would be placed inside the element, after its last child.
// afterend - The HTML would be placed immediately after the element, as a sibling.

Add/Remove/Toggle/Check Classes

// grab element on page you want to use
var firstHeading = document.getElementById('firstHeading');

// will remove foo if it is a class of firstHeading

// will add the class 'anotherClass' if one does not already exist

// add or remove multiple classes
firstHeading.classList.add('foo', 'bar');
firstHeading.classList.remove('foo', 'bar');

// if visible class is set remove it, otherwise add it

// will return true if it has class of 'foo' or false if it does not

Add/Remove Array Item

// create an empty array
var myArray = [];

// create array with items. Can store any type
var myOtherArray = [myArray, true, 'a random string'];

// call specific value in an array
// will return myArray

// change value for this item
myOtherArray[0] = false;
// will now return false

// add to end of array
myOtherArray[myOtherArray.length] = 'new stuff';
// will return the new item 'new stuff'

// or you can use push()
myOtherArray.push('new stuff');
// will return new length of array

// you can remove this last item by using pop()
// will return the last item of the array and will have removed it from myOtherArray

// shift and unshift will do the same for the begging of the Array
// will remove and return first item of array

// this will add 1 and 2 to beginning of array and return new length

// you can use delete keyword but turn value to undefine and not shorten length. so we use splice()
myOtherArray.splice(2, 1);
// this will remove and return  the third item only.
// first arg is where to start and second is how many things to splice. this example is 1.

Add/Remove Object Properties

// create an object
var newObject = {};

// add a property to object
newObject.newPropName = 'super slick';

// or other syntax
newObject['other new prop name'] = 'mildly slick';

// Now newObject.newPropName will return 'super slick'

// now to delete
delete newObject.newPropName;


// If Else statements
var a = 1;
var b = 2;

if (a < b) {
  console.log('the if is true!');
} else {
  console.log('the if is false!');

// Multi If Else statements
var a = 1;
var b = 2;
var c = 3;

if (a > b) {
  console.log('a is bigger than b');
} else if (a > c) {
  console.log('but a is bigger than c');
} else {
  console.log('a is the smallest');

// Ternary operators. same as if else
var a = 1;
var b = 2;

a === b ? console.log('The statement is true') : console.log('The statement is false');

// switch statements
var a = 4;
switch (a) {
  case 'Oranges':
    console.log('Orange? really?');
  case 1:
    console.log('a is equal to 1.');
  case 2:
    console.log('a is equal to 2.');
  case 3:
    console.log('a is equal to 3.');
  case 4:
    console.log('a is equal to 4.');
    console.log('I run if no one else is true.');


// while loop
var i = 0;
while (i < 10) {
  i += 1

// do while loop
var i = 0;
do {
  i += 1
} while (i < 10)

// for loop
for (var i = 0; i < 10; i++) {

// for in statments
var obj = {a:1, b:2, c:3};

for (var prop in obj) {
  // check if property is inherited or not
  if (obj.hasOwnProperty(prop)) {
    console.log('obj.' + prop + ' = ' + obj[prop]);

Events (MDN Event reference)

var newElement = document.getElementsByTagName('h1');

newElement.onclick = function() {

var logEventType = function(e) {
    console.log('event type:', e.type);

newElement.addEventListener('focus', logEventType, false);
newElement.removeEventListener('focus', logEventType, false);

window.onload = function() {
  console.log('Im loaded');


function simpleMessage() {
  alert('This is just a simple alert');

// set time out
window.setTimeout(simpleMessage, 5000);

// if you wanted to clear the timer.
var timer = window.setTimeout(simpleMessage, 5000);

// set interval. will repeat every  5000ms
window.setInterval(simpleMessage, 5000);

// if you wanted to clear the intervals.

var intervalHandler = window.setInterval(simpleMessage, 5000);

Type Checking

var myNumber = 1;
var myString = 'some Text';
var bools = true;
var myArray = [];
var myObj = {};
var notNumber = NaN;
var nullified = null;
var undef;

typeof myNumber;
// returns 'number'

typeof myString;
// returns 'string'

typeof bools;
// returns 'boolean'

typeof myArray;
// returns 'object'.

// Not super helpful so must check if it has length property to see if it is an array.
typeof myArray === 'object' && myArray.hasOwnProperty('length');
// returns true

typeof myObj;
// returns 'object'. Must do the same test as above but expect false back from check.

typeof notNumber;
// returns 'number'. this is confusing but returns this as NaN is part of the global Number object.

// must check if isNaN()
typeof notNumber === 'number' && isNaN(notNumber);
// returns true if type of is 'number' and is still NaN

typeof undef;
// returns 'undefined'

undef === undefined && typeof undef === 'undefined';
// returns 'true'

notDeclared === undefined;
// -> Uncaught ReferenceError: notDeclared is not defined

Add default arguments to a function

var myFunc = function (arg1='default argument one', arg2='default argument two') {
  console.log(arg1 + " & " + arg2);

myFunc(undefined, 'and a new value'); // logs 'default argument one & and a new value'

Throttle or Debounce Functions Calls

var helpers = {
   * debouncing, executes the function if there was no new event in $wait milliseconds
   * @param func
   * @param wait
   * @param scope
   * @returns {Function}
  debounce: function(func, wait, scope) {
    var timeout;
    return function() {
      var context = scope || this, args = arguments;
      var later = function() {
        timeout = null;
        func.apply(context, args);
      timeout = setTimeout(later, wait);

   * In case of a "storm of events", this executes once every $threshold
   * @param fn
   * @param threshold
   * @param scope
   * @returns {Function}
  throttle: function(fn, threshold, scope) {
    threshold || (threshold = 250);
    var last, deferTimer;

    return function() {
      var context = scope || this;
      var now = +new Date, args = arguments;

      if (last && now < last + threshold) {
        // Hold on to it
        deferTimer = setTimeout(function() {
          last = now;
          fn.apply(context, args);
        }, threshold);
      } else {
        last = now;
        fn.apply(context, args);

var resizeHandler = function(){
  console.log('do stuff');

// Debounce by waiting 0.25s (250ms) with "this" context
window.addEventListener('resize', helpers.debounce(resizeHandler, 250, this));
Copy link

dagoss commented Sep 13, 2017

Great reference. Maybe add for ... of to the loops section.
- no es6 here

Copy link

angelsantosa commented Dec 2, 2017

default args to function can be like this too

var myFunction = function (arg1="default argument one", arg2="default argument two";) {
  console.log(arg1 + " & " + arg2);

- thanks, updated

Copy link

johnmilner commented Jan 9, 2018

great! thanks for this!

Copy link

inawrath commented Jan 26, 2018

I change typeof myArray === 'object' && myArray.hasOwnProperty('length'); by Array.isArray(myArray)
the rest is perfect 😃

Copy link

yogicat commented Feb 25, 2018

thanks for the gist! really useful stuff!

Copy link

Ya-Za commented Aug 1, 2018

Good job :-)
@kareraisu, simpler general ways for type checking:

  • obj instance of Tyep


[] === 'Array' // true
[] instanceof Array // true

@thegitfather, More readble way to loop through the object properties:

for (const key of Object.keys(obj)) {

Copy link

jsayev commented Oct 5, 2018

thanks for sharing...

Copy link

fires3as0n commented Oct 8, 2018

I was so desperate, that neither MDN nor W3Schools has anything like this, that was going to make my own, then I've found this reference.
You saved me and other people so much time, you literally need a medal for this, lots and lots of thanks!

Copy link

gioragutt commented Dec 31, 2018

I'd add a couple of notes regarding:

  • Object.keys
  • Object.values
  • Object.entries
  • Array#filter
  • Array#map
  • Array#reduce

This cheatsheet is amazing! It'd be amazing if it would contain newer features for new people to learn!

Copy link

mthurmond commented Feb 10, 2019

Very helpful, thanks

Copy link

anshulabes commented Jul 10, 2019

Hey folks, what is the alternate for .stop() fuction in JQlite? Its saying "Property 'stop' does not exist on type 'JQLite'"

Copy link

hidaytrahman commented Oct 21, 2019

Thanks for your moments :)

Copy link

dekadentno commented Jan 22, 2020

Thank you for your time to make this marvelous gist.
Do you (or anyone) know if maybe something similar and nice as this exists for python?

Copy link

reMRKableDev commented Jan 22, 2020

This is fantastic, thanks!

Copy link

heytulsiprasad commented Mar 4, 2020

Yo devs out there, is there any level to express how much thankful I am to one who made this? Thanks man!

Copy link

solocreativeone commented Mar 13, 2020

Thanks, this is helpful, I appreciate it.

Copy link

jeje16 commented Jul 16, 2020

Thanks a lot.

Copy link

michellebannon commented Jan 2, 2021

This is great! Thank you.

Copy link

ogorei commented Jan 6, 2021

thank you!!

Copy link

edithpenha20 commented Jan 30, 2021

Thank you!

Copy link

MeenakshiSundaram-MS commented Jun 12, 2021

Thanks for this awesome resource.

Copy link

decodedmrq commented Jun 17, 2021

Thanks for sharing.

Copy link

shourov-rahman commented Mar 21, 2022

This is my go to checklist when I work with DOM .

Copy link

frahmanf commented Apr 5, 2022

Great work!

Copy link

dahoumanekhalil commented Apr 16, 2022

aww thank you so much for that work its a helpful

Copy link

obrianthe1st commented May 11, 2022

I love this, thank you.

Copy link

tanvirsp commented Jun 4, 2022

Very helpfull. thanks

Copy link

j-masci commented Aug 22, 2022

How about some element and window scroll top/bottom positions, etc. ?

Copy link

TriOptCorp commented Aug 25, 2022

Is there a way to get this beautiful cheat sheet as a pdf formatted just like the original post is?
Please advise. Thank you.

Copy link

coder-ralph commented Dec 2, 2022

A very useful resource. Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment