javascript
Creating Strings
There are three common ways to create a string in Javascript:
- With single quotes, e.g. 'like this'
- With double quotes, e.g. "like this"
- With backticks, e.g. `like this`
The following example shows the three ways:
let name = 'Jeff'; let profession = "Ice Cream Scooper"; let newFlavor = "Quadruple Papaya Fudge"; let dream = `Inventor of the ${newFlavor} flavor of ice cream`;
Notice the last two lines do something new: string interpolation. The newFlavor variable is inserted into the backticks string.
If you were to alert the dream variable, you would see the changed string:
alert(dream); // ^ This prints: Inventor of the Quadruple Papaya Fudge flavor of ice cream
One reason you might use these different ways to create a string might be to contain other quote characters. For example, if your string contains single quotes, it would make sense to put it in double quotes. Otherwise, the only way to represent the single quotes would be to escape the characters. Escaping characters allows us to continue the string without closing it as it normally would when we match its opening character.
let single = 'I can put these "double quotes" in here'; let double = "I can put these 'single quotes' in here"; let backticks = `I can put either type of 'quotes' in "here"`; let escapeSingle = 'I could do that, or I could do \'this\' instead'; // ^ The single quotes within other single quotes are escaped. let escapeDouble = "\"This\" is also an option";