Adds an event listener to an object. Once the event in triggered function passed as the second argument is fired.

#javascript#event
object.addEventListener("click", function(){
    // do something
});
copy

Example of looping through an array of objects and adding click event listeners.

#javascript#event#loop
var itemsArray = document.querySelectorAll('.item');

itemsArray.forEach(function(item){
    item.addEventListener('click', function(){
        console.log(item);
    });
});
copy

ES6 arrow function syntax. In one line arrow functions the function output is automatically returned.

#javascript#es6
(a, b) => { a + b };
copy

Step by step explanation of the ES6 arrow function syntax.

#javascript#es6
// 1. We start here with the standard function
function(a + b){ 
    return a + b;
}

// 2. Drop the "function" and insert the "=>" after the arguments
(a, b) => { 
    return a + b
};

// 3. Move the function body to a single line. One line arrow functions will automatically return the output. This allows you to drop the "return", curly brackets and semicolon.
(a, b) => a + b
copy

Async attribute can be added to the script tag loading an external file. Script will be loaded asynchronously and executed in the background. Note, this can cause script executing before page has been completely parsed so make sure you account for that in your code.

#javascript#performance
<script src="/path/to/the/script.js" async></script>
copy

Example of the ES6 class declaration.

#javascript#es6
class Shape {
    constructor(){
        // Constructor code
    }

    color(){
        // Define shape color
    }

    size(){
        // Define shape size
    }
}

var newShape = new Shape();
newShape.color();
copy

Append a style class to the selected element. Use only the class name without the dot notation. 'add' method belongs to the 'classList' property.

#javascript#class#list
element.classList.add('new-class-name');
copy

Check if the given class exists in the element's class list. Returns True if the class exists. Use only the class name without the dot notation. 'contains' method belongs to the 'classList' property.

#javascript#class#list
element.classList.contains('class-name');
copy

This method lets you return a class name assigned to a given index value in the class list. Useful for looping through the 'classList' items. 'item' method belongs to the 'classList' property.

#javascript#class#list
element.classList.item(0);
copy

Use this method to remove one or more classes from the class list. 'remove' method belongs to the 'classList' property.

#javascript#class#list
element.classList.remove('class-name', 'some-other-class');
copy

This method lets you toggle a class in the class list property. It will also return True if the class has been added and False when the class was toggled off. Use only the class name without the dot notation. 'toggle' method belongs to the 'classList' property.

#javascript#class#list
element.classList.toggle('class-name');
copy

Closures are functions using externally declared variables in their own scope. Useful when debugging Closures - console.dir method allows you to preview a function scope.

#javascript
// EXAMPLE 1
// Outer scope variable closure
// ----------------------
var change = 4;

function calculate(){
    var base = 50;
    return base + change; // change variable doesn't exist in the calculate function scope. 
}

calculate(); // Returns 54


// EXAMPLE 2
// Inner function closure
// ----------------------

function outerFunction(outerVar){

    function innerFunction(innerVar){
        return outerVar + ' from ' + innerVar;
    }

    return innerFunction;
}

var saySomething = outerFunction('Hello'); // 'Hello' is being passed as the outerVar argument. 

console.log(saySomething()); // Logs 'Hello from undefined' as we haven't set the innerVar yet.
console.dir(saySomething); // console.dir() function allows you to preview the current state of the scope

saySomething('closure'); // In the second run the argument will passed as the innerVar.
copy

Console assert takes two attributes. If the first attribute is evaluated as false it will log a message passed as the second attribute.

#javascript#console
console.assert(false, "Message to log.");
copy

Prints a detailed view of DOM JS object to the console.

#javascript#console
console.dir(Object);
copy

Returns value to the console. "\n" will start a new line

#javascript#console
console.log("What is 23 * 65 = " + 23 * 65);
copy

Outputs an object to console in format of a table.

#javascript#console
console.table(Object);
copy

Create and append HTML element. In the example an empty paragraph is being created using createElement property. Then the content is added through innerHTML property and finally the new element is appended to the body.

#javascript
var el = document.createElement("p");
el.innerHTML = "Content of the new element";
document.body.appendChild(el);
copy

A simple example of a time counter. Counts down days, hours, minutes and seconds to a set date.

#javascript#date
<script>
(function(){
    // Targeted date
    var countDownDate = new Date("Jun 2, 2025 23:59:59").getTime();
    // Update the count down every 1 second
    var x = setInterval(function() {
        // Get current date and time
        var now = new Date().getTime();
        // Time to the date
        var timeToDate = countDownDate - now;
        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(timeToDate / (1000 * 60 * 60 * 24));
        var hours = Math.floor((timeToDate % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((timeToDate % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((timeToDate % (1000 * 60)) / 1000);
        // Display the result in the element with id="counter"
        document.getElementById("counter").innerHTML = days + "<small>d</small> " + hours + "<small>h</small> " + minutes + "<small>m</small> " + seconds + "<small>s</small> ";
        // If the countdown is finished, display a message 
        if (timeToDate < 0) {
            clearInterval(x);
            document.getElementById("counter").innerHTML = "Countdown finished";
        }
    }, 1000);

})();
</script>

<div id="counter"></div>
copy

Defer attribute can be added to the script tag loading an external file. This will defer execution of the file until the whole page is parsed. It's a common technique improving site performance by delaying potentially blocking assets.

#javascript#performance
<script src="/path/to/the/script.js" defer></script>
copy

Using setTimeout function this loop example lets you delay the iteration.

#javascript#loop
(function iterate(i) {          
    setTimeout(function () {   
       console.log(i);                     
       if (--i) iterate(i);      
    }, 200)
 })(10);
copy

To delete a cookie pass the name and a date set in the past.

#javascript#cookie
document.cookie = "cookieName=; expires=Sun, 15 Jun 2019 00:00:00 UTC; path=/"
copy

Use it to extract specific data from an object or an array.

#javascript#object#es6
var dayObject = {
    morning: "Good morning",
    afternoon: "Hello there" 
};

var { morning } = dayObject;
copy

It allows you to pass function arguments as an object. You can set default values for the arguments (see "size" argument) and it also allows for omitting arguments when calling a function rather than using null.

#javascript#object#es6
function buildElement({ color, shape, size = 20, callback }){
    // Do something...
}

var el1 = buildElement({ color, shape, size: 10, callback: function(){} });
var el2 = buildElement({ color, size });
copy

Use object destructuring to pass arguments in the function parameters.

#javascript#destructuring#es6
class Shape {
    createShape(options = {}) {
        const { x = 0, y = 0, w = 100, h = 100, c = '#FFF'} = options;
        console.log(x,y,w,h,c);
    }
}

const shape = new Shape();
shape.createShape({});
copy

Copies referenced object to the clipboard.

#javascript#devtools
copy(Object)

// i.e. copy(dataLayer)
copy

Document location gives you an access to an object containing useful information about the current URL and methods for updating and redirecting. Use the dot notation to access object properties and methods.

#javascript#document
document.location // returns a full list of methods and properties
document.location.hash // returns a string marked with the # sign 
document.location.hostname // returns the base domain name
document.location.href // returns a full url including query string and hash
document.location.pathname // returns the the page or a subfolder
document.location.search // returns a string marked with the ? sign 

document.location.reload() // forces page reload
document.location.assign('new-url') // redirects to a new url and saves it to the browsing history
copy

Gets the referrer url of the page.

#javascript#url
document.referrer
copy

You can use 'client' and 'offset' variants of width and height properties to get the dimensions of elements. The 'clientWidth' and 'clientHeight' properties capture element sizes including padding only. The 'offsetWidth' and 'offsetHeight' properties capture the full size of the element including padding, margin and border.

#javascript#element
// Element sizes including padding
element.clientHeight;
element.clientWidth;

// Element sizes including padding, margin and border
element.offsetHeight;
element.offsetWidth;
copy

This ES6 feature allows you to easily import and export whole modules or parts of them between javascript files.

#javascript#es6#modules
// file-one.js
    export function sendInfo(){
        // ...
    }

// file-two.js
    // import whole module
    import Comms from 'CommunicationModule'

    // or import individual methods using destructuring
    import { sendInfo } from './js/file-one.js'
copy

Also referred to as template strings. Allows for a simpler use of variables within blocks of text and multi lines.

#javascript#es6
let firstname = "John";
let lastname = "Smith"
console.log(`Hi my name is:
${firstname} ${lastname}`);
// Hi my name is:
// John Smith
copy

Extend an existing ES6 class. super() references the parent class constructor.

#javascript#es6
class ParentClass{    
    constructor(){
        // Constructor code
    }
    foo(){
        // Foo function code
    }
}

// Extend ParentClass
class ChildClass extends ParentClass{
    constructor(){
        // Super references the ParentClass constructor 
        super()
    }
    // Add here methods for the ChildClass
} 
copy

Filter out values from a set of data.

#javascript#filter#es6
let values = [23, 4, 345, 6, 343, 22];
values.filter(number => number < 23);
// This returns [4, 6, 22]
copy

Finds and selects the closest parent element to the selected one. It will check all elements all the way to the document root.

#javascript#select
element.closest('.nav');
copy

Loop though the code number of times defined in the "for" block.

#javascript#loop
for (var i = 0; i < 10; i++) {
    console.log("Value of i = " + i);
}
copy

Similar to for loop but you don't need to specify the number of iterations. The loop uses an iterator function built in to arrays.

#javascript#loop
var arr = [blue, green, yellow]

for (var color of arr) {
    console.log("The color is " + color);
}
copy

Loops through an array of items.

#javascript#loop#array
var values = [{number:'34'}, {number:'4'}, {number:'67'}];

values.forEach(function(num){
    console.log(num.number); // 34, 4, 67
});
copy

Get a value of the selected data attribute.

#javascript#select#attribute
element.getAttribute('data-attribute');
copy

Read the cookie value by assigning it to a variable. This will return a string containing all the name value pairs set in a cookie.

#javascript#cookie
var readCookie = document.cookie;
copy

Use dataset property to return an object containing all data attributes set on the element. You can also get value of a particular data attribute by using dot notation and referencing the unique name part of the attribute.

#javascript#data#attribute
// <div data-color="red" data-shape="square" data-count="4"></div>

element.dataset // { color: "red", shape: "square", count: "4" }
element.dataset.count // "4"
copy

Get the scroll position from the top of the window.

#javascript
window.scrollY
copy

Use this helper function to check if the element has a given class. It uses a regular expression to match the queried class name. First attribute of the helper function takes the element name. Pass the name of the class you want to check as the second attribute.

#javascript#helper#function#class
function hasClass(element, class) {
    return !!element.className.match(new RegExp("(\\s|^)" + class + "(\\s|$)"));
}
copy

Inner HTML lets you get and set the content of selected element.

#javascript
// Get the inner HTML value of the selected element and assign it to a variable
var el = document.getElementById("element").innerHTML;

// Set the inner HTML value
document.getElementById("another-element").innerHTML = "New content added";
copy

Inner text lets you get and set the text of selected element.

#javascript
// Get the inner text value of the selected element and assign it to a variable
var el = document.getElementById("element").innerText;

// Set the inner text value
document.getElementById("another-element").innerText = "New text";
copy

Select last n items from array

#javascript#array
// Number of items to select
numberOfItems = 100;
// Create a new array with last N items
let selectedArray = originalArray.slice( Math.max( originalArray.length - numberOfItems, 1 ) );
copy

Used for storing key value pairs and can be accessed through the window object.

#javascript#storage
window.localStorage // returns Storage object 

window.localStorage.setItem('counter', 1) // set key value pair

window.localStorage.getItem('counter') // returns "1"

window.localStorage.clear // clears all data in the Storage object
copy

Remove an item from localStorage object.

#javascript#storage
localStorage.removeItem('counter');
copy

Performs an operation on each mapped value.

#javascript#es6
let values = [4, 54, 56, 23, 8, 54];
values.map(number => number * 2);
// This returns [8, 108, 112, 46, 16, 108]
copy

Math.floor() method takes a fraction as an argument and returns the largest integer equal or smaller than the original value.

#javascript#math
Math.floor( 1.75); //  Returns 1
copy

Returns the largest number from the supplied values.

#javascript#math
console.log(Math.max(1, 23, -2, 2));
copy

Math.round() method takes a single number as an argument and returns the closest integer.

#javascript#math
Math.round(0.9); // Returns 1
Math.round(1.49876); // Returns 1
Math.round(1.5); // Returns 2
copy

You can capture X and Y mouse position using clientY and clientX properties.

#javascript#mouse
window.addEventListener("mousemove", function(e){
    console.log("Mouse position: Y " + e.clientY, ", X " + e.clientY, );
});
copy

Navigation timing is part of the Performance API that lets you benchmark web applications. It allows to measure various points of page load, including the time it takes for the server to respond. In the attached example we are capturing total page load time, DOM start, DOM interactive, content loaded, DOM complete, and total page render time. These are just a few examples form the API. For the full explanation visit https://www.w3.org/TR/navigation-timing/

#javascript#performance
(function(){        
    timings = window.performance.timing;
    //  Get the time passed between two events in seconds
    function performance(start,end){
        return (end - start) / 1000 + "s";
    }    
    // New object to store calculated and human-readable results
    latency = {}
    // CALCULATE THE RESULTS HERE:
        // Total Page Load Time
        latency.totalPageLoadTime = performance(timings.navigationStart, timings.loadEventEnd);
        // DOM Start
        latency.domStart = performance(timings.navigationStart, timings.responseEnd);
        // DOM Interactive
        latency.domInteractive = performance(timings.navigationStart, timings.domInteractive);
        // DOM Content Loaded
        latency.domContentLoaded = performance(timings.navigationStart, timings.domContentLoadedEventEnd);
        // DOM Complete
        latency.domComplete = performance(timings.navigationStart, timings.domComplete);
        // Page Render Time
        latency.pageRenderTime = performance(timings.domLoading, timings.domComplete);
    // Draw results table in the console
    console.table(latency);
})();
copy

Use destructuring to pass variables to an object.

#javascript#object#es6
var color = "red";
var shape = "square";

buildObject({ color, shape });
copy

Object literal pattern, also known as modular pattern, is a way of organizing your javascript code. The biggest advantages of this approach is modularity, encapsulation and a clear, readable structure.

#javascript#object
// Declare an object
var Component = {

    // Set required variables here
    element : document.querySelector('.component'),

    // Add your methods
    componentMethod : function(){
        // Do something
    },

    // Initialization method
    init : function(){
        // Set the requirements that need to be met to execute the method
        if( Component.element ){
            this.componentMethod();
        }
    }

};

// Finally check for elements and initialize the object
if ( Component.element ){
    Component.init();
}
copy

Add event listeners for checking the network status. Capturing those events lets you handle offline and online status of the application.

#javascript
window.addEventListener('online', ()=> console.log("online"));
window.addEventListener('offline', ()=> console.log("offline"));
copy

Runs a function when an object is clicked.

#javascript#event
object.onclick = function(){
    console.log(this);
};
copy

Gets domain name of the page.

#javascript#url
document.domain
copy

Location is a property of the Window object and it allows to set a new page url effectively acting as a page redirect.

#javascript
window.location = "/new-page.html"
copy

Converts a string to an integer.

#javascript
var stringVal = "34"; // Returns "34"
parseInt(stringVal); // Returns 34
copy

The Promise object allows you to make an asynchronous call to another function. The 'resolve' function is called when the asynchronous call is successful otherwise it falls back to 'reject' function.

#javascript#es6
// Create promise
var promise = new Promise(function(resolve, reject) {
    if (...) {
        resolve("Promise resolved!");
    }
    else {
        reject(Error("Oh no!"));
    }
});

// Then you can use the promise
promise.then(
    function(result) {
        console.log(result); // "Promise resolved!"
    },
    function(err) {
        console.log(err); // Error: "Oh no!"
    }
);
copy

Use push method to append a new item to the end of an array.

#javascript#array
var colors = ["red","green","blue"];
colors.push("yellow");
// ["red","green","blue","yellow"]
copy

Returns the first descendant of the queried element.

#javascript#select
object.querySelector();
copy

Returns a list of nodes that are descendants of the queried element. To operate on the returned values you can loop through it using forEach() or convert the list to an array using Array.from()

#javascript#select
object.querySelectorAll();
copy

This function removes selected element from DOM.

#javascript#dom
element.remove();
copy

Request animation frame lets you line-up changes for the next window paint.

#javascript
function update() {
    
    // Animate elements here

    window.requestAnimationFrame(update);
  }
}

window.requestAnimationFrame(update);
copy

Return statement finishes function execution and can output a value.

#javascript
function foo(a, b){
    return a + b;
}
copy

Selects body element.

#javascript#select
document.body
copy

Select all document elements with a given data attribute.

#javascript#select
document.querySelectorAll('[data-attribute]');
copy

Selects the next sibling of the element. Returns null if no element is found.

#javascript#select
element.nextElementSibling
copy

Selects the next sibling of the element including text. Returns null if no element is found.

#javascript#select
element.nextSibling
copy

Selects the parent of the element. Returns null if no parent is found.

#javascript#select
element.parentElement
copy

Selects the previous sibling of the element.

#javascript#select
element.previousSibling
copy

Self invoking function lets you immediately execute code. Another benefit is scoping, so you are not risking cluttering the global object. It's also a good practice to check for the window object and other dependencies by passing them as arguments.

#javascript
(function(){

    // Place your code here
    
})(window) // Ensure that the window object is available before executing the code.
copy

Set the value of the targeted data attribute.

#javascript#select#attribute
element.setAttribute('attribute','value');
copy

Create cookie by passing a cookie name, value, expiry date and path to witch the cookie belongs.

#javascript#cookie
document.cookie = "simpleCookie=Cookie value"; // Simple cookie
document.cookie = "cookieName=Cookie value; expires=Sun, 15 Jun 2019 23:59:00 UTC; path=/javascript-cheatsheet" // Cookie with an expiry date and a path set
copy

Set a cookie with one year expiry date.

#javascript#cookie
document.cookie = `cookie_name=${cookie_value}; expires=${new Date(new Date().getTime()+1000*60*60*24*365).toGMTString()}; path=/`;
copy

Allows to run a function in regular intervals. The second argument takes the interval time in milliseconds. The example checks for the existence of the class before stopping the loop.

#javascript#loop
var checker = setInterval(function() {
    if (document.querySelector('.sc')) {
       console.log('Found it!');
       clearInterval(checker);
    }
 }, 100);
copy

Assigning array to Float64Array array type lets you correctly sort its numeric values.

let arrayToSort = new Float64Array([10, 23, 5, 456, 11, 1]);
sortedArray = arrayToSort.sort(); // returns [1, 5, 10, 11, 23, 456]
copy

Splice method lets you add and remove items from an array. I takes a minimum of two arguments, first one marks the index of the array item, second, is a number of items to be removes, set to 0 if no items are to be deleted. The following arguments are the new items to be added to the array. When taking out items from the array, splice will automatically return them.

#javascript#array
var colors = ["red","green","blue"];
// Select item with index 1 and remove 1 item. Returns removed color ["green"]
colors.splice(1, 1);

// Add more colors to the array
colors.splice(1, 0, "purple", "yellow"); // colors["red", "purple", "yellow", "blue"]
copy

Check if the string ends with the given text.

#javascript#string#es6
let title = 'Section introduction';
title.endsWith('duction') // Returns true
copy

Check if the string includes the given text.

#javascript#string#es6
let title = 'Section introduction';
title.includes('intro') // Returns true
copy

Check if the string starts with the given text.

#javascript#string#es6
let title = 'Section introduction';
title.startsWith('Section') // Returns true
title.startsWith('sec') // Returns false
title.startsWith('intro') // Returns false
copy

Runs through a set of cases and executes the code when the condition is met.

#javascript#conditional
switch(myVar){
    case "a" :
    // Execute some code if myVar equals "a"
    break;

    case "b" :
    case "c" :
    // Execute some code if myVar equals "b" or "c"
    break;

    default :
    // If all cases fail run this
}
copy

Ternary operator evaluates first parameter followed by two values. First value is returned when the condition is true otherwise the second value is returned.

#javascript#conditional
// Structure 
// Condition ? True : False

var hour = 14;
var day = (hour <= 12) ? "Morning" : "Afternoon";
console.log(day); // Afternoon
copy

toFixed() method takes a single integer as an argument determining how many decimal numbers should the original value be fixed to.

#javascript
(1.7549).toFixed(2); //  Returns 1.75
(1.7551).toFixed(2); //  Returns 1.76
copy

Try catch allows to run a block of code and capture any exceptions.

#javascript
try {
    // try some code here
} catch(error) {
    console.error(error);
}
copy

Returns user agent header identifying browser type, name and version.

#javascript#navigator
navigator.userAgent
copy

Es6 introduced 'let' and 'const' to register variables. By default use 'let' to indicate that the variable can mutate or be reassigned, otherwise use 'const'. The use of 'var' has been limited to use in the global scope.

#javascript#es6
let a = "5" // Use by default
const day = "Monday" // Assume that the value doesn't change
var theme = "sunrise" // Mainly used for global variables
copy

Execute the code inside the loop as long as the statement is true.

#javascript#loop#array
var width = 1;
var limit = 200;

while (width <= limit){
    console.log(width);
    width++;
}
copy

Window on load property will run the handler function when the load event is fired. The event is raised when the document, including all objects and elements, has fully loaded.

#javascript#window
window.onload = function() {
    // Run your code here
};
copy

You can use 'inner' and 'outer' variants of width and height properties to get the dimensions of the window element. The 'innerWidth' and 'innerHeight' properties capture window sizes excluding scrollbars or toolbars. On the other hand 'outerWidth' and 'outerHeight' properties capture the full area of the browser window including all the panels and scrollbars.

#javascript#window
// window size EXCLUDING panels
window.innerHeight;
window.innerWidth;

// window size INCLUDING panels
window.outerHeight; 
window.outerWidth;
copy