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

How to space variables with concatenation on each side of a plus symbol so they aren't connected as one word?

hey. Im trying to concatenate two variables next to each other in a sentence ( using the + with a space on each side of it), but it keeps combining them together. Please help!

Sentence says: All of the wormswiggle into space in search of gold.

var questions = 3;
var questionsLeft = '[' + questions + ' questions left]';
var noun = prompt('Tell me a noun ' + questionsLeft);
questions -= 1;
questionsLeft = '[' + questions + ' questions left]';
var adjective = prompt('Tell me an adjective ' + questionsLeft);
questions -= 1;
questionsLeft = '[' + questions + ' questions left]';
var verb = prompt('Tell me a verb ' + questionsLeft);
var sentence ='<h2>All of the ' + noun  + verb + ' into space ' + ' in search of '  + adjective + '.</h2>';
alert('All finished!');
document.write(sentence);
Dave StSomeWhere
Dave StSomeWhere
19,870 Points

You can just stick a " " + after noun (add a space where you want it).

Cheo R
Cheo R
37,150 Points

You can also use backticks and interpolation template literals:

var questions = 3;
var questionsLeft = `[{questions} questions left]`;

2 Answers

Thanks Steven. That helped to see it in action

Steven Parker
Steven Parker
229,982 Points

As Dave suggested, you can just add a literal space where you need it. Perhaps it will be helpful to see the concept applied to your actual code. So for basic concatenation:

var sentence ='<h2>All of the ' + noun + ' ' + verb + ' into space in search of ' + adjective + '.</h2>';

Notice that to simplify the code a bit I also removed the concatenation between two literals and just made a larger literal (' into space in search of ').

And Cheo's suggestion of template strings will be covered in later courses, but here's an example (note the syntax should also include a dollar sign):

var sentence =`<h2>All of the ${noun} ${verb} into space in search of ${adjective}.</h2>`;