Search code examples
javascripttemplate-strings

Why use the templatestring expression a=`${a}` in javascript?


I was looking at some javascript code and noticed a line using the template string backticks:

a=`${a}`

However, this does not seem to have any effect to me as the variable a contains a string.

Is this simply a NOP or is there string value for a that would make the result differ from the original value?


Solution

  • If a is not a string, doing this will convert the variable to a string, by invoking the .toString() available on the object's prototype:

    function templateString(d) {
      return `${d}`;
    }
    
    console.log(templateString('foo bar'));
    console.log(templateString(1337));
    console.log(templateString(false));
    console.log(templateString(undefined));
    console.log(templateString({ 'foo': 1337, 'bar': 'baz' }));
    console.log(templateString(['foo', 'bar', 'baz']));
    console.log(templateString(function(x) { return x; }));
    console.log(templateString(new RegExp('\\w+')));