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.
Get the Current Timestamp
There are several ways to get the UNIX timestamp from a Date
instance.
The timestamp is a number of milliseconds from January 1, 1970, 12 AM UTC.
We can use the Date.now()
method to get the timestamp.
Then we get something like 1589399748029.
We can also use the new Date().getTime()
method.
new Date().valueOf()
does the same thing.
To express the timestamp in seconds, we just divide it by 1000.
So we can write:
Math.floor(Date.now() / 1000)
The Value of this
this
can take on different values depending on where it’s used.
Outside of an object, this
is always undefined
in strict mode,
Otherwise, it’s the global object.
this
will be bound to the object at the top level of the method.
For instance, if we have:
const person = {
name: 'james',
greet() {
console.log(`hi ${this.name}`)
}
}
Then when we call person.greet()
, we have 'hi james'
logged.
this
doesn’t bind to arrow functions. It’ll just take the value of this
outside.
We can also set the value of this
explicitly.
To do this, we can use the bind
method to do it.
For instance, we can write:
const joe = person.greet.bind({ name: 'joe' });
Then when we call joe
, we get 'hi joe'
.
bind
returns a function.
We can change the value of this
and call the function with the new this
with call
and apply
.
For instance, we can write:
person.greet.call({ name: 'joe' });
or:
person.greet.apply({ name: 'joe' });
The difference between the 2 is how they take arguments.
For instance, if we have:
const person = {
name: 'james',
greet(greeting) {
console.log(`${greeting} ${this.name}`)
}
}
Then we can call person.greet
by writing:
person.greet.call({ name: 'joe' }, 'hello');
Then we get 'hello james'
because we passed in 'hello'
as the first argument.
To call apply
, we pass the arguments as an array.
For instance, we write:
person.greet.call({ name: 'joe' }, ['hello']);
Then we get the same result.
In HTML event element handlers, this
is bound to the element.
For instance, if we have:
document.querySelector('button').addEventListener('click', function(e) {
console.log(this)
}
Then this
‘s value is the button.
Convert a String to a Number
There are many ways to convert a string to a number.
Number
We can convert a string to a number with the Number
function.
For instance, we can write:
const count = Number('123');
Then count
is '123'
.
parseInt
To parse a string into an integer, we can use parseInt
.
For instance, we can write:
const count = parseInt('123', 10)
The first argument is the string to convert and the 2nd argument is the radix.
Then we convert the string to the decimal.
As long as the number begins with a number, it’ll convert the numerical part.
If we have:
const count = parseInt('123 bottles', 10)
then we get 123.
parseFloat
To parse a string to a float, we can use parseFloat
.
For instance, we can write:
parseFloat('1.20')
Then we get 1.2.
Unary +
Also, we can use the +
operator to do the same thing as parseFloat
.
For example, we can write:
+'1.20'
and get the same thing.
Math.floor
Likewise, we can use Math.floor
to round a string to the floor of it.
We can pass in a string straight to the method and it’ll do the conversion for us.
For instance, if we write:
Math.floor('9.81')
and we get 9.
Use * 1
We can convert a string to a number by multiplying it by 1.
For example, we can write:
'9.20' * 1
and we get 9.2.
Format a Number to a Currency Value
JavaScript has a Intl.NumberFormat
constructor to convert a number to a currency value.
For instance, we can write:
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
const price = formatter.format(888);
Then we get “$888.00”
as the value of price
.
The style
is the formatting style, and we set that to 'currency'
to convert it to a currency string.
currency
is the currency we want to format the string to.
minimumFractionDigits
is the minimum number of decimal digits.
Conclusion
We can do many things with numbers.
We can format them to a currency string.
Also, there are many ways to convert a string to a number.