Hacker News new | ask | show | jobs
by dmitriid 2526 days ago
My personal opinion is that tagged template literals are the worst addition to Javascript [1]

As HN user stevebmark said [2]:

--- start quote ---

…we’ve learned not to write code in strings. You’d think this would be a fundamental law of software engineering

Writing code, not strings, means you can do everything to it that you can do to code. You can type check code. You can lint it. You can optimize it, compile it, validate it, syntax highlight it, format it with tools like Prettier, tree shake it…

--- end quote ---

[1] https://dmitriid.com/blog/2019/03/tagged-template-literals/

[2] https://news.ycombinator.com/item?id=18511943

2 comments

> You’d think this would be a fundamental law of software engineering

Agreed, but not for the reasons you quoted.

It should be a law of software engineering because when you're writing code, you aren't writing strings, you're writing a serialized and prettified form of a tree. So when you have two pieces of code you want to join together, you should join trees, not strings.

Breaking this law is precisely why things like SQL Injection even exist in the first place.

I think your blog post misses an important aspect of tagged template literals, which is that the first argument is an immutable object that is unique to the source location of the template. That doesn’t necessarily invalidate the rest of your argument, but it is a very powerful feature that is not really equivalent to anything else in JavaScript.
What do you mean by 'source location'? Why does this matter? I'm intrigued (and also suffering from conjunctivitis so excuse me if I'm being a bit dense and totally missed your point).
If you put a tagged template literal on line 42 in foo.js, every time the tagging function is called from there, the array of strings passed as the first argument is the same object. It’s unique for the source location of the template literal, so even if you paste the exact same code into bar.js, it will have a different object. So, the function can recognize that it is being called from the same location in the source. This has some interesting implications for meta programming and debugging.

I’m not sure that it matters so much to the discussion, but it is a completely unique feature, and really has to be mentioned when discussing what tagged template literals offer.

EDIT: Looked for a good reference - best detailed description I could find was here: https://exploringjs.com/es6/ch_template-literals.html#sec_im...

Never knew about this, and completely missed it when reading about them on exploringjs.

Thank you for the explanation!