Skip to content
Share
Explore

Template Literals

Template literals are a way to concatenate strings in JavaScript.
They are a more modern way to do this than using the `+` operator. They allow you to embed expressions inside the string.
Có từ ES6.
const name = 'John';
// Concatenation using the + operator
const greeting = 'Hello, ' + name;

// Using template literals
const greeting = `Hello, ${name}`;
Instead of quotes, we use backticks to surround the string. Then we can use the `${}` syntax is used to embed expressions inside the string.
You can put any valid JavaScript expression inside the curly braces.
// a fn that return a string in both ways
const formatDate = (timestamp) => {
const date = new Date(timestamp);
// Concatenation using the + operator
return date.toLocaleDateString() + ' at ' + date.toLocaleTimeString();
// Using template literals
return `${date.toLocaleDateString()} at ${date.toLocaleTimeString()}`;
};

// let's create a dummy object
const note = {
title: 'Discuss project roadmap',
timestamp: Date.now(),
};

// Let's now output the function expression to the console using template literals
console.log(`Last edited: ${formatDate(note.timestamp)}`);

Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.