when you first start javascript building string often involves using the + operator.While this works quickly but it become messy and hard to read as code grows.
Before ES6, developers created strings like this:
let name = "Alice";
let age = 25;
let message = "Hello, my name is " + name + " and I am " + age + " years old."
This approach has several drawbacks:
- Hard to read: The sentence is broken into multiple parts.
- Error-prone: Easy to forget spaces or quotes.
- Messy with complex strings: Adding more variables makes it worse.
- Difficult for multi-line strings: Requires \n or awkward formatting. Template Literal Syntax
Template literals were introduced in ES6 and use backticks (`) instead of quotes.
javascriptHello, my name is Alice.
let message =;
Embedding Variables in Strings
Instead of breaking the string with +, you can directly insert variables using ${}:
`javascript
let name = "Alice";
let age = 25;
let message = Hello, my name is ${name} and I am ${age} years old.;
`
- Cleaner and easier to read
- Looks more like natural language
- No need to worry about spacing issues Multi-line Strings Made Easy: With traditional concatenation:
javascript
let text = "This is line one.\n" +
"This is line two.\n" +
"This is line three.";
With template literals:
javascriptThis is line one.
let text =
This is line two.
This is line three.;
Some Use cases
- Creating API URLs
javascripthttps://api.example.com/users/${userId}`;
let userId = 42;
let url =
`
- Generating HTML templates
let html = <div class="user">${name}</div>;
Logging and debugging
javascriptUser ${name} logged in at ${time}
console.log();
plaintext
`
Top comments (0)