#javascript#event

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

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

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

var itemsArray = document.querySelectorAll('.item');

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

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

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

Step by step explanation of the ES6 arrow function syntax.

// 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
#javascript#es6

Example of the ES6 class declaration.

class Shape {
    constructor(){
        // Constructor code
    }

    color(){
        // Define shape color
    }

    size(){
        // Define shape size
    }
}

var newShape = new Shape();
newShape.color();
copy
#javascript#class#list

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

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

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.

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

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.

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

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

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

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.

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

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.

// 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
#javascript#console

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

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

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

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

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

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

Outputs an object to console in format of a table.

console.table(Object);
copy
#javascript

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.

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

A simple example of a time counter. Counts down days, hours, minutes and seconds to a set 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
#javascript#loop

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

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

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

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

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

var dayObject = {
    morning: "Good morning",
    afternoon: "Hello there" 
};

var { morning } = dayObject;
copy
#javascript#object#es6

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.

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

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

Use object destructuring to pass arguments in the function parameters.

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
#javascript#devtools

Copies referenced object to the clipboard.

copy(Object)

// i.e. copy(dataLayer)
copy
#javascript#document

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.

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
#javascript#url

Gets the referrer url of the page.

document.referrer
copy
#javascript#element

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.

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

// Element sizes including padding, margin and border
element.offsetHeight;
element.offsetWidth;
copy
#javascript#es6#modules

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

// 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
#javascript#es6

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

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

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

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
#javascript#filter#es6

Filter out values from a set of data.

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

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

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

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

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

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.

var arr = [blue, green, yellow]

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

Loops through an array of items.

var values = [{number:'34'}, {number:'4'}, {number:'67'}];

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

Get a value of the selected data attribute.

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

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.

var readCookie = document.cookie;
copy
#javascript

Get the scroll position from the top of the window.

window.scrollY
copy
#javascript#helper#function#class

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.

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

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

// 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
#javascript

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

// 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
#javascript#array

Select last n items from 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
#javascript#storage

Used for storing key value pairs in the browser and can be accessed through a window property.

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
#javascript#es6

Performs an operation on each mapped value.

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

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

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

Returns the largest number from the supplied values.

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

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

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

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

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

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/

(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
#javascript#object#es6

Use destructuring to pass variables to an object.

var color = "red";
var shape = "square";

buildObject({ color, shape });
copy
#javascript#object

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.

// 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
#javascript

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

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

Runs a function when an object is clicked.

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

Gets domain name of the page.

document.domain
copy
#javascript

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

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

Converts a string to an integer.

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

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.

// 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
#javascript#array

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

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

Returns the first descendant of the queried element.

object.querySelector();
copy
#javascript#select

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()

object.querySelectorAll();
copy
#javascript#dom

This function removes selected element from DOM.

element.remove();
copy
#javascript

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

function update() {
    
    // Animate elements here

    window.requestAnimationFrame(update);
  }
}

window.requestAnimationFrame(update);
copy
#javascript

Return statement finishes function execution and can output a value.

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

Selects body element.

document.body
copy
#javascript#select

Select all document elements with a given data attribute.

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

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

element.nextElementSibling
copy
#javascript#select

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

element.nextSibling
copy
#javascript#select

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

element.parentElement
copy
#javascript#select

Selects the previous sibling of the element.

element.previousSibling
copy
#javascript

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

(function(){

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

Set the value of the targeted data attribute.

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

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

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
#javascript#cookie

Set a cookie with one year expiry date.

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

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.

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

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.

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
#javascript#string#es6

Check if the string ends with the given text.

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

Check if the string includes the given text.

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

Check if the string starts with the given text.

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

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

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
#javascript#conditional

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

// Structure 
// Condition ? True : False

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

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

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

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

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

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

navigator.userAgent
copy
#javascript#es6

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.

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
#javascript#loop#array

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

var width = 1;
var limit = 200;

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

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.

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

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.

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

// window size INCLUDING panels
window.outerHeight; 
window.outerWidth;
copy
Sitemap Git repository