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));
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!");
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));
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());
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" });
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" });
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)}`;
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.
-
I am a beginner, how should I learn Front-End Web Dev?
Look into the following articles:
Top comments (23)
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
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.Correct!
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;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 🙂
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
@lukeshiru your point about
copyToClipboard
is 100% legit, but maybe like this then:...so we're able to provide a rejection reason and not just throw text back
Yeah I knew you wouldn’t read the spec, that’s why I said you probably won’t know. Sadly.
There's an error in generateRandomColor: if math random is below 1/0x100000, the value may not have 6 characters.
Why not just
padStart
?String.prototype.padStart
is pretty recent and not supported by older browsers.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:
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 🛌
Actually, there is one problem with shuffle function
// 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:
source: javascript.info/array-methods#tasks
1) Have you even read the spec I wrote?
2) lol
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.