JavaScript

We have the most popular JavaScript snippets, ranging popular lodash functions to DOM manipulation. Add these JavaScript code snippets to Pieces.

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.

Tags: javascript, promise

How to create a promise function in Javascript

Create a Javascript promise to handle asynchronous events.

new Promise((resolve, reject) => {
  // asynchronous operation

  // then in case of success
  resolve();
  // or
  reject("failure reason");
});

Tags: javascript, count

Count number of occurrences in array with JavaScript

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

Tags: javascript, defer

How to use defer in Javascript

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'

Tags: javascript, difference

How to find difference between arrays in JavaScript

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]

Tags: javascript, array, set, duplicate

How to remove duplicates from an Array in JavaScript

Remove duplicates from an array using a Set.

const unique = [...new Set(array)]

Tags: javascript, object, key

How to find object key in JavaScript

Returns the first key that satisfies a given function.

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));

Tags: javascript, array, flatten

How to flatten an array in Javascript

Flattens a deeply nested array up until the specified depth.

const flatten = arr => arr.flat(Infinity);

Tags: javascript, array, common elements

JavaScript array Intersection

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));
};

Tags: javascript, url

How to get URL path in JavaScript

Gets the url path for a webpage using javascript.

const newURL = `${window.location.protocol}//${window.location.host}/${window.location.pathname}${window.location.search}`

Tags: javascript, html

How to remove HTML tags from strings in JavaScript

This JavaScript removes html tags from strings.

const strippedString = originalString.replace(/(<([^>]+)>)/gi, "");

Tags: javascript, html

Array to HTML list JavaScript code snippet

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

Tags: javascript, class, element

Check if element has a class in JavaScript

This Javascript checks whether an element has a class.

const hasClass = (el, className) => el.classList.contains(className);

Tags: javascript, date, time

How to get current time in JavaScript

Get the current date and time.

const date = new Date()
const currentTime = 
   `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`

Tags: javascript, json

Check if JSON is valid using JavaScript

Checks whether a string is valid JSON.

const isValidJSON = str => {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }

	return true;
};

Tags: javascript, timeout, async

JavaScript delay async function

Delays the execution of an asynchronous function by putting it into sleep.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

Tags: javascript, class

How to add multiple classes in JavaScript

Adds multiple classes to the selected element.

element.classList.add("active", "highlighted");

Tags: javascript, promise

How to use Promise.all in JavaScript

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
});

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.

150,000+ Installs

Want to use these JavaScript code snippets in your IDE?

Install one of our IDE integrations to 10x your productivity during your next coding project.