With the following useful JavaScript snippets, we collected some popular actions performed in JavaScript ranging from creating a promise, popular lodash functions in native JavaScript, DOM manipulation, etc.
These JavaScript code snippets may be helpful to speed up your workflows while developing in your IDE or other text editors. You can save any of these JavaScript snippet examples to your personal Pieces micro repository, categorize and share them instantly.
How to create a promise function in Javascript
Tags: javascript, promise
Create a Javascript promise to handle asynchronous events.
new Promise((resolve, reject) => {
// asynchronous operation
// then in case of success
resolve();
// or
reject("failure reason");
});
Related links:
- Understanding JavaScript promises
- How to use a promise in JavaScript
- JavaScript promise examples
Count number of occurrences in array with JavaScript
Tags: javascript, count
Use this JavaScript snippet to count the occurrences of a value in an array.
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
Related links:
- JavaScript code snippet - array prototype reduce
- JavaScript array reduce
How to use defer in Javascript
Tags: javascript, defer
JavaScript snippet that delays execution of function until the current call stack is cleared.
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
Related links:
- SetTimeOut in Javascript
- Window SetTimeOut Method
How to find difference between arrays in JavaScript
Tags: javascript, difference
Finds the difference between two arrays.
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
difference([1, 2, 3], [1, 2, 4]); // [3]
Related links:
- Set object in JavaScript
- JavaScript code snippet - Array prototype filter
- JavaScript Snippet - Map Prototype Has
How to remove duplicates from an Array in JavaScript
Tags: javascript, array, set, duplicate
Remove duplicates from an array using a Set.
const unique = [...new Set(array)];
Related links:
- JavaScript snippets: remove duplicates from an array
- JavaScript code to remove duplicates from an array
- Remove duplicate values from a JavaScript array
How to find object key in JavaScript
Tags: javascript, object, key
Returns the first key that satisfies a given function.
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
Related links:
- Get an object key by its value using JavaScript
- JavaScript fundamentals
How to flatten an array in Javascript
Tags: javascript, array, flatten
Flattens a deeply nested array up until the specified depth.
const flatten = arr => arr.flat(Infinity);
Related links:
- How to flatten a nested JavaScript array
- JavaScript SnippetL: Flatten an array
JavaScript array Intersection
Tags: javascript, array, common elements
Gets an array with elements that are included in two other arrays.
const intersection = (a, b) => {
const s = new Set(b);
return a.filter(x => s.has(x));
};
Related links:
- Find intersection of two arrays in JavaScript
- JavaScript Snippet - Map Prototype Has
- Intersection example in JavaScript
How to get URL path in JavaScript
Tags: javascript, url
Gets the url path for a webpage using javascript.
const newURL = `${window.location.protocol}//${window.location.host}/${window.location.pathname}${window.location.search}`
Related links:
- Useful JavaScript Snippet - Get portion of URL path
- JavaScript Window Location
How to remove HTML tags from strings in JavaScript
Tags: javascript, html
This JavaScript removes html tags from strings.
const strippedString = originalString.replace(/(<([^>]+)>)/gi, "");
Related links:
- How to strip HTML tags from string in JavaScript
- Strip HTML from text JavaScript
- Strip HTML tags in JavaScript
Array to HTML list JavaScript code snippet
Tags: javascript, html
Converts the given array elements into <li> tags and appends them to the list of the given id.
const arrayToHTMLList = (arr, listID) =>
document.querySelector(`#${listID}`).innerHTML += arr
.map(item => `${item}`)
.join('');
Related links:
- How to display a JavaScript array in a HTML list
Check if element has a class in JavaScript
Tags: javascript, class, element
This Javascript checks whether an element has a class.
const hasClass = (el, className) => el.classList.contains(className);
Related links:
- Check if an element contains a class using JavaScript
- JavaScript has class example
How to get current time in JavaScript
Tags: javascript, date, time
Get the current date and time.
const date = new Date()
const currentTime =
`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
Related links:
- How to get current date and time in JavaScript
- How to get current time and date in JavaScript
- Get current time in JavaScript example
Check if JSON is valid using JavaScript
Tags: javascript, json
Checks whether a string is valid JSON.
const isValidJSON = str => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
Related links:
- How to Check if a string is JSON in JavaScript
- How to check if a String is a valid JSON string
JavaScript delay async function
Tags: javascript, timeout, async
Delays the execution of an asynchronous function by putting it into sleep.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
Related links:
- Delay, sleep, pause, and wait in JavaScript
- Async function - Javascript snippets
How to add multiple classes in JavaScript
Tags: javascript, class
Adds multiple classes to the selected element.
element.classList.add("active", "highlighted");
Related links:
- Add and remove multiple classes to element in JavaScript
- Element Classlist - JavaScript
How to use Promise.all in JavaScript
Tags: javascript, promise
Aggregates results from an array of promises as an input and gets resolved when all the promises get resolved or any of them gets rejected.
Promise.all([ promise_1, promise_2 ]).then((values) => {
// all input Promises resolved
}).catch((reason) => {
// one of input Promises rejected
});
Related links:
- All you need to know about promise.all
- JavaScript promise all snippets
Want to use these JavaScript snippets in your IDE? Download our JetBrains plugin or VS Code extension to improve your developer productivity wherever you code.
Let us know what you think! Would you like to see other useful JavaScript snippets not listed on this page? Suggest a collection you'd like to see to help other developers speed up their workflows.