In this article, you will go over the differences between single/double-quoted strings and template literals, running through the various ways to declare strings of different shape, including multi-line strings and dynamic strings that change depending on the value of a variable or expression. You will then learn about tagged templates and see some real-world examples of projects using them.
This section will review how to declare strings with single quotes and double quotes, and will then show you how to do the same with template literals.
const single = 'Every day is a good day when you paint.'
A string can also be written with double quotes (
const double = "Be so very light. Be a gentle whisper."
The use of single- or double-quoted strings mostly comes down to personal preference and convention, but used in conjunction, each type of string only needs to escape its own type of quote:
// Escaping a single quote in a single-quoted string const single = '"We don\'t make mistakes. We just have happy accidents." - Bob Ross' // Escaping a double quote in a double-quoted string const double = "\"We don't make mistakes. We just have happy accidents.\" - Bob Ross" console.log(single); console.log(double);
The result of the
log() method here will print the same two strings to the console:
Output "We don't make mistakes. We just have happy accidents." - Bob Ross "We don't make mistakes. We just have happy accidents." - Bob Ross
Template literals, on the other hand, are written by surrounding the string with the backtick character, or grave accent (```):
const template = `Find freedom on this canvas.`
They do not need to escape single or double quotes:
const template = `"We don't make mistakes. We just have happy accidents." - Bob Ross`
However, they do still need to escape backticks:
const template = `Template literals use the \` character.`
Template literals can do everything that regular strings can, so you could possibly replace all strings in your project with them and have the same functionality. However, the most common convention in codebases is to only use template literals when using the additional capabilities of template literals, and consistently using the single or double quotes for all other simple strings. Following this standard will make your code easier to read if examined by another developer.
Now that you’ve seen how to declare strings with single quotes, double quotes, and backticks, you can move on to the first advantage of template literals: writing multi-line strings.
Does your business need an interactive website or app?
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.