JavaScript Snippets

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

Add 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.

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:

  1. Understanding JavaScript promises
  2. How to use a promise in JavaScript
  3. 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:

  1. JavaScript code snippet - array prototype reduce
  2. 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:

  1. SetTimeOut in Javascript
  2. 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:

  1. Set object in JavaScript
  2. JavaScript code snippet - Array prototype filter
  3. 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:

  1. JavaScript snippets: remove duplicates from an array
  2. JavaScript code to remove duplicates from an array
  3. 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:

  1. Get an object key by its value using JavaScript
  2. 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:

  1. How to flatten a nested JavaScript array
  2. 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:

  1. Find intersection of two arrays in JavaScript
  2. JavaScript Snippet - Map Prototype Has
  3. 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:

  1. Useful JavaScript Snippet - Get portion of URL path
  2. 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:

  1. How to strip HTML tags from string in JavaScript
  2. Strip HTML from text JavaScript
  3. 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:

    1. How to display a JavaScript array in a HTML list
    2. JavaScript array to 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:

    1. Check if an element contains a class using JavaScript
    2. 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:

    1. How to get current date and time in JavaScript
    2. How to get current time and date in JavaScript
    3. 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:

    1. How to Check if a string is JSON in JavaScript
    2. 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:

    1. Delay, sleep, pause, and wait in JavaScript
    2. 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:

    1. Add and remove multiple classes to element in JavaScript
    2. 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:

    1. All you need to know about promise.all
    2. JavaScript promise all snippets
    3. JavaScript Code Snippet - promise all

    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.