Logo LIBR
Halo

Portfolio

Back to Blog
5 min read
Challenge Day 1June 5, 2025

Print Name and Status

JavaScript, Template Literals
Syifa Fauziyah Arizal

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:

JavaScript
const currentDate = new Date();
console.log(`Hari ini tanggal ${currentDate}`);

That prints the date and time info in JavaScript's default format, for example:

Today is Sun Jun 16 2025 21:41:00 GMT+0700 (Western Indonesia Time)

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:

Improved Date Formatting
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:

Today is 05/6/2025, at 21:41

Why do we use minutes < 10 ? "0" + minutes : minutes?

I was confused when I first saw this line:

Ternary Operator
minutes < 10 ? '0' + minutes : minutes

It 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.

Key Takeaways

Use new Date() to get the current time, break it into date components, and style the output using a ternary operator for a cleaner result. Template literals with ${} syntax make string interpolation much easier and more readable than plain concatenation.

More to read