7 Useful Javascript Tips
Without further ado, lets dive into it:
- 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);
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
//Example 2
const a = -1.5
const b = ~~a
console.log(b) // Equals -1
//Example 3
const z = ~~2.73123
console.log(z) // Equals 2
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
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]
console.log(array.slice(-1)); // Equals [8]
console.log(array.slice(-2)); // Equals [7, 8]
console.log(array.slice(-3)); // Equals [6, 7, 8]
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)
Useful for doing this (get time 10 seconds later)
const z = new Date(+new Date() + 10 *1000)
console.log(z) //Equals 1591887403586
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}`)
};
print(2);// Equals 2
print()// Throws error
print(null)// Equals null
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'))
];
//Map and catch for promises
//And just console.log them
const all = await Promise.all(
promiseArray.map(p => p.catch(console.log))
)
Thats all!
Do you have any Javascript tips?
Feel free to leave them as a comment below π
Top comments (16)
On the last one perhaps there is a formatting error, since comment is affecting the const declaration:
Thanks, I'll give it an edit!
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.
Ahh true, that looks much more understandable. Thanks for the feedback!
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.
True, readability is a good point. Thanks for the feedback!
Shorter way to filter falsey values:
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 :)
Awesome, didn't know about that. Thanks for sharing!
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.Oh awesome, didn't know about that one, thank you!
Nice!
Nice!
Awesome read
Informative in short way Thanks