Today I Learned - Rocky Kev

TIL JS Template Literal Shortcuts

POSTED ON:

TAGS:

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);

reference


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.