Contents
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
JavaScript template literals, introduced in ES6, are a powerful feature for string manipulation. They are delimited with backtick (`) characters and provide three main capabilities:
- Multi-line strings
- String interpolation
- Tagged templates
Template Literals: Basic Usage
String Interpolation
The most common use case is string interpolation using ${expression}
syntax:
|
|
Multi-line Strings
Template literals preserve whitespace and line breaks:
|
|
Expression Evaluation
Template literals can evaluate expressions:
|
|

The Problem with Template Literals in URLs
While template literals are convenient, they can cause significant issues when used for URL construction, especially with query parameters. Let’s examine why:
Common Anti-pattern
|
|
This approach has several problems:
- Special Characters: Characters like
&
,?
,=
, and spaces are not properly encoded - Array Handling: Arrays are converted to comma-separated strings
- Type Coercion: Objects are converted to
[object Object]
Real-world Example of Issues
|
|
The Solution: URLSearchParams
URLSearchParams
is the proper way to handle URL query parameters in JavaScript. It automatically handles:
- URL encoding
- Special characters
- Array parameters
- Multiple values for the same parameter
Basic Usage
|
|
Advanced Usage
|
|
Working with Arrays
|
|
Best Practices for URL Construction
- Always use URLSearchParams for query parameters
- Handle special characters properly
- Consider using a URL construction library for complex cases
- Validate parameters before construction
- Use TypeScript for type safety
TypeScript Example
|
|
Common Pitfalls to Avoid
Direct string concatenation
1 2
// ❌ Don't do this const url = '/api/cities?country=' + country + '&page=' + page;
Template literals for URLs
1 2
// ❌ Don't do this const url = `/api/cities?country=${country}&page=${page}`;
Manual encoding
1 2
// ❌ Don't do this const url = '/api/cities?country=' + encodeURIComponent(country);
Conclusion
While template literals are a powerful feature in JavaScript, they should not be used for URL construction. URLSearchParams
provides a robust, built-in solution that handles all the edge cases and special characters correctly. By following these best practices, you can avoid common pitfalls and create more maintainable, reliable code.
Remember:
- Use
URLSearchParams
for query parameter handling - Consider TypeScript for type safety
- Validate parameters before construction
- Test edge cases with special characters and arrays
✨ Thank you for reading! If you found this guide helpful, please share it with others. Your feedback and suggestions are always welcome in the comments section.