I became quite fond of using template literals instead of string literals in most situations even when a simple string literal would suffice. The benefits include that I do not have to think about special cases (quotes, newlines), can use interpolation later, and reduced cognitive load of deciding what literal to use.
When teaching JavaScript, I saw that students can get confused when templates are introduced after string literals. If we start with them, they are quite close to how strings work in other languages with string interpolation like Ruby, Python, or Kotlin.
Later, I discovered that I can use template literals almost everywhere where I'd otherwise would use a string literal. Based on my experimentation and reading of the spec, there are only two situations where this substitution is not possible:
Case 1: Import / Export clause
import defaultExport from `module-name`;
import { `string name` as alias } from `module-name`;
export * from `module-name`;
export { variable1 as `string name` };
// SyntaxError: Unexpected token
There is currently no workaround for this.
Suggestion: add NoSubstitutionTemplate to allowed values of ModuleSpecifier and ModuleExportName
Case 2: Object literal key
const obj = {
foo: 1,
`bar baz`: 2,
// SyntaxError: Unexpected template string
};
The workaround in this situation is probably something like this:
const obj = {
[`bar baz`]: 2,
};
The benefit of the workaround is that it naturally supports interpolation.
Suggestion: Add NoSubstitutionTemplate
to allowed values of LiteralPropertyName
Possibly, object literal could support any template literal as a key to serve as a shorthand for the computed property name.
Notes
It seems that this change would be straightforward and would not intervene with existing functionality.
It's clear to me why import and export clauses would break if we allowed substitution in the module names, that is why I suggest to use NoSubstitutionTemplate
. This would be its first independent use.
I'm not sure what would be the performance impact of checking that the template has no substitutions. This would also probably need a special error type.
I understand that this stylistic choice would not be generally adopted, I still think that it is a legitimate one.
What are your thoughts? Is this worth pursuing? Is there some pitfall I missed?