DEV Community

Cover image for 7 Useful Javascript Tips

7 Useful Javascript Tips

Victor Chan on June 18, 2020

7 Useful Javascript Tips Without further ado, lets dive into it: Filtering falsy values: If you have an array of values, you can f...
Collapse
 
tovvaar profile image
˗ˏˋトバーˎˊ˗

On the last one perhaps there is a formatting error, since comment is affecting the const declaration:

//Map and catch for promises 
//And just console.log them 
const all = await Promise.all(
    promiseArray.map(p => p.catch(console.log))
)
Collapse
 
__victorchan profile image
Victor Chan

Thanks, I'll give it an edit!

Collapse
 
alvechy profile image
Alex Vechy

Thanks for sharing. It's good to know tricks even if it's not good to use them.
Example with implicit number coercion on Date is misleading. I'll be disappointed to see it in some produciton code.

new Date(+new Date() + 10 *1000)
// vs
new Date(Date.now() + 10 * 1000)
Collapse
 
__victorchan profile image
Victor Chan

Ahh true, that looks much more understandable. Thanks for the feedback!

Collapse
 
westim profile image
Tim West

From my experience, 2, 3 & 5 aren't significantly faster and make the code harder to read/understand. I avoid these by enabling eslint rules to disable implicit coercion.

Tip 7 can soon be replaced by the new ES2020 Promise.allSettled() feature.

Collapse
 
__victorchan profile image
Victor Chan

True, readability is a good point. Thanks for the feedback!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Shorter way to filter falsey values:

myArray.filter(x=>x)
Collapse
 
veljko94pesic profile image
veljko94pesic

Maybe you should mention that double tilde operator (~~) for negative numbers acts like Math.ceil() function, in your example:

const x = -1.5
const y = ~~x

console.log(y) // Equals -1

Nice article btw :)

Collapse
 
__victorchan profile image
Victor Chan

Awesome, didn't know about that. Thanks for sharing!

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Nice - I learned one there. I've mostly used |0 to floor numbers but I like the ~~ prefix style a lot too. I like the parameter validation one too. That's nice.

Collapse
 
__victorchan profile image
Victor Chan

Oh awesome, didn't know about that one, thank you!

Collapse
 
shriji profile image
Shriji

Nice!

Collapse
 
duhbhavesh profile image
Bhavesh Kasturi

Nice!

Collapse
 
kpulkit29 profile image
Pulkit Kashyap

Awesome read

Collapse
 
abdulrayhman profile image
Abdul Rehman

Informative in short way Thanks

Collapse
 
jabo profile image
Jabo • Edited

Awesome and helpful tips! Definitely learned something from this