Improve JS programming efficiency: 19 practical JS code examples

In actual work, developers often face challenges that require clever programming to solve. Sometimes a few lines of code can solve the problem. This article has compiled a series of practical code snippets to help you easily handle common issues such as URLs, DOM operations, event handling, date processing, and user preference settings.

These featured code snippets are sourced from ” 30 seconds of code” – a preeminent library of programming resources. I highly recommend checking out its full code for more inspiration.

The first criterion for selecting these code snippets is their usefulness. I hope you will find valuable resources here and apply them to future projects to improve your programming efficiency and quality.

1. How to get the base URL?

const getBaseURL = url => url.replace(/[?#].*$/, '');

getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'

2. How to check if a URL is absolute?

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false

3. How to get URL parameters as objects?

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  );

getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}

4. How to check if an element contains another element?

const elementContains = (parent, child) =>
  parent !== child && parent.contains(child);

elementContains(
  document.querySelector('head'),
  document.querySelector('title')
);
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false

5. How to get all ancestors of an element?

const getAncestors = el => {
  let ancestors = [];
  while (el) {
    ancestors.unshift(el);
    the = the. parentNode ;
  }
  return ancestors;
};

getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]

6. How to smoothly scroll elements into view?

const smoothScroll = element =>
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth'
  });

smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar');
// scrolls smoothly to the first element with a class of fooBar

7. How to handle clicks outside an element?

const onClickOutside = (element, callback) => {
  document.addEventListener('click', e => {
    if (!element.contains(e.target)) callback();
  });
};

onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element

8. How to generate UUID?

const UUIDGeneratorBrowser = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );

UUIDGeneratorBrowser (); // '7982fcfe-5721-4632-bede-6000885be57d'

9. How to get the selected text?

const getSelectedText = () => window.getSelection().toString();

getSelectedText (); // 'Lorem Ipsum'

10. How to copy text to the clipboard?

const copyToClipboard = str => {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str);
  return Promise.reject('The Clipboard API is not available.');
};

11. How to add styles to HTML elements?

const addStyles = (el, styles) => Object.assign(el.style, styles);

addStyles(document.getElementById('my-element'), {
  background: 'red',
  color: '#ffff00',
  fontSize: '3rem'
});

12.How to switch to full screen mode?

const fullscreen = (mode = true, el = 'body') =>
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen();

fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode

13. How to detect whether Caps Lock is on?

<form>
  <label for="username">Username:</label>
  <input id="username" name="username">

  <label for="password">Password:</label>
  <input id="password" name="password" type="password">
  <span id="password-message" style="display: none">Caps Lock is on</span>
</form>
const el = document.getElementById('password');
const msg = document.getElementById('password-message');

el.addEventListener('keyup', e => {
  msg.style = e.getModifierState('CapsLock')
    ? 'display: block'
    : 'display: none';
});

14. How to check if the date is valid?

const  isDateValid = ( ...val ) => ! Number . isNaN ( new  Date (...val). valueOf ());

isDateValid ( 'December 17, 1995 03:24:00' ); // true 
isDateValid ( '1995-12-17T03:24:00' ); // true 
isDateValid ( '1995-12-17 T03:24:00' ); // false 
isDateValid ( 'Duck' ); // false 
isDateValid ( 1995 , 11 , 17 ); // true 
isDateValid ( 1995 , 11 , 17 , 'Duck' ); // false 
isDateValid ({}); // false

15. How to get hour, minute and second information from date?

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // '08:38:00'

16. How to generate UNIX timestamp from Date?

const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);

getTimestamp(); // 1602162242

17. How to check the current user’s preferred language?

const detectLanguage = (defaultLang = 'en-US') =>
  navigator.language ||
  (Array.isArray(navigator.languages) && navigator.languages[0]) ||
  defaultLang;

detectLanguage(); // 'nl-NL'

18. How to view a user’s preferred color scheme?

const prefersDarkColorScheme = () =>
  window &&
  window.matchMedia &&
  window.matchMedia('(prefers-color-scheme: dark)').matches;

prefersDarkColorScheme(); // true

19. How to check if the device supports touch events?

const supportsTouchEvents = () =>
  window && 'ontouchstart' in window;

supportsTouchEvents(); // true