简体   繁体   中英

How do template literals work in javascript?

I'm just curious as to how JS handles expressions inside template literals. On one hand,

console.log(`hi ${3>5}`); //false

meaning the logical expression is indeed evaluated, and

function myFunction()
{
      return("caca");
};

console.log(`${myFunction()}`);`

actually produces the desired "caca" meaning the function is executed just like the previous logical expression was evaluated, but

console.log (`${function() {return("caca");}}`); //returns function() {return("caca");}

does not. I know that marking the function expression as self-executing will actually run it, but I just wonder why the JS engine behaves this way. I know the JS engine doesn't care about my "intuition" but I intuitively assumed the function expression inside the template literal would be executed.

Well, if you were to evaluate the code inside the template literal that "doesn't work", you aren't actually running the function. Take, for example, this code:

function myFunction()
{
      return("caca");
};

On its own, this is a function, not the string "caca" . Only when you run the function does it return that value. In your template literal, you are just defining an anonymous function. To run it, you would need to do this:

console.log (`${(function() {return("caca");})()}`);

This runs the function after defining it, and logs the function's return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM