What does this ${} syntax do?

Question

From this lesson, you need to understand what ${} syntax is. How does it work and how is it used?

Answer

Sometimes called template literals or template strings, this format is another way to type out a string making use of `` (called a backtick or grave accent). It can be used easily as a replacement.

'Hello'
"Hello"
`Hello`

These are all valid strings, however it adds a couple additional features that make it very useful. First by using backticks, words with an apostrophe can be easily incorporated into the string without use an \ escape character. (note that in the example the second line is valid)

'I haven't seen that'
'I haven\'t seen that'
`I haven't seen that`

Secondly it allows for the introduction of a variable without concatenating (which is what you will use it for in this lesson). This is done using ${var} to add the variable string in-line to your current string.

let captain = 'Jean-luc'
console.log('Paging ' + captain + ' to report to the bridge.')
console.log(`Paging ${captain} to report to the bridge.`)

This is especially helpful if you wish to print out complex statements comparing various variables for example.

Hope this helps, please discuss below. This concept is introduced in Introduction to Javascript - String Interpolation.

3 Likes

What does the tt${}: (I replaced grave accent ` as tt to prevent markup) mean in console.log(tt${crewMember}: ${spaceship.crew[crewMember].name}tt)?

3 Likes

I’m puzzled. The examples introduce formatting/syntax that are new to me but go unexplained. Why are the backticks necessary in the console.log statement, and where do the dollar signs come from? (Maybe that has been explained in very early lessons that I finished a long time a go, but I’ve reviewed every lesson now that I’ve returned to learning javascript, star). Also: where does this dollar sign come from all of a sudden? Why is ‘crewMember’ surrounded with accolades at first and then with square brackets?
Update (while writing): after reviewing earlier lessons, it appears that these back ticks and dollar signs are explained in the ‘Variables’ lesson, at ‘8. String interpolation’. I don’t think they have made an appearance in any subsequent lesson until now. I may not be the first person who’s thrown off by their sudden reappearance.

26 Likes

${} is just a lot cleaner to insert variable in a string then using +:

let x = 5;
console.log("hello world " + x + " times");
console.log(`hello world ${x} times`);

for ${} to work, the string needs to be enclosed in backticks.

17 Likes

I think it would be a lot more helpful for people who are trying to learn JS through these lessons to introduce new concepts instead of just throwing them at people and hoping that they will go to the forums to investigate. Template literals or the fact that a ‘for…in’ loop iterator returns a string were not explained in this or the previous lessons which created a lot of unnecessary confusion.

Correction: They do mention that keys are strings in Lesson 2 of the Module and introduce template literals at the very start of the course however it would be good to repeat that in a ‘Don’t forget that keys are strings!’ form that some educational books use in the margins. It also seems that some people don’t really understand or grasp what a datatype is aside from the superficial visual distinction of it being in quotation marks. Maybe an additional explanation would be good when introducing them.

As well, I think it would be good to add that a for…in loop only iterates over the keys of an object and it knows nothing about the object otherwise. This would clear up people’s assumptions that if you can iterate over the keys of an object then you must be able to do other things with it.

18 Likes

Template literals were introduced in module 1:

https://www.codecademy.com/courses/introduction-to-javascript/lessons/variables/exercises/string-interpolation-ii?action=resume_content_item

Not sure if this is new since your post, however.

3 Likes

im kinda confused on why you have to define the variable twice like (just as an example)

for (let crewD in spaceship.crew) {
console.log(${spaceship.crew[crewD].name}: ${spaceship.crew[crewD].degree})
}

spaceship.crew and crewD are together why?
why repeat the output twice
it looks like your saying spaceship.crew.spaceship.crew
why?

That is not the case.

we loop over all the crew members (captain, medic, etc) and log there name and degree to the console

The crew[crewD] helps to select each specific crewmember. Each dot is like a pathway. So its “the spaceship” -> "crew’ -> which crew? [crewD] -> “name”, and again but to get to the degree.

1 Like

I think I’ve finally figured this out, hope this helps anyone that has difficulty. In step two it wants a result of “name: degree” from executing the for in loop.

My solution was:

for (let crewAndDegree in spaceship.crew) {
    console.log(`${spaceship.crew[crewAndDegree].name}: ${spaceship.crew[crewAndDegree].degree} `);
}; 

What they really want is: “spaceship.crew.name”: “spaceship.crew.degree” . Just put the variable name just before what you really want executed/displayed. Please correct me if this is an incorrect way to think about this.

3 Likes

Why is nothing explained in the lesson? Is how future lessons are going to be?

3 Likes

This was a rough one. The template literals were introduced earlier, but not reinforced since, so their reintroduction threw me for a loop.

I think this lesson was too hard and probably the for…in needed another step or two to show how it worked.

3 Likes

we did pass string interpolation, instead of writing
ex:
‘My name is’ + name + ‘etc’

'My name is' ${name} 'etc'

but what about Colon symbol in between {} : {}

${}    :     ${}
       ^

There is not a single word about Colon between string interpolation
I’ve searched everywhere. What does that mean what does it do ?
does it act like a ternary operator like this > func ? (true) : (false)

1>0? (true) : (false)

The colon is just literally a colon. Its part of the string. Its unrelated to string interpolation.

I was affraid of thinking of it like that as it wasn’t captured in " : "
so its a string
thanks

@catower - Question regarding the different ways to output strings. If using backticks is the most flexible, why would I ever just use single quotes? What’s the advantage to the first ways of outputting strings using quotes or doublequotes?

This is one of the areas where JavaScript is frustrating for me. I’d like to know 1 right way to do something, which is a lot easier to remember, than 3 or 4 alternatives that also all get the job done.

Often you need to know multiple ways to do something, and choice the best option. This is not JS specific.

well, when backticks/template literals where introduced in 2015, browser support wasn’t great. So if you wanted to use template literals, you would have to transpile to es5.

Given template literals/grave accents where introduced later, its still good to know about quotes or double quotes, given you might run into them in a legacy project or transpiled code

1 Like