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
Arikaturika Tumojenko
8,897 PointsHow come you can put a number inside of a string with Javascript? can you give another example of how this works?
So let's me see if I get this correct. If you have a variable with the value of a number, you can concatenate it with a text string by placing the number variable in quotes? I can't wrap my head around the syntax of
var questionsLeft = '[' + questions + ' questions left]';
What's with the two pluses and how ' + questions + ' = 3?
2 Answers
Steven Parker
243,656 PointsIn your example, the number variable is not in quotes. There are quotes around the bracket ('['), and there are quotes around the ending phrase that includes the closing bracket (' questions left]').
When the JavaScript system sees that the numeric variable questions is being concatenated (+) with two strings, it performs what's known as type coercion, taking whatever value it holds and creating a string that represents that value.
So, the whole process goes like this:
'[' start with this string
+ questions convert questions to a string and concatenate it
+ ' questions left]' then concatenate this string
var questionsLeft = finally put the new string into the variable questionsLeft
I hope that clears it up a bit.
-sp
Arikaturika Tumojenko
8,897 PointsOh, now it makes sense. I was looking at the quotes all wrong. So when Dave said at a point that Javascript allows you to put a number inside a string he meant inside the whole string, no? Thank you!