DEV Community

Cover image for 24 modern ES6 code snippets to solve practical JS problems

24 modern ES6 code snippets to solve practical JS problems

Madza on January 30, 2020

I hand-picked some of the most useful code snippets from 30 seconds of code. It's an awesome resource, go ahead and show it some ❤️. In this artic...
Collapse
 
3zzy profile image
Ibrahim Ezzy

hasClass(document.querySelector('p.special'), 'special'); doesn't make sense. If you're already searching with the class in selector, couldn't you just do if (document.querySelector('p.special')) ?

Collapse
 
fetishlace profile image
fetishlace

To point 12.
Instead of confusing reduce I would do rather:
const formToObject = form => Object.fromEntries([...new FormData(form)])
(when Object.fromEntries() is available indeed...)

Collapse
 
zarabotaet profile image
Dima

Congrat, you reinvented
yarn add jquery

Collapse
 
jscripter profile image
Jscripter

I didn't know about the classList.toggle. Thanks.
In nodejs there is native package called querystring for url parameters.
I find it useful copy to clipboard, used it in a project.

Collapse
 
vonheikemen profile image
Heiker
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);

That number 14 really doesn't do anything. You might as well just assign the function to delay.

const delay = setTimeout;
Collapse
 
madza profile image
Madza • Edited

I see your point. This is great for hard-coded values in setTimeout() method and without need to create other constants later, like:

const delay = setTimout(()=>{console.log('delay event')}, 1000); 
// logs 'delay event' after 1000ms each time

by wrapping setTimeout() method in a function you can re-use your defined timer function with different values each time without creating new constants:

const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
delay(()=>{console.log('delay event 1')}, 1000) //logs 'delay event 1' after 1000ms
delay(()=>{console.log('delay event 2')}, 5000) //logs 'delay event 2' after 5000ms, etc
Collapse
 
vonheikemen profile image
Heiker • Edited

by wrapping setTimeout() method in a function you can re-use your defined timer function with different values each time without creating new constants

I'm not sure I understand what you're saying here. They behave the same.

var delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
var renamed = setTimeout;

var handler = (arg) => { console.log('delay event 1', arg) };
var other_handler = (arg) => { console.log('another one', arg) };

delay(handler, 1000, 'from delay');
renamed(handler, 1000, 'from renamed');
setTimeout(handler, 1000, 'from setTimeout');

delay(other_handler, 2000, 'from delay');
renamed(other_handler, 2000, 'from renamed');
setTimeout(other_handler, 2000, 'from setTimeout');

Personally, if I were to wrap setTimeout it would be to change the function signature, something like this.

var delay_fn = (wait, fn) => (...args) => setTimeout(fn, wait, ...args);

var delay_log = delay_fn(1000, handler);

delay_log('from delay log');

I only use var because I tested these on firefox's devtools.

Thread Thread
 
madza profile image
Madza

That's the point - they behave the same, but you don't have to create new variables for the same functionality throughout your app. Instead you just use the same function once you need timer functionality for something.

Furthermore, if you need different function signature, you can use the latter assigning it to different var.

Thread Thread
 
vonheikemen profile image
Heiker

they behave the same, but you don't have to create new variables for the same functionality throughout your app.

if I assign setTimeout that will force me to create new unnecesary variables in the entire app? And that doesn't happen if I wrap it in a function?

Thread Thread
 
piterden profile image
Denis Efremov
/**
 * Sleep pause.
 *
 * @param {Number} time The time in milliseconds.
 * @return {Promise<void>}
 */
const sleep = (time) => new Promise((resolve) => {
  setTimeout(resolve, time)
})
Collapse
 
webreflection profile image
Andrea Giammarchi • Edited

The getURLParameters is not really safe/useful, I'd go instead with:

const getURLParameters = url => [
  ...new URL(url).searchParams
].reduce(
  (obj, [key, value]) => ((obj[key] = value), obj),
  {}
);

or, for possible duplicated keys:

const getURLParameters = url => [
  ...new URL(url).searchParams
].reduce(
  (obj, [key, value]) => ((
    obj[key] = key in obj ? [].concat(obj[key], value) : value
  ), obj),
  Object.create(null)
);
Collapse
 
3zzy profile image
Ibrahim Ezzy

To to check if the element specified is visible in the viewport, IntersectionObserver is more performant and available in all major browsers.

Collapse
 
madza profile image
Madza • Edited

Thanks for your feed. Checked in caniuse and the support is better than i expected :)

Collapse
 
kimsean profile image
thedevkim

I love one liners but I'm afraid that my co-developers wont get it right.

Collapse
 
madza profile image
Madza • Edited

For those not familiar with ES6 syntax it could be harder to grasp at first :)

Collapse
 
isherwood profile image
Clint Buhs

Yeah, but these aren't one liners in the traditional sense (code crushed like a soda can for no good reason). The new syntax is worth working to understand since it brings benefits beyond brevity.

Collapse
 
piterden profile image
Denis Efremov
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));

This is wrong! ^

const hide = (el) => [...el].forEach(e => (e.style.display = 'none')); 

This is correct! ^

Collapse
 
marko035 profile image
Marko • Edited

22 can be shortened a lot. Here is shorter version.

const listener = (e: ClipboardEvent) => {
  e.clipboardData.setData('text/plain', text);
  e.preventDefault();
};

document.addEventListener('copy', listener);
document.execCommand('copy');
document.removeEventListener('copy', listener);
Collapse
 
madza profile image
Madza • Edited

Thanks for your point. I first started with clipbard.js for that (3kb gzipped) :)

Collapse
 
cyberhck profile image
Nishchal Gautam

These are the worst piece of advice I saw, sorry, I'm just being honest. You have toggle already, you wanna wrap that, just use the original method, why not use setTimeout instead of delay? Use fetch to post to a url, just use remove event listener to remove, following these, people will have to learn new functions instead of using normal Javascript

Some of them might be useful, but I found most of them to be nonsense.

Collapse
 
mateiadrielrafael profile image
Matei Adriel

Why do you need the spread in the first example, rest params will already be collected into an array

Collapse
 
cameronapak profile image
cameronapak

Thanks for posting this! I'll definitely keep them saved and in mind. I see that a lot of people are saying some comment about how something isn't best practice, but I'm happy you even posted this. Even if there are better ways, most of these are great examples and approaches I would've never thought about on my own.

Collapse
 
fetishlace profile image
fetishlace • Edited

To point 11. It is maybe modern JS but there is URL object for these things for some time, no need for regexping
You have all the parameters in URL searchParams object
const params = new URL(window.location.href).searchParams
You can just spread it into entries
[...params] or [...params.entries()]
or if you want to have object so much (even it makes not much sense here, since you can have valid params string with multiple same parameter with different values and then you will loose them except last one, since object cannot have multiple same keys...)
Object.fromEntries([...params])

Collapse
 
mwansa19 profile image
Mwansa Chupa

This is great..Thanks

Collapse
 
siddharthshyniben profile image
Siddharth

You don't need to do [...el] I think in the first one. Is there any reason you do that?

Collapse
 
lukegarrigan profile image
Luke Garrigan

Thanks for the blog, some very nice solutions to problems I bump into regularly!