Let’s say I have a function that should return a HTML string with either <h1>
or <h2>
depending on whether a second argument is provided and true. Is it allowed to write it like this? (Notice that I’m assigning to level
inside of the template string, then reusing the assigned value for the end tag.)
function heading(str, level) {
return `<h${level = level ? '1' : '2'}>${str}</h${level}>`
}
I do realize that the sane way to write it would be to assign to level
on a separate line, then use that inside the template literal.
-
Is assignment of this kind is allowed inside a template literal?
-
Is there some official documentation or standard that documents this?
I have not been able to find any kind of documentation (MDN or otherwise) that even mentions that assignment work inside of template literals. According to my own experiments it seems to work just fine though, as long as I don’t initialize a variable (with let
, const
or similar) inside the template string. (Also, it seems to work regardless of whether 'use strict'
is used or not.)
6