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

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

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 (23)

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!

 
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 🙂

 
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

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

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.

 
Sloan, the sloth mascot
Comment deleted
 
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 🛌

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

 
martinpham profile image
Martin Pham

1) Have you even read the spec I wrote?

2) lol

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.

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