Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics Working with Strings Combine and Manipulate Strings

John MacDougall
John MacDougall
2,184 Points

cant figure this out.

app.js
const firstName = "john";
const lastName = "Mac";
const role = 'developer';
const msg = firstName + ` `lastName + `:` + ` `role + `.`
Dina Deljanin
Dina Deljanin
10,386 Points

It's not returning the string as you wanted, right, 'john Mac: developer'?

String concatenation is tricky, especially when we do it this way. This would be the solution. Notice how you have to add the variable AND the space?

const msg = firstName + ` ` + lastName + `:` + ` ` + role + `.`

But remembering each space... it's cumbersome. So here comes the Template Literal. You could write your sentence as you normally would, without having to remember to add spaces. You plug in your variables like this: ${str}.

And your code would look like this:

const msg = `${firstName} ${lastName}: ${role}.`

2 Answers

If you want to combine the strings, the easiest method is to use backquotes. You will put all the variables in side of parentheses and instead of using quotation marks, you use backquotes. to properly use the variables you must type a dollar sign then a set of curly braces. (like so ---> ${variable name here} <--- ). The cool thing about this method, is that you can use spaces, symbols and characters without the worry of manually adding the strings together

const firstName = "john";
const lastName = "Mac";
const role = 'developer';
const msg = (`${firstName} ${lastName}: ${role}.`);

if you want to manually add the strings together, try something like this.

const firstName = "john";
const lastName = "Mac";
const role = 'developer';
const msg = (firstName + ' ' + lastName + ': ' + role + '.');

( the reason your code did not work, is because you left out a plus sign in-between lastName and the space, you did not have any parenthesis starting from, in the msg variable, firstName to the end of the line, and you left out a semi-colon at the end of line four. Hope this helps. Have a good week :)

John MacDougall
John MacDougall
2,184 Points

Thank you. I'm afraid of going bald from pulling my hair out on this stuff.