JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,609 Points

String

html += '<div style="background-color:' + rgbColor + '"></div>'; Please explain anyone , how inverted commas are used here. I think a variable can't be placed inside a string , but here "rgbColor" is used in between inverted commas.

2 Answers

andren
andren
28,375 Points

The example you posted does mix a lot of different single and double quotes together which makes it hard to follow but the variable is actually outside the string. The quotes surrounding it are used to end and start the strings that are on either side of it. Take a look at the code with some color highlighting:

html += '<div style="background-color:' + rgbColor + '"></div>'

The first ' single quote starts the string and then the second single quote ' ends the string. Then the rgbColor variable is concatenated to the variable using the + operator. Then another string is concatenated which starts and ends with a single quote.

The double quotes " within the string is just treated as normal text since they hold no special meaning in a string that is started with single quotes.

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,609 Points

I understood little bit, but I still have that why double quote is used in '<div style="background-color:' and '"></div>'

Steve Gallant
Steve Gallant
14,874 Points

The double quote is actually part of the string in this case, rather than a string delimiter. It is surrounding the value of the background-color property within the div tag.