Are JavaScript template literals guaranteed to call toString()?

房东的猫 提交于 2020-11-24 18:13:49

问题


const num = 42
const str = `My number is ${num}`

In this code what guarantee do I have about the conversion of num to a string ?

Is it guaranteed to just call its toString() method or could the conversion be done in another way ?


回答1:


Untagged templates use the ECMAScript ToString() abstract operation. The logic of template literal evaluation is spread over several sections which makes it difficult to follow, so I'll just post a link to it: https://tc39.es/ecma262/#sec-template-literals-runtime-semantics-evaluation

ToString(argument) uses a table instead of algorithmic steps, so I'll write out some pseudocode here:

switch (Type(argument)) {
  case 'Undefined':
    return 'undefined';
  case 'Null':
    return 'null';
  case 'Boolean':
    return argument ? 'true' : 'false';
  case 'Number':
    return Number::toString(argument);
  case 'String':
    return argument;
  case 'Symbol':
    throw new TypeError();
  case 'BigInt':
    return BigInt::toString(arugment);
  case 'Object':
    return ToString(ToPrimitive(argument, 'string'));
}

As you can see, no js execution happens at all for primitive values, the engine internally creates a string representation. For objects, we go into the ToPrimitive() algorithm.

ToPrimitive(input, PreferredType) will try to get the Symbol.toPrimitive method from input, and if it's present, call it with the given PreferredType hint. If input does not have a Symbol.toPrimitive property, it falls back to OrdinaryToPrimitive.

OrdinrayToPrimitive(O, hint) will try to call the toString and valueOf methods. If hint is 'string', it try to call toString method first, otherwise it will try to call the valueOf method first. If either of those methods are present and they don't return an object, their return value will be used. If neither are present or they both return objects, a TypeError will be thrown.

So to answer your original question, converting 42 will not call any other methods. The engine will internally create a string representation ('42'), and use that.




回答2:


Yes. If either value is not a string, it’ll be converted to a string using the usual rules. For example, if action is an object, its .toString() method will be called.

Read the full article from mozilla https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/




回答3:


Yes, it is a function of Object Primitive as described in MDN

Edit: ECMA specification is expression as described here.

Again in MDN - Template literal is written:

The default function just concatenates the parts into a single string



来源:https://stackoverflow.com/questions/62516921/are-javascript-template-literals-guaranteed-to-call-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!