Search code examples
javascriptjqueryinterpolation

Can you perform a ternary expression in a javascript string interpolation?


I have this variable :

var foobar = "Hi, my name is #{name}";

But if name is not defined at load of the page.. I'd like it to save "unknown" instead.

But writing something like this :

var foobar = "Hi, my name is #{typeof name === 'undefined' ? 'unknown' : name}";

Still returns the error, unknown variable name


Solution

  • Instead of making logic decisions within a string construct, do it outside for better performance and (far) more readable code:

    name = name||'unknown';