Print Name and Status
Today I learned about template literals in JavaScript - a feature that allows us to insert variables directly into strings using the ${} syntax.
Today I learned about template literals in JavaScript - the feature where you can insert variables directly into strings using ${}. It feels simple, but once you use it, it makes string building much cleaner.
At first, I used it in a simple way like this:
const currentDate = new Date();
console.log(`Hari ini tanggal ${currentDate}`);That prints the date and time info in JavaScript's default format, for example:
Better Date Format
The default output feels a bit messy and not very personal. So I looked for a more flexible way to format it. Here's an example:
const now = new Date();
const day = now.getDate();
const month = now.getMonth() + 1;
const year = now.getFullYear();
const hours = now.getHours();
const minutes = now.getMinutes();
console.log(`Today is ${day}/${month}/${year}, at ${hours}:${minutes < 10 ? "0" + minutes : minutes}`);The result looks cleaner and is easier to read:
Why do we use minutes < 10 ? "0" + minutes : minutes?
I was confused when I first saw this line:
minutes < 10 ? '0' + minutes : minutesIt is a ternary operator, basically a compact if-else.
If the minute is less than 10, it adds a zero in front, so 5 becomes 05. That way, the time format stays neat and consistent.
