JavaScript - Single quote, double quotes and backtick strings?
There are three ways a string could be defined in JavaScript. There is no particular difference between single quote and double quote strings. But, which to use can depend on situation.
Single quote, double quotes
The only difference is that it is required to escape "
or '
depending on which quote is being used.
Examples
// Wrong choice
let stringSingleQuote = 'I\'m inside single quote';
let stringDoubleQuote = "He said, \"Work is Worship\"";
let htmlDoubleQuote = "<h1 class=\"some-class\">Some text</h1>";
// Below is easier
let stringSingleQuote = "I'm inside single quote";
let stringDoubleQuote = 'He said, "Work is Worship!"';
let htmlDoubleQuote = '<h1 class="some-class">Some text</h1>';
Backtick(`) strings or template strings
We would need to escape backticks.
let withBacktick = `I have backtick(\`).`;
// I have backtick(`).
console.log(withBacktick);
The power of backtick in JavaScript
let title = `Backtick explanation`;
let bodyText = "I'll explain a complex string.";
let complexString = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>${title}</title>
</head>
<body>
<h1>${bodyText}</h1>
<h2>${1 + 2}</h2>
<h2>${title === 'none' ? (1 + 2) : "I'll come"}</h2>
</body>
</html>`
console.log(complexString);
See carefully what gets printed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Backtick explanation</title>
</head>
<body>
<h1>I'll explain a complex string.</h1>
<h2>3</h2>
<h2>I'll come</h2>
</body>
</html>
The above must explain the use of template or backtick strings.
Tag function
Now take following code as an example
function translate(strings, ...values) {
//[ 'I am ', ' to ', '.' ]
console.log(strings);
//[ 'going', 'New Delhi' ]
console.log(values);
return 'Translated text';
}
let city = 'New Delhi';
let activity = 'going';
let translated
= translate`I am ${activity} to ${city}.`;
//prints 'Translated text'
console.log(translated);
In reality translate
function can do actual translate to
some language and return translated text. Currently a constant string is
being returned.
Comments
Post a Comment