Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.
Extracting UNIX Timestamps in JavaScript
We can get the UNIX timestamp of a Date
instance with the +
operator.
For instance, we can write:
+new Date(2020, 0, 1)
Then we get 1577865600000.
Also, we can use the getTime
method to do the same thing:
new Date(2020, 0, 1).getTime()
Then we get the same thing returned.
The date can also be parsed if it’s in YYYY-MM-DD format.
So we can write:
new Date('2020-01-01').getTime()
And we also get the same thing.
The timestamp is in the number milliseconds since January 1, 1970 12AM UTC.
So we can divide the returned number by 1000 to convert it to seconds.
Combining Array Values into One
We can use the reduce
method to reduce array entries into one result.
For instance, if we have:
const cart = [{price: 10}, {price: 40}, {price: 20}];
Then we get can the total price from the cart
by writing:
`const reducer = (total, item) => total + item.price;const total =` cart`.reduce(reducer, 0);`
Then total
is 70 since we combined all the cart
entries’ price
properties by adding their values together.
Detect if a Document is Ready
We can detect if a page is loaded completely with the document.readyState
property.
For instance, we can write:
if (document.readyState === 'complete') {
//...
}
to detect if a page is fully loaded and then do something.
We can also check the state periodically using:
let stateCheck = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(stateCheck);
// document ready
}
}, 100);
Then we can check the loading state of the page every 100 milliseconds until it’s ready.
In the if
block, we call clearInterval
to end the timer so we’ll stop checking for the readyState
.
Also, we can listen to the readystatechange
event with:
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
// document ready
}
}
This is better than creating a timer and running it until the ready state changes.
Calculate the Maximum or Minimum Value of an Array
We can pass in as many values into the Math.max
or Math.min
methods to check for the max or min values of the array.
For instance, we can write:
const max = Math.max(1, 2, 3);
to return the maximum value or:
const min = Math.min(1, 2, 3);
to return the minimum value.
To pass in an array, we can use the spread operator:
const max = Math.max(...[1, 2, 3]);
or:
const min = Math.min(...[1, 2, 3]);
Or we can use apply
as follows:
const max = Math.max.apply(undefined, [1, 2, 3]);
or:
const min = Math.min.apply(undefined, [1, 2, 3]);
apply
takes the value of this
as the first argument, which is undefined
since Math.max
and Math.min
are static methods.
The 2nd argument is an array of arguments that we want to pass in as arguments into the array.
Destructuring in Function Parameters
We can destructure object parameters with the destructuring syntax.
For instance, we can write:
const greet = ({ name, lastName }) => {
console.log(`hi, ${name} ${lastName}`);
};
We get the object’s name
and lastName
properties with the destructuring assignments.
Then we can call it by calling:
greet({ name: 'jane', lastName: 'doe' })
We can also set a default value for the destructured variables.
For instance, we can write:
const greet = ({ name = 'jane', lastName = 'smith' }) => {
console.log(`hi, ${name} ${lastName}`);
};
Then when we call it by writing:
greet({})
Then name
is 'jane'
and lastName
is 'smith'
since we didn’t set the value of either property.
Prevent Changing Built-in Prototypes
We can call Object.freeze
to prevent changing objects, which include built-in prototypes.
So we can write:
Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
Object.freeze(Function.prototype);
to prevent changing any built-in prototypes.
Conclusion
We can prevent changing built-in prototypes with Object.freeze
.
Also, we can use the spread operator or apply
to call a function with an array of arguments.
There are also various ways to get a UNIX timestamp.