DEV Community

Cover image for 30 JavaScript Tricky Hacks

30 JavaScript Tricky Hacks

Mainul Hasan on March 03, 2024

Welcome to our curated collection of JavaScript tricks, which will help you optimize your code, make it more readable, and save you time. Let’s di...
Collapse
 
moopet profile image
Ben Sinclair

If the premise is to "help you optimize your code, make it more readable, and save you time", then I'd steer clear of some of these.

Using !! to convert to boolean

This is probably less readable, especially for people new to Javascript. There's nothing wrong with using a truthy value directly or casting things explicilty.

"short-circuit" evaluation

Again, there's nothing wrong with using more characters to make things easier to read, and in fact there are good reasons to keep separate things on separate lines (like always using a block for if).

Using ^ for Swapping Values

This hasn't been useful for at least 30 years unless you're trying to impress someone in a coding interview. It's not readable, and it doesn't save any time or effort.

Converting to Numbers with Unary Plus

Same deal as before. Be explicit.

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you for taking the time to share your excellent thoughts. I truly appreciate your perspective and understand the concerns about readability, particularly for those new to JavaScript.

The intention behind showcasing these techniques, such as using !! to force a boolean context or the unary + for type conversion, was to present a spectrum of approaches that developers might encounter in practice or find useful in specific scenarios.

It’s a valid point that explicit casting and traditional methods can enhance clarity, especially for less experienced developers. The utility of these tips often depends on the context in which they’re used and the audience interpreting the code.

Regarding the bitwise XOR for value swapping, I agree that it’s not a common practice in every day coding. It’s indeed more of a fun trick that could be useful to understand when reading legacy code or preparing for interviews, as you mentioned.

Ultimately, the goal is to inspire developers to think critically about the tools at their disposal and to choose the best tool for the task, balancing efficiency and readability.

Thanks again for providing friendly suggestions and feedback.

Collapse
 
iakovosvo profile image
iakovosvo

Regarding the use of !!, I find Boolean(isThisAtruthyValue) to be more expressive and easier to read.

Collapse
 
mainulspace profile image
Mainul Hasan

Absolutely, using Boolean(isThisTruthyValue) is indeed more expressive and can be clearer to read, especially for those who are not as familiar with the nuances of JavaScript’s type coercion. It’s great that you’ve highlighted an alternative that prioritizes readability and self-documenting code.

The choice between !! and Boolean() often comes down to personal or team preference, and the context in which the code will be read and maintained. I appreciate you bringing this up β€” it’s always beneficial for developers to be aware of different options that can make their intent more explicit.

Thank you for adding to the conversation with your insightful suggestion!

Collapse
 
seandinan profile image
Sean Dinan • Edited

As a counter-point for short circuit evaluation, I've mostly switched over to it for conditionally rendering things in JSX. I stuck to ternary for years but have gradually switched over.

I'd now say that:

return (
  <section>
    {isLoading && <LoadingMessage/>}
    {/* ... */}
  </section>
)
Enter fullscreen mode Exit fullscreen mode

is at least as clear as:

return (
  <section>
    {isLoading ? <LoadingMessage/> : null}
    {/* ... */}
  </section>
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
moopet profile image
Ben Sinclair

I agree, for things like JSX (which still look uncomfortable to me even after a few years) it is still readable - provided you keep things simple.

Collapse
 
chasm profile image
Charles F. Munat

True. And the way to convert to Boolean is Boolean(value).

Collapse
 
masteryder profile image
JoΓ£o Filipe Ventura Coelho

Was about to comment the exact same thing

Collapse
 
joolsmcfly profile image
Julien Dephix • Edited

Nice list, even though I wouldn't call these code snippets hacks but shortcuts?

Couple of things to note.

Hack # 1: !! is called a double bang. I don't use it as it looks a bit weird. I prefer to use Boolean().

Hack # 11. example you provided for tagged template literals could be better as it just outputs what was passed. Looks like a copy of Wes Bos' article back in 2016:

function highlight(strings, ...values) {
  let str = '';
  strings.forEach((string, i) => {
    str += `${string} <span class='hl'>${values[i] || ''}</span>`;
  });
  return str;
}
Enter fullscreen mode Exit fullscreen mode

Hack #21. swapping values is much easier this way:

let a = 2, b = 1;
[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

Hack #23. converting the way you do it can cause issues if variable holds non numerical characters. Prefer .parseInt over plus.

let n = "123A";
console.log(+n); // NaN
console.log(parseInt(n, 10)); // 123
Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Collapse
 
xi_sharky_ix profile image
shArky

Simply note, that #21 is more readable (for me both is good), but not easier for PC.
In case of XOR swap we working with numbers as bits represented in memory. In case of array swap we created 2 arrays.

Collapse
 
joolsmcfly profile image
Julien Dephix

You're right but it only creates one array actually: a temp array [b, a].
JS then destructures it to assign values to a and be respectively.

This is what code looks like after being transpiled:

    var a = 12;
    var b = 13;
    var _b;
    _b = [b, a], a = _b[0], b = _b[1];
Enter fullscreen mode Exit fullscreen mode

Yes, it uses more memory but we're talking about 2 numbers here so the diff in memory footprint is very minimal and not worth loosing readability.

Collapse
 
jdhinvicara profile image
John Harding

Cool! I never knew about #11. It took me a while to figure it out - and, as another poster (@joolsmcfly) mentioned, your example just returns the same string you passed in. However, the sample he provided has an empty span at the end and doesn't use reduce...

So, here's my submission as a better example (which is entirely subjective of course):

const spanify = (strings, ...values) => 
  strings.reduce((resultSoFar, stringPart, valueIndex) => 
    `${resultSoFar}${stringPart}${values[valueIndex]?`<span class='foo'>${values[valueIndex]}</span>`:''}`, '')

spanify`My name is ${'John'}` // "My name is <span class='foo'>John</span>"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lotfijb profile image
Lotfi Jebali

console.table() :))))

Collapse
 
chasm profile image
Charles F. Munat

In dev terms, "tricky" is bad. Nothing you do in code should ever be "tricky". That's a fail. Hacks should also be avoided except in extraordinary circumstances.

But most of these are not "hacks" and most are not "tricky". How these listicles that have nothing but collections of old info keep getting onto the DEV Community Digest list while far better and more interesting articles languish in obscurity is quite disturbing.

What is up with that?

Collapse
 
jdhinvicara profile image
John Harding

@chasm - Yes, the article might be slightly mistitled- but it is a good list. I've been writing code for 30+ years and I learned from #11 (even though it wasn't a great example - it piqued my interest and made me look more). I may even have already known that info but forgotten it.

As a listicle I could scan it quickly (and I cringed at #21!) - it's actually one of the better articles because it's so terse.

The constant publishing of "old" information is thus useful because it can remind all of us of little bits and pieces. As to why other articles languish - who knows? Maybe, just maybe, that's more the subjectivitiy of what you think is interesting?

@mmainulhasan - perhaps a better title "30 useful JS tips and tricks" ?

Collapse
 
daniordonez profile image
Daniel Ordonez

For cloning objects with depth I prefer structuredClone() instead of the spread operator (#6) so you don’t store references to objects inside the old object in the clone.

Collapse
 
cuihaoweb profile image
cuihao

The article is very practical, I want to reprint your article, will mark the source of the article, if there is something wrong, please contact me, I will immediately delete

Collapse
 
kmsaifullah profile image
Khaled Md Saifullah

Many things got to know from this blog. Thank you so much.

Collapse
 
jangelodev profile image
JoΓ£o Angelo

Hi M Mainul Hasan,
Your tips are very useful
Thanks for sharing

Collapse
 
sezginibis profile image
Sezgin İbiş (incelemeelemani)

Thanks for you article.

Collapse
 
urian121 profile image
URIAN VIERA

Excelente amigo.

Collapse
 
likeatruckberserker profile image
Fiji

Sweet! Thanks

Collapse
 
get_pieces profile image
Pieces 🌟

Great article! πŸ”₯

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

Very nice ! I never knew about 11.

Collapse
 
emmabase profile image
Emmanuel Eneche

Great article. πŸ‘

Collapse
 
serantu profile image
Serantu

Thanks for the resource!