Skip to content
Advertisement

Variable declared inside template literal context problem

This code works fine in the global context:

console.log(`${text = "It works!", text}`);

But when you import it from another module (from html doc)

<script type="module" src="literal.js"></script>

or from another script

import "literal.js";

Then throw an error:

Uncaught ReferenceError: text is not defined

Advertisement

Answer

The template literal is a red herring. text = "It works!" is sufficient to reproduce this problem.

This will error:
<script type=module>
text = "It works!"
</script>

Modules automatically run in strict mode where assigning to undeclared variables is an error instead of an implicit global.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement