Print Name and Status
Today I learned about template literals
in JavaScript — you know, that thing where you can insert variables directly into strings using ${}
. Kinda mind-blowing at first 😄
At first, I just used it in a simple way like this:
const currentDate = new Date();
console.log(`Hari ini tanggal ${currentDate}`);
Yep, this shows the date and time info in JavaScript's default format, like:
Better Date Format
But… it feels kinda messy and not that personal, right? So I found a more flexible way where you can customize it however you want. 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 way cleaner and easier to read:
🤔 Why do we use minutes < 10 ? "0" + minutes : minutes
?
I was kinda confused when I first saw this line:
minutes < 10 ? '0' + minutes : minutes
But I finally got it: it's a ternary operator, basically like a mini if-else.
Basically: if the minute is less than 10 (like 5), it'll automatically add a zero in front ("05") so it doesn't look weird. Imagine writing 03:7
instead of 03:07
— yeah, kinda awkward. This makes it way more readable and aesthetic.