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


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

28,360 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.

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

<div starts with a single quote then comes a double quote, what does it mean?

Steve Gallant
Steve Gallant
14,873 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.