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)}`;
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.
-
I am a beginner, how should I learn Front-End Web Dev?
Look into the following articles:
Top comments (40)
A few suggestions:
window
(mainly for "consistency' given thatglobalThis
is global for the browser, web workers and node, and was introduced as a "standard way of accessing global").Cheers!
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!
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 usingglobal
in old node andwindow
in browsers. You just use a single value for globals. I'll add "for consistency" in that comment to avoid further confusion.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
I missed the point of
globalThis
? How so? That value was designed to be consistent across environments. In this particular scenariomatchMedia
will not be available inglobalThis
in an environment such asnode
, but I would much prefer to havematchMedia
beundefined
, that havingwindow
beingundefined
as well and having to do the "double check" ... that being the case we need yet another optional chain just for that: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 useglobalThis
always when talking about a "global value" in any JS environment, while you'll usewindow
only on the browser (and maybedeno
which haswindow
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 ofglobalThis
: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 🙂
I get you, but the thing is why use
window
for this particular function and the few that are "like it", and thenglobalThis
for everything else, when we can just useglobalThis
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 😵💫
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 🛌
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 forwindow
, orself
orthis
orglobal
, now is justglobalThis
. I see value in that consistency, you see value in being explicit that you want to access something that is only available inwindow
and not in other globals. So you want to readwindow?.matchMedia
as "match media in the browser", while I preferglobalThis?.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 withglobalThis
from node and mockmatchMedia
if needed, I can't say the same aboutwindow
).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.
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".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_XI 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 likelocalStorage
in both the client side and the server side.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!
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? 😅
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.1) Have you even read the spec I wrote?
2) lol
I don't need to read that spec, this doesn't require a spec to understand it, is easy:
navigator.clipboard
here might beundefined
so the author uses optional chaining and then the&&
operator, this way if clipboard isundefined
, the expression reads:undefined && ...
, so becauseundefined
is falsy, we return that value but if it is defined, we return aPromise
, so the output isPromise | undefined
.Now the code suggestion:
Is pretty similar to the previous one, but this time we make use of nullish coalescing, so if
navigator.clipboard
isundefined
we just return a rejected promise, this is better because now we return aPromise
either way, and we can handle it easier.The main difference is later, when we want to use it:
Do you really need a spec to get how that works? :/
@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
That's another sweet approach, yup. The important thing is to always return a Promise 💖
Yeah I knew you wouldn’t read the spec, that’s why I said you probably won’t know. Sadly.
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.
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.
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 ifclipboard
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 ifclipboard
isn't, unless your point is thatPromise
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 anawait
as suggested by other user here).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.
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.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
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.
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.
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.
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.
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_XIt makes me so sad that JavaScript still needs these functions explained instead of part of the standard lib in 2022.
You can use optional chaining for functions too, so:
Is valid
Dope some good ones in here.
we need more and more like dozens !!! Better to specify running on which platform: browsers and nodejs
Beautiful!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.