To pass variables to JavaScript in Express.js, we put a property in the context.
For instance, we write
app.get("/test.js", (req, res) => {
res.set("Content-Type", "application/javascript");
res.render("testPage", { myVar: "foo" });
});
to call res.render
to render the testPage template.
We call it with an object with the variables we want to pass to the template.
Then we render the variable value with
<script>
const myVar = <%- JSON.stringify(myVar) %>;
</script>
Conclusion
To pass variables to JavaScript in Express.js, we put a property in the context.