DEV Community

Cover image for 20 JavaScript Tricks Every Developer Must Know πŸš€

20 JavaScript Tricks Every Developer Must Know πŸš€

Jagroop Singh on October 28, 2024

JavaScript is a powerful, flexible language, and knowing a few cool tricks can make your code cleaner, faster, and more efficient. Below are 20 pra...
Collapse
 
hraifi profile image
sewiko

This one is very new to me :

let count;
count ||= 10;
console.log(count); // 10
Enter fullscreen mode Exit fullscreen mode

I really want such kind of functionality and till now I thought it doesn't exist but thanks to use. Now I don't require extra check for undefined or null value.

This is very very useful to me and also other tips as well.
Thanks for sharing @jagroop2001

Collapse
 
oculus42 profile image
Samuel Rouse

I recommend using ??= Nullish Coalescing Assignment rather that Logical OR assignment unless you specifically want to exclude falsy values rather than just nullish.

Collapse
 
jagroop2001 profile image
Jagroop Singh

@oculus42 ,
Great recommendation! Using ??= (Nullish Coalescing Assignment) is indeed a better choice when you want to assign values only if the left-hand side is null or undefined, excluding other falsy values. It helps avoid unintended overrides when falsy values like 0 or '' are present. Thanks for highlighting that distinction! If you have more tips, feel free to share!

Collapse
 
jovian profile image
Nick A

Yeah, I actually have never use that before either, I usually use ?? for a fallback value if I expect something maybe undefined/null.

Collapse
 
jagroop2001 profile image
Jagroop Singh

@jovian ,
That makes sense! The ?? operator is great for providing fallback values, especially when you want to handle undefined or null specifically

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @hraifi , I also learn this from one of my senior.

Collapse
 
hraifi profile image
sewiko

I find your all blogs to be quite informative.

Thread Thread
 
jagroop2001 profile image
Jagroop Singh

❀️

Collapse
 
anirudh7065 profile image
anirudh7065

Same here i have never seen this ||= or this ??=

Collapse
 
rolandcsosz profile image
Roland CsΕ‘sz • Edited

Isn’t the new copy in trick 10 is a deep copy instead of a shallow copy? Shallow copies have the references to the original objects. Deep copies are deep cause there is no reference left in them and you can modify them without changing the originals.

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him) • Edited

Try

const original = { a: { c: 1 }, b: 2 };
const copy = Object.assign({}, original);
copy.a.c = 3;
console.log(original.a.c); // 3 (changed!)
Enter fullscreen mode Exit fullscreen mode

It's a shallow copy because nested objects stay referenced. For deep copies you should use structuredClone()

Collapse
 
rolandcsosz profile image
Roland CsΕ‘sz

Yes, you are totally right. With nested objects the result will be shallow copy but the example is still a deep copy. Object.assign can create deep and shallow copy based on the original object. The article has beginner hashtag on it and by the context of the trick I felt that the description is not showing example what it originally aimed for. πŸ˜…

Thread Thread
 
syeo66 profile image
Red Ochsenbein (he/him) • Edited

You're wrong.

For deep cloning, we need to use alternatives like structuredClone(), because Object.assign() copies property values.
If the source value is a reference to an object, it only copies the reference value.

Source: developer.mozilla.org/en-US/docs/W...

Thread Thread
 
rolandcsosz profile image
Roland CsΕ‘sz

Nope. I think the problem here is that the example show the deep copy side of this new object with primitive properties. It's clearly says "without changing the original" but it can change the original if it had nested property. Yes, it's a useful trick if someone want to modify the primitive properties of a copy but the statement is not true for all use cases. For an article with the #beginner tag it's not so straightforward in my opinion.

The copy of an object whose properties all have primitive values fits the definition of both a deep copy and a shallow copy.

Source: developer.mozilla.org/en-US/docs/G...

Collapse
 
jagroop2001 profile image
Jagroop Singh

@rolandcsosz ,
Great observation! The new copy in Trick 10 does indeed create a deep copy, as it avoids references to the original objects. Shallow copies only replicate the first level, retaining references to nested objects. Thanks for clarifying that distinction! It’s an important detail for understanding how data is managed in JavaScript. If you have any more thoughts, I’d love to hear them!

Collapse
 
khankudo profile image
KhanKudo • Edited

The ||= Operator from Trick 3 would be perfect for Trick 12, really a missed opportunity and classic example of "Do as I say, not as I do" hahaha

Collapse
 
jagroop2001 profile image
Jagroop Singh

@khankudo ,
Haha, that's a great point! The ||= operator would definitely fit well in Trick 12. It’s a classic case of learning from our own mistakes, right? Thanks for the feedback! If you have any other ideas or tweaks, I’m all ears!

Collapse
 
tracygjg profile image
Tracy Gilmore

On item 11, it is worth noting that function memorisation only really works for pure functions. If external state is modified and has the potential to impact the output, the cached values cannot be trusted.
Pure functions: same input => same output.

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks for pointing it out πŸ‘

Collapse
 
john12 profile image
john

What's the use of this Dynamic Imports for Lazy Loading?. Is it provide any benefit ?

Collapse
 
jagroop2001 profile image
Jagroop Singh

Hey @john12 ,
Dynamic imports allows us to load modules only when needed, reducing the initial load time and improving app performance.
This on-demand loading enhances user experience by ensuring faster interactions and reducing the overall bundle size.
It also enables code splitting, making it easier to manage and optimize your application efficiently.

Collapse
 
john12 profile image
john

ohh okay, got it.
Thank you for this wonderful explanation.

Thread Thread
 
jagroop2001 profile image
Jagroop Singh

your welcome @john12

Collapse
 
huiguang_xian profile image
huiguang xian

improve performance

Collapse
 
idanen profile image
Idan Entin

Thanks! Must save as kind of a cheat-sheet.
I have this one coming up in PRs to turn big arrays to maped object (or a Map):

const mapped = Object.fromEntries(
  array.map((item) => [item.id, item])
)
Enter fullscreen mode Exit fullscreen mode

Also, for 12 (grouping an array) we have Object.groupBy() coming up πŸŽ‰

Collapse
 
jagroop2001 profile image
Jagroop Singh

Nice @idanen , sounds like you've got some great refactoring going on!

Collapse
 
olivergrimsley profile image
Mike Oliver

On number 12, you can now just use Object.groupBy, developer.mozilla.org/en-US/docs/W... - however, reduce is extremely powerful and that example is a good example where you need to perform other operations on the grouped data.

Collapse
 
jagroop2001 profile image
Jagroop Singh

@olivergrimsley ,
Absolutely! With Object.groupBy, it’s become much simpler to group data in one line. But you're rightβ€”using reduce allows for more complex operations on the grouped data, making it a valuable tool in many situations. Both approaches have their merits, depending on the use case. Thanks for pointing that out! If you have more insights, I’d love to hear them!

Collapse
 
robertjameszenith profile image
Robert James

Thanks for sharing @jagroop2001 Your function is really new for me , and it's also helpful ,

If I need a background removal service color code which one is perfect for me

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @robertjameszenith for the kind words! 😊 ,
As per my understanding,
If you want something with background removal in JavaScript, a tip is to use canvas to manipulate imagesβ€”applying ctx.clearRect on areas you want transparent works well. You can also use libraries like fabric.js or remove.bg API for more complex removals.

If it's not what you are looking for please explain your query in detail ?

Collapse
 
robertjameszenith profile image
Robert James

@jagroop2001 thank you for trying to understand my problem, yes remove bg is automatically remove any kind of photo, but remove.bg do not remove hair photo smoothly. I want to know you how can i implement remove background transparent background with color code in Zenith Clipping front page .

Image description

what is the latest code

Thread Thread
 
jagroop2001 profile image
Jagroop Singh

Okay, I understand your problem however I haven't collide with such type of issue before. remove bg works in my case but you can try pix2pix with TensorFlow.js if remove bg doesn't work. @robertjameszenith

Thread Thread
 
robertjameszenith profile image
Robert James

Thank you , If i face some problem i will contact you , please never mind

Thread Thread
 
jagroop2001 profile image
Jagroop Singh
Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

Look at those bots go... 🀣

Collapse
 
skhmt profile image
Mike

For 19 you don't need to use a template literal, you can just console.log(Math.round(num * 100) / 100); directly

Collapse
 
jagroop2001 profile image
Jagroop Singh

@skhmt ,
You're absolutely right! Using console.log(Math.round(num * 100) / 100); is a straightforward way to round the number without the extra complexity of a template literal. Thanks for pointing that out! Always good to streamline the code. If you have more insights, feel free to share!

Collapse
 
iainsimmons profile image
Iain Simmons

Can't you just do num.toFixed(2)?

Thread Thread
 
jagroop2001 profile image
Jagroop Singh

Yes, using num.toFixed(2) is definitely an option. I prefer this in TypeScript, but keep in mind that it changes the number to a string. If you need to convert it back to a number, you'll have to do that separately, which can be a bit cumbersome.

Collapse
 
andrewbaisden profile image
Andrew Baisden

So many of these are useful I use a few all the time.

Collapse
 
jagroop2001 profile image
Jagroop Singh

Good to know @andrewbaisden

Collapse
 
jocedeo1 profile image
jocedeo • Edited

Great tips from ChatGPT...

(tip: try and change the name ChatGPT gives, Alice is reserved for ChatGPT examples)

Collapse
 
jagroop2001 profile image
Jagroop Singh

Olay @jocedeo1 but it's not taken from ChatGPT it's from my experience.

About why I choose name Alice because recently I am doing leetcode basically dynamic programming questions and name Alice is frequently used in a series of it.

Also nowadays, it's easy to say it's GPT based blogs but in reality I dedicated time to this and put my all efforts to list it down with my full time job and other do's.

Collapse
 
liyakat_pathan_f06dbf7425 profile image
Liyakat Pathan

Informative content

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks

Collapse
 
ciphernutz profile image
Ciphernutz IT Services

Great list

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @ciphernutz

Collapse
 
works profile image
Web

High quality content for java-script !!

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks !!

Collapse
 
serhiyandryeyev profile image
Serhiy

some of them are new to me! thanks!!!

Collapse
 
jagroop2001 profile image
Jagroop Singh

Your welcome πŸ™

Collapse
 
wizard798 profile image
Wizard

Great list and covering all essentials tricks for any js developer

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @wizard798 ! I'm glad you found the list helpful

Collapse
 
lutfur_rahman profile image
Lutfur rahman

thanks for sharing

Collapse
 
jagroop2001 profile image
Jagroop Singh

You're welcome

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

I'm glad you found the JavaScript shortcuts helpful! If you need more specific shortcuts or tricks, especially for any particular task in JavaScript or a particular framework, feel free to ask. It’s a pleasure to share helpful insights!

Collapse
 
jagroop2001 profile image
Jagroop Singh

??

Collapse
 
jswhisperer profile image
Greg, The JavaScript Whisperer

3) is cool but it feels like a code smell.

Everything else is gold!