DEV Community

Cover image for 7 neat tricks for JS that you probably did not know

7 neat tricks for JS that you probably did not know

Tapajyoti Bose on August 28, 2022

Got tired of learning and want to get some cool tricks up your sleeve to earn the right to show off? You have come to the right place. Here are nea...
Collapse
 
decker67 profile image
decker • Edited

Think about 0 and "" with && and ||, the are also falsy and sometimes you do not want that. Thats the reason for ?? I would think.

Also sometimes nice but dangerous: monkey patching.

const array = [1, 2, 3]
array.x = 42
Enter fullscreen mode Exit fullscreen mode

Gives also no error for value types like string and number, but looses the value.

Better forget it, its bad style. ;-)

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Yeah I agree, it's NOT a recommended approach of resizing arrays. Added that just to showcase that it's also a setter which most people don't know

Collapse
 
innocentdevii profile image
Dipesh Raichana

I think it is a best way to make the array empty. This can be used array.length = 0 in place of array = []because prior one is faster than the later one.

Thread Thread
 
decker67 profile image
decker

We should not use the fastes method but the method who is understood.

Collapse
 
decker67 profile image
decker

Thats not monkey patching.

Collapse
 
r4e profile image
Richie Permana

Wth? length is also a setter?
My whole life is a lie...

Collapse
 
devfarouqk profile image
Umar Sulaiman Mailafiya

Man...
You never know. 😂Life is a lie in general. But we move..

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

For "Replace all" you can also just use the replaceAll method - which could be considered more readable.

Collapse
 
umamahesh_16 profile image
Umamaheswararao Meka

_Readable numbers _ is something which I never knew about, thanks a lot for that !!!

Collapse
 
tusharshahi profile image
TusharShahi • Edited

One more :
Swapping 2 array elements.

const arr = [1,2];
[arr[1],arr[0]] = [arr[0],arr[1]];
console.log(arr); //[2,1]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
incrementis profile image
Akin C.

Hi Tapajyoti Bose,

thank you for your article.
I already knew two of the 7 tricks when reading your article.
The other five are pretty neat in my opinion :D!

Collapse
 
vishal590 profile image
vishal

first one is called grouping integers

Collapse
 
citronbrick profile image
CitronBrick

The array length setter was really surprising.

Collapse
 
crossroadspharmacy profile image
Marian Davis

Hi! Very useful tips.
Thank you very much for sharing. 🙏
Already used some of your advises...

Collapse
 
ili profile image
iliya khoshnodi

It's great