DEV Community

Cover image for 7 Killer One-Liners in JavaScript
Tapajyoti Bose
Tapajyoti Bose

Posted on • Updated on • Originally published at tapajyoti-bose.Medium

7 Killer One-Liners in JavaScript

7 Killer One-Liners in JavaScript

JavaScript is the most crucial pillar of Web Development.

This article contains code snippets hand-picked by sterilized contamination-free gloves and placed onto a satin pillow.

A team of 50 inspected the code and ensured it was in the highly polished before posting. Our article-posting specialist from Switzerland lit a candle, and a hush fell over the crowd as he entered the code into the finest gold-lined keyboard that money can buy.

We all had a wonderful celebration, and the whole party marched down the street to the café where the entire town of Kolkata waved "Bon Voyage!" to the article as it was posted online.

Have a wonderful time reading it!

Shuffle Array

While using algorithms that require some degree of randomization, you will often find shuffling arrays quite a necessary skill. The following snippet shuffles an array in place with O(n log n) complexity.

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);

// Testing
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));
Enter fullscreen mode Exit fullscreen mode

Copy to Clipboard

In web apps, copy to clipboard is rapidly rising in popularity due to its convenience for the user.

const copyToClipboard = (text) =>
  navigator.clipboard?.writeText && navigator.clipboard.writeText(text);

// Testing
copyToClipboard("Hello World!");
Enter fullscreen mode Exit fullscreen mode

NOTE: The approach works for 93.08% global users as per caniuse. So the check is necessary that the user's browser supports the API. To support all users, you can use an input and copy its contents.

Unique Elements

Every language has its own implementation of Hash List, in JavaScript, it is called Set. You can easily get the unique elements from an array using the Set Data Structure.

const getUnique = (arr) => [...new Set(arr)];

// Testing
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr));
Enter fullscreen mode Exit fullscreen mode

Detect Dark Mode

With the rising popularity of dark mode, it is ideal to switch your app to dark mode if the user has it enabled in their device. Luckily, media queries can be utilized for making the task a walk in the park.

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

// Testing
console.log(isDarkMode());
Enter fullscreen mode Exit fullscreen mode

As per caniuse the support of matchMedia is 97.19%.

Scroll To Top

Beginners very often find themselves struggling with scrolling elements into view properly. The easiest way to scroll elements is to use the scrollIntoView method. Add behavior: "smooth" for a smooth scrolling animation.

const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" });
Enter fullscreen mode Exit fullscreen mode

Scroll To Bottom

Just like the scrollToTop method, the scrollToBottom method can easily be implemented using the scrollIntoView method, only by switching the block value to end

const scrollToBottom = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "end" });
Enter fullscreen mode Exit fullscreen mode

Generate Random Color

Does your application rely on random color generation? Look no further, the following snippet got you covered!

const generateRandomHexColor = () =>
  `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
Enter fullscreen mode Exit fullscreen mode

Research says, writing down your goals on pen & paper makes you 21% to 39% more likely to achieve them. Check out these notebooks and journals to make the journey of achieving your dreams easier: https://www.amazon.com/Tapajyoti-Bose/e/B09VGDDHRR

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas

Top comments (40)

Collapse
 
lukeshiru profile image
Luke Shiru • Edited

A few suggestions:

  • Copy function: You can use optional chaining further, and because it's a Promise, you should make it reject when it can't copy:
const copyToClipboard = text =>
    (navigator.clipboard?.writeText ?? Promise.reject)(text);
Enter fullscreen mode Exit fullscreen mode
  • Detect Dark Mode: You can also use optional chaining here, and maybe use globalThis instead of window (mainly for "consistency' given that globalThis is global for the browser, web workers and node, and was introduced as a "standard way of accessing global").
const isDarkMode = () =>
    globalThis.matchMedia?.("(prefers-color-scheme:dark)").matches ?? false;
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
 
martinpham profile image
Martin Pham

1) It will lead to another problem: When navigator.clipboard is not available, the Promise.reject will be called, and probably you won't know: TypeError will be thrown (spec 25.4.4.4)
2) I'm not sure why using globalThis instead of window here btw

Collapse
 
adam_cyclones profile image
Adam Crockett • Edited

Point 2 is especially true

matchMedia will never be isomorphic, such recommendations appear to be blanket.

globalThis was not the original way to reference global and will still break some browsers unless a global.globalThis = global where global is window nor global, is referred to as a polyfill.

Thread Thread
 
martinpham profile image
Martin Pham

Correct!

Thread Thread
 
lukeshiru profile image
Luke Shiru

As I said, is just a suggestion (and pay special attention to the "maybe" before that particular suggestion), and is based on globalThis being more consistent than using global in old node and window in browsers. You just use a single value for globals. I'll add "for consistency" in that comment to avoid further confusion.

Thread Thread
 
adam_cyclones profile image
Adam Crockett

Hey luke I think you miss the point, node will never use screen based APIs such as match media, therefore globalThis is never going to be needed. It's better to be precise about the usage of any code with reasoning which backs it up. There's no "maybe" in this case

Thread Thread
 
lukeshiru profile image
Luke Shiru

I missed the point of globalThis? How so? That value was designed to be consistent across environments. In this particular scenario matchMedia will not be available in globalThis in an environment such as node, but I would much prefer to have matchMedia be undefined, that having window being undefined as well and having to do the "double check" ... that being the case we need yet another optional chain just for that:

window?.matchMedia?.("(prefers-color-scheme:dark)").matches;
Enter fullscreen mode Exit fullscreen mode

Not to mention that when testing in isolation, is way easier to mock something global using globalThis from node, than having to figure out the environment first and then where to do the mock. Consistency for things like this, from my point of view, is really valuable. The main difference from my point of view is that you'll use globalThis always when talking about a "global value" in any JS environment, while you'll use window only on the browser (and maybe deno which has window as a global as well). So you have to chose between writing a different global based on where the code is running, or use always the same global. This is taken straight from MDN's description of globalThis:

The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in.

Thread Thread
 
adam_cyclones profile image
Adam Crockett

I missed the point of globalThis?

No, I believe you have a firm grasp of JavaScript in general and understanding that globalThis brings safety through referencing whatever the global scope may be.

.. however, let's just step back, in this particular instance and many others, window is the only appropriate approach to access match media or any Browser based API, because;

  • there is no motivation from anyone including the community to add it to node.js or any other js environment
  • because it wouldn't do anything in any other environment

With such a low risk (which is the truth of programming, evaluation of risk to solve a problem as best you can)

Therefore as true optimization it's worth removing the complexity of polyfill, you are creating work for yourself in the name of safety

Example:
I am a banana but I could be an orange but the odds are extremely low that I am anything other than a banana, better prepare for both eventualities.

To me that's not efficient planning 🙂

Thread Thread
 
lukeshiru profile image
Luke Shiru • Edited

I get you, but the thing is why use window for this particular function and the few that are "like it", and then globalThis for everything else, when we can just use globalThis for anything global? There's not much value in that distinction, and now we need to consider different globals when mocking and coding, instead of just one.

Using your example, you're a banana, but you're also a fruit, so what better way of being prepared for eventualities than coding for fruits instead of coding thinking only in bananas 😅

And this is not even considering that is not a big change, is just using globalThis instead of window, is not that the implementation is completely changed 😵‍💫

Thread Thread
 
adam_cyclones profile image
Adam Crockett • Edited

The ultimate point here is that, you suggested something implicit globalThis is agnostic and implicit, window was correct and explicit, explicit tells me a little more about the intent of the code - in my head: "window suggests this must be browser only code"

My nitpicky points come from a good place. Do you know how much code runs behind the scenes for JavaScript to do a simple 2 plus 2? It's shockingly quite a lot! Although I won't let that put the fear into me, I don't believe in micro optimizations after all, I do believe that programming is exact, in the grand scheme from the computers perspective, it works or it don't. But the human, well that's a different story, humans make assumptions which lead to N number of understandings, so I feel that it's our job as programmers, writers of instructions, to layout out Intensions using explicit code, it is always clearer and carries some meta meaning, implicit is just magic it's implied with out reference and prior knowledge must be obtained.

I argue, and from several past mistakes I might add that adopting a blanket coding standard is pretty toxic, by adopting a rule for all cases without then thinking is this adding a little more work that should not happen in this situation, I believe that actually, this is the cause of most sub optimal code. Additionally globalThis is newish, it does nothing for a new programmer who may have seen thousands of bits of code with window

A wise programer once said:

"code must be smarter than table, but dumber than dog"

A sentiment that sticks with me almost 6 years after hearing it, to me, it means that simple (as in the intent) is not the same as simplyfied syntax and a fact I bitterly resent, by using the latest and greatest of any language features (typically abstractions) is then bringing a lot small pieces of overhead.

Lastly let's get quantitative, globalThis, how much have you used it and what percentage of it actually made it into both Node.js and Browser? Then answer this one, based on your previous answer, was it worth the saving? If the answer was, "not much but yes because it's easier." Does that mean perhaps you don't actually care about correct code. 😱

Thanks for playing, it's been fun 🛌

Thread Thread
 
lukeshiru profile image
Luke Shiru

The ultimate point here is that, you suggested something implicit globalThis is agnostic and implicit, window was correct and explicit, explicit tells me a little more about the intent of the code - in my head: "window suggests this must be browser only code".

I suggested globalThis because is the "most consistent global value" we have in modern JS. Previous to that if we wanted to access something global, we needed to check for window, or self or this or global, now is just globalThis. I see value in that consistency, you see value in being explicit that you want to access something that is only available in window and not in other globals. So you want to read window?.matchMedia as "match media in the browser", while I prefer globalThis?.matchMedia as "if there is a match media in the global space, use that". I also mentioned that is easier to test and mock (I can easily do a unit test of a function with globalThis from node and mock matchMedia if needed, I can't say the same about window).

So long story short, I prefer the consistent value, you prefer the value that will tell you something about where will it be used. So I prefer a more "abstract" approach, and you prefer a more concrete one.

Layout out Intensions using explicit code, it is always clearer and carries some meta meaning, implicit is just magic it's implied with out reference and prior knowledge must be obtained.

We should always code with other human beings in mind. I will always prefer readable code over "performant". But the thing is that you see globalThis as "implicit", and I see it as a "explicit true global".

Additionally globalThis is newish, it does nothing for a new programmer who may have seen thousands of bits of code with window

That's exactly why I make this suggestions. You will never learn about new stuff if everybody "avoids it" just because is new. This is like saying we should be using function because arrow functions are pretty new X_X

Lastly let's get quantitative, globalThis, how much have you used it and what percentage of it actually made it into both Node.js and Browser?

I just tend to avoid globals altogether, just because I tend to do programming closer to FP principles, and relying on global is a really bad practice in FP. But when I need global, I use globalThis. At work we used it a few times and made testing and mocking way easier. In environments such as Deno, you can get pretty sweet stuff like localStorage in both the client side and the server side.

Thanks for playing, it's been fun

I guess that's your way of saying you don't want to discuss this any longer, but I hope you understand why I made suggestions like the one I made, even if you don't agree with it. I hope that even if what's valuable for me isn't valuable for you, you at least see the value that motivates me to do this kind of suggestions.

Cheers!

Collapse
 
lukeshiru profile image
Luke Shiru • Edited

Why type error will be thrown? You're rejecting the promise, so you can catch it and show an error like "Can't copy". Have you even tried that line? 😅

copyToClipboard("😉")  
  .then(showFancyCopyAnimation)
  .catch(showErrorMessage);
Enter fullscreen mode Exit fullscreen mode

If you don't reject the promise, then the returned value is either a Promise or undefined which isn't ideal.

globalThis is better just because is more consistent, but again, this are just suggestions.

Thread Thread
 
martinpham profile image
Martin Pham

1) Have you even read the spec I wrote?

2) lol

Thread Thread
 
lukeshiru profile image
Luke Shiru • Edited

I don't need to read that spec, this doesn't require a spec to understand it, is easy:

const copyToClipboard = text =>
    navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

navigator.clipboard here might be undefined so the author uses optional chaining and then the && operator, this way if clipboard is undefined, the expression reads: undefined && ..., so because undefined is falsy, we return that value but if it is defined, we return a Promise, so the output is Promise | undefined.

Now the code suggestion:

const copyToClipboard = text =>
    (navigator.clipboard?.writeText ?? Promise.reject)(text);
Enter fullscreen mode Exit fullscreen mode

Is pretty similar to the previous one, but this time we make use of nullish coalescing, so if navigator.clipboard is undefined we just return a rejected promise, this is better because now we return a Promise either way, and we can handle it easier.

The main difference is later, when we want to use it:

// With the author code:
(copyToClipboard("😉") === undefined
    ? showErrorMessage
    : showFancyCopyAnimation)();

// With my suggestion, as I already shown:
copyToClipboard("😉")
  .then(showFancyCopyAnimation)
  .catch(showErrorMessage);
Enter fullscreen mode Exit fullscreen mode

Do you really need a spec to get how that works? :/

Thread Thread
 
snigo profile image
Igor Snitkin

@lukeshiru your point about copyToClipboard is 100% legit, but maybe like this then:

const copyToClipboard = async (text) => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

...so we're able to provide a rejection reason and not just throw text back

Thread Thread
 
lukeshiru profile image
Luke Shiru

That's another sweet approach, yup. The important thing is to always return a Promise 💖

 
martinpham profile image
Martin Pham

Yeah I knew you wouldn’t read the spec, that’s why I said you probably won’t know. Sadly.

Thread Thread
 
lukeshiru profile image
Luke Shiru

Bro, are you just trolling? Seriously if you actually wanted to "prove a point" you would actually comment what that spec has to do with what I wrote, or at least share a link to "the spec" you're talking about and how it relates to my comment. This is not the first time you just reply or comment something I wrote adding 0 value to the conversation other than remarks like "sadly" .... smh.

Thread Thread
 
martinpham profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Martin Pham

Well, I wouldn’t waste time to “troll” anyone here, I want you to be a better dev instead.
Your solution is not good, because like I said, the Promise.reject will be called when clipboard is not available, TypeError will be thrown (since reject is being called on non-obj). As it’s been described in the spec I told you to read.

But sadly, you just don’t want to listen, don’t want to read the documentation. It’s just impossible to discuss like that. And I’m so sorry if I said something bad to you.

Thread Thread
 
lukeshiru profile image
Luke Shiru • Edited

I want you to be a better dev instead.

Saying "lol read a spec" is not the way. If you actually wanted me to be "a better dev" you provide actual sources or explanations. You still didn't linked the actual spec, you could say instead that Promise isn't available if clipboard doesn't exist, which could be a valid point if it wasn't for the fact that is way easier and more common to polyfill Promise than doing so with clipboard. You could also provide a better alternative in a snippet so we all learn. Still If we are targeting supported browsers, Promise will be there if clipboard isn't, unless your point is that Promise isn't available in IE 11 (not to mention that the main point of my suggestion is being consistent with the returned type of the function, which can also be achieved with an await as suggested by other user here).

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
t0nyba11 profile image
Tony B

I know this isn't exactly in the spirit of one-liner (you could squeeze it I guess!), but this approach would likely scale better for shuffling larger arrays.

o(n) instead of o(n log n) via your sort approach I think.


const shuffleArray = arr => {
  for (let i = 0, j, l = arr.length; i < l; i++) {
    const x = arr[i]
    arr[i] = arr[j = Math.random() * l | 0];
    arr[j] = x;
  };
  return arr;
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lexlohr profile image
Alex Lohr

There's an error in generateRandomColor: if math random is below 1/0x100000, the value may not have 6 characters.

// wrong:
const generateRandomHexColor = () =>
  `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;

// corrected:
const generateRandomHexColor = () =>
  `#${Math.floor(0x1000000 + Math.random() * 0xffffff).toString(16).slice(1)}`;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
snigo profile image
Igor Snitkin

Why not just padStart?

Collapse
 
lexlohr profile image
Alex Lohr

String.prototype.padStart is pretty recent and not supported by older browsers.

Collapse
 
vanekcheck profile image
Vanya • Edited

Actually, there is one problem with shuffle function

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);

// counts of appearances for all possible permutations
let count = {
  '123': 0,
  '132': 0,
  '213': 0,
  '231': 0,
  '321': 0,
  '312': 0
};

for (let i = 0; i < 1000000; i++) {
  let array = [1, 2, 3];
  shuffleArray(array);
  count[array.join('')]++;
}

for (let key in count) {
  console.log(`${key}: ${count[key]}`);
}
Enter fullscreen mode Exit fullscreen mode

// the result will be
"123: 374916"
"132: 62851"
"213: 125285"
"231: 62489"
"312: 62000"
"321: 312459"

We can see clearly: 123 and 321 appear much more often than others.

There are other good ways to do the task. For instance, there’s a great algorithm called Fisher-Yates shuffle. The idea is to walk the array in the reverse order and swap each element with a random one before it:

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
    [array[i], array[j]] = [array[j], array[i]];
  }
}
Enter fullscreen mode Exit fullscreen mode

source: javascript.info/array-methods#tasks

Collapse
 
andrewbridge profile image
Andrew Bridge

Sporadically in the same browser or varying across different browsers? I've certainly had to polyfill this behaviour option for Safari and several Chromium based browsers on macOS which is quite frustrating but never seen it fail to work when it is natively supported.

Collapse
 
jeydotc profile image
Jeysson Guevara

The copy to clipboard one is a really bad idea, in this case, you're just silencing a potential error without proper handling.

I've faced too many obscure bugs because of this kind of bad practice.

Collapse
 
lukeshiru profile image
Luke Shiru

How is it silencing errors? Do you prefer it to throw because you're trying to access writeAccess of undefined? You can still handle errors with it, is just a little bit awkward to do so with the implementation in the post, as I mentioned in this comment.

Collapse
 
jeydotc profile image
Jeysson Guevara

Well, It is hiding any error derived from the browser not supporting that API, and I wasn't referring to your solution in the comments (which looks cool), if that's what you think.

And no, I don't prefer to throw because of undefined, I prefer either your version of the solution (with the reject), or show a message to the user indicating the lack of support, or to directly hide the feature if we assert it beforehand.

Hiding an error is to catch/prevent an exception and do nothing with that, as the OP does, just think from an end user perspective, you'll click on a copy to clipboard button, then see a success message and then, when you attempt to paste... Nothing.

Thread Thread
 
lukeshiru profile image
Luke Shiru

But the OP is the same as mine, the main difference is that OP needs to check for undefined when used, but both require extra code to "show the error". If you always return a promise you have to use .catch to handle the possible error, but either way the error handling doesn't go in the function itself. If we don't do a .catch in my version, then the "error is hidden" as well X_X

Collapse
 
gantlaborde profile image
Gant ℒ𝒶𝒷ℴ𝓇𝒹ℯ

It makes me so sad that JavaScript still needs these functions explained instead of part of the standard lib in 2022.

Collapse
 
tutorial_livre profile image
Tutorial Livre

You can use optional chaining for functions too, so:

navigator.clipboard?.writeText?.(text);
Enter fullscreen mode Exit fullscreen mode

Is valid

Collapse
 
andrewbaisden profile image
Andrew Baisden

Dope some good ones in here.

Collapse
 
bacloud22 profile image
aben • Edited

we need more and more like dozens !!! Better to specify running on which platform: browsers and nodejs

Collapse
 
dayliver profile image
dayliver

Beautiful!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.