Is There a Downside to Using Es6 Template Literals Syntax Without a Templated Expression

Is there a downside to using ES6 template literals syntax without a templated expression?

The most significant reason not to use them is that ES6 is not supported in all environments.

Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.

Exclusive use of Template Literals in JavaScript?

We successfully use it in every location except import statements with Babel. It will throw an error there.

It makes it nice for extending code to drop in variables, much like always wrapping single parameter fat arrow functions with ( ) does.

We thought the same thing you did, and began using it everywhere instead of ' and it works. We also checked the MDN and there is nothing saying you can't use it, but it has some quirks such as indenting console.logs by preserving characters, but the short answer is JavaScript and 99% of libraries don't care about spaces or linebreaks, so its not necessary until you get into a wild use case.

Edit

We have since converted to use eslint-config-airbnb which by default, enforces usage of single quotations for everything, except JSX (which is double quote). It also enforces grave accents only when using template literals.

I consider this config fairly defacto-standard and its ruleset is extremely well-informed and backed by reason. I would recommend setting your proverbial clocks to it.

If you have any questions, definitely create an issue in the Airbnb GitHub. Target any questions to ljharb.

Defer execution for ES6 Template Literals

I can see three ways around this:

  • Use template strings like they were designed to be used, without any format function:

    console.log(`Hello, ${"world"}. This is a ${"test"}`);
    // might make more sense with variables:
    var p0 = "world", p1 = "test";
    console.log(`Hello, ${p0}. This is a ${p1}`);

    or even function parameters for actual deferral of the evaluation:

    const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;
    console.log(welcome("world", "test"));
  • Don't use a template string, but a plain string literal:

    String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\$\{p(\d)\}/g, function(match, id) {
    return args[id];
    });
    };
    console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));
  • Use a tagged template literal. Notice that the substitutions will still be evaluated without interception by the handler, so you cannot use identifiers like p0 without having a variable named so. This behavior may change if a different substitution body syntax proposal is accepted (Update: it was not).

    function formatter(literals, ...substitutions) {
    return {
    format: function() {
    var out = [];
    for(var i=0, k=0; i < literals.length; i++) {
    out[k++] = literals[i];
    out[k++] = arguments[substitutions[i]];
    }
    out[k] = literals[i];
    return out.join("");
    }
    };
    }
    console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));
    // Notice the number literals: ^ ^

Should we use backticks to quote string literals now?

Using Backticks for Strings allows to create Template Strings.

const create = word => `Hello ${word}`

console.log(create("World")); // Hello World

So this is a cleaner way to create/interpolate Strings. Since the transpiler/interpreter will turn that back into something like: "Hello" + word the impact on Performance should depend on the number of Strings to combine and the overall length of the String.

No matter which »type« of String you chose if you need the quoting characters in it, you need to escape them:

console.log(```) // SyntaxError
console.log(`\``) // `

So all in all, template Strings are great for templates, so use them for it if you like, but it wont make any difference, when it comes to escaping, plus, you have to escape $ signs, too.

Is there any case where single quote or double quote is still required for JavaScript since we have template literals (backtick quote)?

What I found is, the following can't use backtick

  1. Object declaration
                const headers2 = {
`Accept`: `application/json`,
`Content-Type`: `application/json`
};

This will error Uncaught SyntaxError: Unexpected template string


  1. Importing module
import React from `react`;

This will error stating Parsing error: Unexpected token

Not sure if my findings are legit or there are more cases. Feel free to share.

Updated
3. Using of use strict

    `use strict`;

The above is not functioning without any warning.

Is there a downside to using ES6 template literals syntax without a templated expression?

The most significant reason not to use them is that ES6 is not supported in all environments.

Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.

ES6 template literals vs. concatenated strings

If you are using template literals only with placeholders (e.g. `Hello ${person.name}`) like in the question's example, then the result is the same as just concatenating strings. Subjectively it looks better and is easier to read, especially for multi-line strings or strings containing both ' and " since you don't have to escape those characters any more.

Readability is a great feature, but the most interesting thing about templates are Tagged template literals:

let person = {name: 'John Smith'}; 
let tag = (strArr, name) => strArr[0] + name.toUpperCase() + strArr[1];
tag `My name is ${person.name}!` // Output: My name is JOHN SMITH!

In the third line of this example, a function named tag is called. The content of the template string is split into multiple variables, that you can access in the arguments of the tag function: literal sections (in this example the value of strArr[0] is My name is and the value of strArr[1] is !) and substitutions (John Smith). The template literal will be evaluated to whatever the tag function returns.

The ECMAScript wiki lists some possible use cases, like automatically escaping or encoding input, or localization. You could create a tag function named msg that looks up the literal parts like My name is and substitutes them with translations into the current locale's language, for example into German:

console.log(msg`My name is ${person.name}.`) // Output: Mein Name ist John Smith.

The value returned by the tag function doesn't even have to be a string. You could create a tag function named $ which evaluates the string and uses it as a query selector to return a collection of DOM nodes, like in this example:

$`a.${className}[href=~'//${domain}/']`


Related Topics



Leave a reply



Submit