DEV Community

loading...
Cover image for 7 Useful Javascript Tips

7 Useful Javascript Tips

Victor Chan
Fullstack dev
・Updated on ・2 min read

7 Useful Javascript Tips

Without further ado, lets dive into it:

  1. Filtering falsy values:

If you have an array of values, you can filter out falsy values(null undefined 0 "" NaN false ) with Boolean()

//Example 1
const x = ["a","",3,false,"hello",undefined]
const y = x.filter(Boolean);

console.log(y) // ["a",3,"hello"]

//Use it like this
myArray.filter(Boolean);

Enter fullscreen mode Exit fullscreen mode

2. Floor a decimal number instead of Math.floor()
Useful for when you want to show whole numbers
(Edit: This removes decimal numbers so it actually acts like Math.ceil() for negative numbers, credits to @veljko94pesic)

//Example 1 
const x = 1.5 
const y = ~~x   
console.log(y) // Equals 1  
Enter fullscreen mode Exit fullscreen mode
//Example 2
const a = -1.5
const b = ~~a
console.log(b) // Equals -1
Enter fullscreen mode Exit fullscreen mode
//Example 3 
const z = ~~2.73123 
console.log(z) // Equals 2   

Enter fullscreen mode Exit fullscreen mode

3. Implicit boolean coercion
Change a value into a boolean (Instead of Boolean(value))

const x = {} 
const y = !!x //Equals true 
console.log(y) // true

Enter fullscreen mode Exit fullscreen mode

4. Last items in an array
You can use Array.slice() with negative indicies to count backwards.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8]  

Enter fullscreen mode Exit fullscreen mode
console.log(array.slice(-1)); // Equals [8]

console.log(array.slice(-2)); // Equals [7, 8]

console.log(array.slice(-3)); // Equals [6, 7, 8]

Enter fullscreen mode Exit fullscreen mode

5. Implicit number coercion using +

Putting a + in front of any value will attempt to change it to a number, similar to Number(value). This can also be used for Date objects as an alternative to Date.getTime()

//Example 1 
const x = new Date() 
const y = +x 
console.log(y) //Equals 1591887393586 (gives back time in ms)

Enter fullscreen mode Exit fullscreen mode

Useful for doing this (get time 10 seconds later)

const z = new Date(+new Date() + 10 *1000)
console.log(z) //Equals 1591887403586

Enter fullscreen mode Exit fullscreen mode

6.Method parameter validation
Lets you throw an error if input not given

const isRequired = () => { throw new Error('param is required'); };

const print = (value = isRequired()) => {   
    console.log(`${value}`)  
};  

Enter fullscreen mode Exit fullscreen mode
print(2);// Equals  2  
print()// Throws error  
print(null)// Equals null

Enter fullscreen mode Exit fullscreen mode

7.Swallow errors for promise all

Normally, Promise.all() will throw if any promises inside its array rejects. We can ignore errors by using map and catch for each promise.

const promiseArray = [
    Promise.reject(null),
    Promise.resolve(100),
    Promise.resolve("More data"),
    Promise.reject(new Error('Throw an error here'))
];

Enter fullscreen mode Exit fullscreen mode
//Map and catch for promises 
//And just console.log them 
const all = await Promise.all(
    promiseArray.map(p => p.catch(console.log))
)

Enter fullscreen mode Exit fullscreen mode

Thats all!
Do you have any Javascript tips?
Feel free to leave them as a comment below πŸ™‚

Discussion (16)

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 Author

Thanks, I'll give it an edit!

Collapse
lexswed profile image
Lex Swed

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 Author

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 Author

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 Author

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 Author

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