Step by step explanation of the ES6 arrow function syntax.
#javascript#es6
// 1. We start here with the standard functionfunction(a+b){returna+b;}// 2. Drop the "function" and insert the "=>" after the arguments(a,b)=>{returna+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
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.
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.
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.
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.
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// ----------------------varchange=4;functioncalculate(){varbase=50;returnbase+change;// change variable doesn't exist in the calculate function scope. }calculate();// Returns 54// EXAMPLE 2// Inner function closure// ----------------------functionouterFunction(outerVar){functioninnerFunction(innerVar){returnouterVar+' from '+innerVar;}returninnerFunction;}varsaySomething=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 scopesaySomething('closure');// In the second run the argument will passed as the innerVar.
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
varel=document.createElement("p");el.innerHTML="Content of the new element";document.body.appendChild(el);
A simple example of a time counter. Counts down days, hours, minutes and seconds to a set date.
#javascript#date
<script>(function(){// Targeted datevarcountDownDate=newDate("Jun 2, 2025 23:59:59").getTime();// Update the count down every 1 secondvarx=setInterval(function(){// Get current date and timevarnow=newDate().getTime();// Time to the datevartimeToDate=countDownDate-now;// Time calculations for days, hours, minutes and secondsvardays=Math.floor(timeToDate/(1000*60*60*24));varhours=Math.floor((timeToDate%(1000*60*60*24))/(1000*60*60));varminutes=Math.floor((timeToDate%(1000*60*60))/(1000*60));varseconds=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>
<divid="counter"></div>
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.
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
functionbuildElement({color,shape,size=20,callback}){// Do something...}varel1=buildElement({color,shape,size:10,callback:function(){}});varel2=buildElement({color,size});
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 propertiesdocument.location.hash// returns a string marked with the # sign document.location.hostname// returns the base domain namedocument.location.href// returns a full url including query string and hashdocument.location.pathname// returns the the page or a subfolderdocument.location.search// returns a string marked with the ? sign document.location.reload()// forces page reloaddocument.location.assign('new-url')// redirects to a new url and saves it to the browsing history
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 paddingelement.clientHeight;element.clientWidth;// Element sizes including padding, margin and borderelement.offsetHeight;element.offsetWidth;
Extend an existing ES6 class. super() references the parent class constructor.
#javascript#es6
classParentClass{constructor(){// Constructor code}foo(){// Foo function code}}// Extend ParentClassclassChildClassextendsParentClass{constructor(){// Super references the ParentClass constructor super()}// Add here methods for the ChildClass}
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.
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.
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 variablevarel=document.getElementById("element").innerHTML;// Set the inner HTML valuedocument.getElementById("another-element").innerHTML="New content added";
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 variablevarel=document.getElementById("element").innerText;// Set the inner text valuedocument.getElementById("another-element").innerText="New text";
// Number of items to selectnumberOfItems=100;// Create a new array with last N itemsletselectedArray=originalArray.slice(Math.max(originalArray.length-numberOfItems,1));
window.localStorage// returns Storage object window.localStorage.setItem('counter',1)// set key value pairwindow.localStorage.getItem('counter')// returns "1"window.localStorage.clear// clears all data in the Storage object
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 secondsfunctionperformance(start,end){return(end-start)/1000+"s";}// New object to store calculated and human-readable resultslatency={}// CALCULATE THE RESULTS HERE:// Total Page Load Timelatency.totalPageLoadTime=performance(timings.navigationStart,timings.loadEventEnd);// DOM Startlatency.domStart=performance(timings.navigationStart,timings.responseEnd);// DOM Interactivelatency.domInteractive=performance(timings.navigationStart,timings.domInteractive);// DOM Content Loadedlatency.domContentLoaded=performance(timings.navigationStart,timings.domContentLoadedEventEnd);// DOM Completelatency.domComplete=performance(timings.navigationStart,timings.domComplete);// Page Render Timelatency.pageRenderTime=performance(timings.domLoading,timings.domComplete);// Draw results table in the consoleconsole.table(latency);})();
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 objectvarComponent={// Set required variables hereelement:document.querySelector('.component'),// Add your methodscomponentMethod:function(){// Do something},// Initialization methodinit:function(){// Set the requirements that need to be met to execute the methodif(Component.element){this.componentMethod();}}};// Finally check for elements and initialize the objectif(Component.element){Component.init();}
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 promisevarpromise=newPromise(function(resolve,reject){if(...){resolve("Promise resolved!");}else{reject(Error("Oh no!"));}});// Then you can use the promisepromise.then(function(result){console.log(result);// "Promise resolved!"},function(err){console.log(err);// Error: "Oh no!"});
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()
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.
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 cookiedocument.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
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.
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
varcolors=["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 arraycolors.splice(1,0,"purple","yellow");// colors["red", "purple", "yellow", "blue"]
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}
Ternary operator evaluates first parameter followed by two values. First value is returned when the condition is true otherwise the second value is returned.
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
leta="5"// Use by defaultconstday="Monday"// Assume that the value doesn't changevartheme="sunrise"// Mainly used for global variables
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.
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 panelswindow.innerHeight;window.innerWidth;// window size INCLUDING panelswindow.outerHeight;window.outerWidth;