const singleQuoteString = 'This is a string wrapped in double quotes'; const doubleQuoteString = "This is a string wrapped in double quotes";
// These are all strings const character = 'a'; const word = 'hello'; const sentence = 'Hello world!'; const symbols = '!@#$'; const numberString = '1';
Note that a number wrapped in quotes is considered a string by the computer, and is not the same as a number that is not wrapped in quotes. There are some instances where they can be used interchangably, but as a general rule you should think of them as being different.
// These values look similar, but are different types const numberString = '1'; const number = 1;
If a string contains one or more single quotes (like an apostrophe), you should wrap it in double quotes to avoid errors. If you use single quotes in that situation, the computer will think the string ends early. Likewise, if a string contains double quotes, you should wrap it in single quotes to avoid errors.
// Mixing quotes const singleQuoteString1 = 'This "string" is cool'; const doubleQuoteString1 = "I should've known";
Alternatively, you can escape the single quote or double quote character using a backslash (like
// Escaping quotation marks const singleQuoteString2 = 'I should\'ve known'; const doubleQuoteString2 = "This \"string\" is cool";
To concatenate (or combine) strings, you can use the plus sign:
// Concatenate string literals const newString = "Hello " + "world"; // newString now equals "Hello world" // Concatenate strings using variables const firstString = "Hello "; const secondString = "world"; const firstPlusSecondString = firstString + secondString; // firstPlusSecondString now equals "Hello world"
If you try to combine two strings that contain numbers, the strings are combined, instead of added together.
const numberString = '1' + '1'; // numberString now equals '11', not '2' or 2
If you try to add a number to a string, the number is converted into a string and the strings are combined.
const numberString = '1' + 1; // numberString now equals '11', not '2' or 2 const otherExample = 'hello' + 1; // otherExample now equals 'hello1'
If you have a string stored inside a variable, you can also combine it with another string using the
+= operator, like this:
let greeting = 'hello'; greeting += ' world'; // greeting = 'hello world'
+= operator takes the string on the right, adds it to the string inside the variable, and stores the new value inside the same variable.
Try the following statements in the console:
'String in single quotes' "String in double quotes" 'This "string" is cool' "I should've known" 'I should\'ve known' "This \"string\" is cool" "Hello " + "world" '1' + '1' '1' + 1
const firstString = "Hello "; const secondString = "world"; const firstPlusSecondString = firstString + secondString;
String literals on MDN