Primitive Data Types, Arrays, Loops, and Conditions - Part 2 [con't]
Strings
A string is a sequence of characters used to represent text. In JavaScript, any value placed between single or double quotes is considered a string. This means that 1 is a number but "1" is a string. When used on strings, typeof
returns the string "string".
Here's an example of a number used in string context:
If you put nothing in quotes, it's still a string (an empty string):
string concatenation
operation and it returns the two strings glued together.
The dual function of the +
operator can be a source of errors. Therefore, it is always best to make sure that all of the operands are strings if you intend to concatenate them, and are all numbers if you intend to add them. You will learn various ways to do so further in the chapter and the book.
String Conversions
When you use a number-like string as an operand in an arithmetic operation, the string is converted to a number behind the scenes. (This works for all operations except addition, because of addition's ambiguity)
A lazy way to convert any number-like string to a number is to multiply it by 1 (a better way is to use a function called parseInt()
, as you'll see in the next chapter):
If the conversion fails, you'll get NaN
:
A lazy way to convert anything to a string is to concatenate it with an empty string.
Special Strings
Some strings that have a special meaning, as listed in the following table:
String | Meaning | Example |
---|---|---|
\ |
\ is the escape character. When you want to have quotes inside your string, you escape them, so that JavaScript doesn't think they mean the end of the string. If you want to have an actual backslash in the string, escape it with another backslash. |
>>> var s = 'I don't know'; This is an error, because JavaScript thinks the string is "I don" and the rest is invalid code. The following are valid: >>> var s = 'I don\'t know'; >>> var s = "I don\'t know"; >>> var s = "I don't know"; >>> var s = '"Hello", he said.'; >>> var s = "\"Hello\", he said."; Escaping the escape: >>> var s = "1\\2"; s; "1\2" |
\n |
End of line | >>> var s = '\n1\n2\n3\n'; >>> s " 1 2 3 " |
\r |
Carriage return | All these:>>> var s = '1\r2'; >>> var s = '1\n\r2'; >>> var s = '1\r\n2'; Result in: >>> s "1 2" |
\t |
Tab | >>> var s = "1\t2" >>> s "1 2" |
|
\u followed by a character code allows you to use Unicode |
Here's my name in Bulgarian written with Cyrillic characters:>>> "\u0421\u0442\u043E\u044F\u043D" |
There are some additional characters which are rarely used: \b
(backspace), \v
(vertical tab), and \f
(form feed).