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.
Semicolon
Semicolons can be automatically inserted in JavaScript.
It inserts semicolons on the next line after code that breaks the current one.
Also, when the next line starts with a }
, a semicolon is inserted.
When the end of the source code file is reached, then the semicolon is added.
Semicolons are also inserted after the break
keyword.
It’s also added after the throw
and continue
keywords.
If we don’t add it ourselves, then the interpreter will insert it for us.
Manipulating Dates Easily with Moment.js
To make date manipulating easier, we can use moment.js
We can install it by adding a script tag or installing the package.
We can write:
<script src="https://unpkg.com/moment" />
or:
npm install moment
If we use the package, we can write:
import moment from 'moment'
To get the current date and time, we can write:
const date = moment();
To parse a date, we can write:
const date = moment(string);
It takes various formatting codes. They are:
YYYY
— 4 digits yearYY
— 2 digits yearM
— 2 digits month number without the 0MM
— 2 digits month numberMMM
— 3 letters month nameMMMM
— full month namedddd
— full day namegggg
— 4 digits week yeargg
— 2 digits week yearw
— week of the year without leading zeroww
— week of the year with leading zeroe
— day of week that starts with 0D
— 2 digits day number without the leading 0DD
— 2 digits day numberDo
— day number with ordinalT
— start of the time partHH
— 2 digit hours from 0 to 23H
— 2 digit hours from 0 to 23 without the leading 0kk
— 2 digit hours from 1 to 24k
— 2 digit hours from 1 to 24 without leading 0a/A
— am or pmhh
— 2 digit hours (12 hours time)mm
— 2 digit minutesss
— 2 digits secondss
— 2 digits seconds without leading 0S
— 1 digit millisecondsSS
— 2 digit millisecondsSSS
— 3 digits millisecondsZ
— timezonex
— UNIX timestamp in milliseconds
For instance, we can format date by writing:
moment().format("YYYY-MM-DD")
Moment.js comes with a few constants.
They are the following:
moment.HTML5_FMT.DATETIME_LOCAL
—‘YYYY-MM-DDTHH:mm’
moment.HTML5_FMT.DATETIME_LOCAL_SECONDS
—‘YYYY-MM-DDTHH:mm:ss’
moment.HTML5_FMT.DATETIME_LOCAL_MS
—‘YYYY-MM-DDTHH:mm:ss.SSS’
moment.HTML5_FMT.DATE
—‘YYYY-MM-DD’
moment.HTML5_FMT.TIME
—‘HH:mm’
moment.HTML5_FMT.TIME_SECONDS
—‘HH:mm:ss’
moment.HTML5_FMT.TIME_MS
—‘HH:mm:ss.SSS’
moment.HTML5_FMT.WEEK
—‘YYYY-[W]WW’
moment.HTML5_FMT.MONTH
—‘YYYY-MM’
We can validate a date with the isValid
method.
For instance, we can write:
moment('2020-13-32').isValid()
which returns false
, or:
moment('2020-01-23').isValid()
which returns true
.
Get the Relative Time String
We can use the fromNow
method to get the relative from the current date and time.
For instance, we can write:
moment("2020-11-23").fromNow()
and get ‘in 6 months’
.
We can pass true
to fromNow
, then it shows the difference without reference to the future or past.
So if we write:
moment("2020-11-23").fromNow(true)
Then we get ‘6 months’
.
Manipulating Dates
We can use the Moment.js add
and subtract
methods to add or subtract amounts from a date.
For instance, we can write:
moment('2020-11-23').add(1, 'days');
moment('2020-11-23').subtract(1, 'days');
The 2nd argument can have the following values:
years
quarters
months
weeks
days
hours
minutes
seconds
milliseconds
Inspect a JavaScript Object
There are various ways to inspect objects in JavaScript.
We can use the console.log
method to log an expression and get its return value.
For instance, we can write:
console.log(dog)
There’s also the console.dir
method to let us inspect any object.
For instance, we can write:
console.dir(dog)
JSON.stringify
is another way to let us inspect an object.
It’ll return a string.
For instance, given that we have:
const dog = {
color: 'white',
breed: 'poodle'
}
we can write:
console.log(JSON.stringify(dog))
which creates an unprettified string.
Then we get:
{"color":"white","breed":"poodle"}
logged.
To pretty-print the string, we can pass in 2 more arguments.
We write:
console.log(JSON.stringify(dog, null, 2))
and we get:
{
"color": "white",
"breed": "poodle"
}
Conclusion
Moment.js makes date manipulating easier than with the Date
constructor.
We can inspect expression values with console
and JSON.stringify
.