Five small JavaScript tips
JavaScript
—
2021-01-27
This post has five small JavaScript tips, including how to improve readability when working with large numbers and how to truncate an array.
1. You can use _
when working with big numbers in JavaScript, use it to increase readability.
You can also use e notation.
const hardToRead = 10000000;
const easyToRead = 10_000_000;
const eNotation = 10e6;
2. Check if the tab running the JavaScript is in view using document.hidden
.
const tabIsInView = () => document.hidden;
console.log(tabIsInView());
//=> true
3. Always use triple equal, ===
, to compare the value and type when comparing values.
'7' == 7 //=> true
'7' === 7 //=> false
[] == 0 //=> true
[] === 0 //=> false
4. Use toFixed()
to convert a number to a string and round to a fixed number of decimals.
const number = 120.438723;
const twoDecimals = number.toFixed(2);
console.log(twoDecimals);
//=> 120.44
5. slice()
will let you truncate an array.
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const truncatedArray = array.slice(0, 4);
console.log(truncatedArray);
//=> [0, 1, 2, 3];