Which of these five items are strings?
'Hello'
'Goodbye'
'G'
' '
''
Quotation marks
The first two are clearly strings, we've already worked with similar constructions and mentioned that strings are sets of characters.
Any single character between parentheses is a string. The empty string '' is also a string. So everything inside the quotation marks can be considered a string, even if it is a space, one character, or no characters at all.
In previous lessons, we enclosed strings in single quotes, but you can also use double quotes:
// Coding airbnb standard recommends
// using single quotes where possible
console.log("Dracarys!");
Imagine you want to print a string: Dragon's mother. The apostrophe before the letter s and a single quote are the same symbols. Let's print it:
console.log('Dragon's mother');
// Uncaught SyntaxError: missing ) after argument list
This program won't work. For JavaScript, the string begins with a single quote and ends after the letter n. Then comes some characters: s mother without quotes, which are not a string. And then there is one quote opening a sting which is never closed: ');. This code is syntactically incorrect (you can see it by the way the code is highlighted).
It's a good idea here is to use double quotes. This version of the program will work correctly:
console.log("Dragon's mother");
Now the interpreter knows that the string begins with a double quote, so it should end with a double quote too. And the single quote inside has become the part of the string.
It works the other way too. If you want to use double quotes inside a string, you should enclose the string in single quotes. And the number of quotes in a string doesn't matter.
Now, what if we want to create a string like this?
Dragon's mother said "No"
There are single and double quotes here. What can we do in this case? You need to somehow tell the interpreter to consider each quote as a part of the string, and not as its beginning or an end.
To do this, you have to use an escape character. In our case, the character that starts and ends a string is either a single or a double quote, depending on the part of the code. Use a backslash \ before the character you want to escape.
// Only " is escaped, because in this code
// double quotes have a special meaning
console.log("Dragon's mother said \"No\"");
// => Dragon's mother said "No"
Look closely: we had to use \ for double quotes to escape them, and not for the single quote (apostrophe) because the string is written in double quotes. If the string were written in single quotes, the escape character would be used before the apostrophe, not before double quotes.
// \ won't be printed if it's followed by a normal character,
// not a special one
console.log("Death is \so terribly final");
// => Death is so terribly final
But what if you want to print the backslash? Just like any other special symbol, it escapes using a backslash too.
console.log("\\");
// => \
Self-test: what will be printed?
console.log("\\ \\ \\\\ \\\ \'\"");
Escape sequences
Imagine you want to print a dialogue between the Mother of Dragons and her child:
- Are you hungry?
- Aaaarrrgh!
If you print a string with this text:
console.log('- Are you hungry?- Aaaarrrgh!');
then you'll see:
- Are you hungry?- Aaaarrrgh!
Not quite what we were looking for. The strings are written one after the other, it doesn't start a new line. We need to tell the interpreter to "press enter" as it were. In other words, it needs to put a line break after the question mark. You can do this with the new line symbol '\n'.
console.log('- Are you hungry?\n- Aaaarrrgh!');
The result:
- Are you hungry?
- Aaaarrrgh!
\n is a special symbol. It's often referred to as LF (Line Feed, sometimes as line break or newline) in documentation. You may have initially thought it was a misprint, since there are two symbols - \ and n, but this isn't the case. To the computer, this is no more than an invisible symbol to tell it to go to the next line. Proof:
// We haven't studied it yet, but you should know the truth
// Below is code that returns the length of a string
'a'.length; // 1
'\n'.length; // 1 !!!
'\n\n'.length; // 2 !!!
Why is it done in this way? \n is just a way to write a line break symbol. That's why line feed is just one character, just invisible. And it's also why this problem has arisen. There had to be a way of representing it using a keyboard. And since the number of keyboard characters is limited and they're all dedicated to very important things, special characters are entered using these escape sequences.
The Line Feed symbol is not something specific to programming. Anyone who has ever typed on a computer has used the line feed by clicking Enter. Many editors can display these invisible characters, you can use this feature to see where they are (though it's only for display, these characters are invisible, they've no graphical representation):
- Hi!¶
- Oh, hey!¶
- What's up?
The device that outputs the corresponding text takes this character into account. For example, when the printer reaches the line feed, it pulls the paper up one line, and the text editor brings all subsequent text down one line as well.
\n is an example of an escape sequence. Although there are dozens of these characters, only a few of them are common in programming. Besides line feed, there is also indents (which you get from pressing Tab) and carriage return (Windows only). Programmers often need to use \n line break to format text properly.
console.log('Gregor Clegane\nDunsen\nPolliver\nChiswyck');
The result:
Gregor Clegane
Dunsen
Polliver
Chiswyck
Note:
It does not matter what comes before or after
\n, whether it's a character or an empty string. The line feed will be detected and executed either wayRemember that a string can contain a single character or none at all. Additionally, a string can only contain
\n. Analyze the following example:console.log('\n'); console.log('Dunsen'); // => // => // => DunsenFirst the interpreter outputs the string "line feed", and then the normal string.
Why are there two empty lines before the Dunsen line instead of one? The point is that
console.log()automatically adds a line feed to the end when it outputs a value. So, we explicitly typed one line feed, passing this escape character as an argument in the function, and the second line feed is added automatically by the function itself.One more example:
console.log('Polliver'); console.log('Gregor Clegane'); console.log(); console.log('Chiswyck'); console.log('\n'); console.log('Dunsen'); // => Polliver // => Gregor Clegane // => // => Chiswyck // => // => // => DunsenNow you understand enough to figure out why the result was formed in this way.
If we need to print
\nas a text (two separate characters), we can use the escape character, adding another\at the beginning. I.e., the sequence of\nwill be printed as characters\andnfollowing each other:console.log('Joffrey loves using \\n'); // => Joffrey loves using \n
A small but important note about Windows. Windows uses \r\n by default to enter a line break. This combination works well in Windows but creates problems when copied to other systems (for example, when the development team includes both Windows and Linux users). The point is that the sequence \r\n has a different interpretation depending on the encoding chosen (we discuss it later). For this reason, it's common among developers to always use \n without \r, since it means that LF is always interpreted the same way and works fine on any system. Remember to configure your editor to use \n.
Concatenation
In web development, programs use strings constantly. Everything we see on websites is represented as text in one way or another. This text is most often dynamic, it's made up of different connected pieces. In programming, the operation of joining one string to another is called concatenation.
// The operator is the same as for adding
// but it has different semantics (meaning)
console.log('Dragon' + 'stone');
// => Dragonstone
Strings always concatenate in the same order in which the operands are written. The left operand becomes the left part of the string, and the right one becomes the right part.
Here are a few more examples:
console.log('Kings' + 'wood'); // => Kingswood
// Reverse word order
console.log('road' + 'Kings'); // => roadKings
// Any string can be concatenated
console.log("King's" + 'Landing'); // => King'sLanding
As you can see, strings can concatenate even if they are written in different quotes.
In the last example, the name of the city has a misprint: King's Landing should be written with a space. But there were no spaces at the beginning of our strings, and the spaces left and right of the + don't matter because they are not part of the strings.
There are two ways to fix this:
// Both ways are functionally the same
// Put space in the end of the left part
console.log("King's " + 'Landing'); // => King's Landing
// Put space in the beginning of the right part
console.log("King's" + ' Landing'); // => King's Landing
A space is also a symbol. The more spaces you put, the wider the indentation will be:
console.log("King's " + ' Landing'); // => King's Landing
console.log("King's " + ' Landing'); // => King's Landing