Template literal vs String

Sorry, I feel like the explanation in the course was too vague and I couldn’t understand when to use literals or why to use… what is the difference between template literal vs strings? and last, why do I need to have the $ and {}?

Thank you, I would appreciate if someone could help me out.

Kind Regards,
Pedro

Hi Pedro,
I’m new to this myself, but I’ll try to help. In JavaScript, strings are a data type that wraps a series of characters in quotes. You can place data you have defined elsewhere in strings by using concatenation or template literals. Both accomplish the same goal, but template literals are a newer way to do this introduced in ES6. Personally, I find it easier to type using template literals. You can do the same with concatenation though. I think you’ll find there are often multiple ways to do the same thing in JavaScript. Hopefully this helps!

If anybody out there has corrections/additions, please chime in! I am sure I have some things to learn on the subject.

Adam

4 Likes

py3064491710 explained it fine but there were no examples so:

Template literals are not a thing only in javascript, they are prevalent in a lot of langauges like php or c#,
The reason why you need ${} is so javascript can actually sense when you want to use a variable, you can argue {} would have been better, but that’s just how they went about it. It’s mainly just so you don’t need to append 15 different strings or 15 “\n”

Example:

const str = "https://" + baseURI + ".com/" + param + "/entries";

//vs

const str = `https://${baseURI}.com/${param}/entries`
2 Likes

Thank you guys, both answers complemented each other and that makes sense now.