TIL JS Template Literal Shortcuts
POSTED ON:
TAGS: javascript
Declaring strings:
const single = 'Hi there, I am a single quoted string.';
const double = "But me, I am a double quote string";
//contains both single and double
const template = `Hi there, I'm called "a template literal". Neat!`;
Escaping quotes:
const single = 'Do not and don\'t mean the same thing.';
const double = "Avoid using \"double quotes\" for emphasis.";
const template = `I use backticks (/` /`) to declare myself.`;
Expression Interpolation:
const interpolation1 = "You can do this" + nameOfReader + " with the help of your friends.";
const interpolation2 = `But with backticks, my dear ${nameOfReader}, you don't need the plus sign.`;
Line breaks:
const linebreak1 = 'You can do line breaks\n
by using the backslash\n
to help out.'
const linebreak2 = `With backticks, you don't need '\n'
them. but notice how
there's no tab/spaces?`
Cool hacks --
TRIM:
const menuItem = (url, link) =>
`
<li>
<a href="${url}">${link}</a>
</li>
`.trim();
menuItem('https://google.com', 'Google');
TERNARY OPERATORS:
const age = 19
const message = `You can ${age < 21 ? 'not' : ''} view this page`
console.log(message);
Related TILs
Tagged: javascript