A string is a type of variable. It represents a series of zero or more characters. Other variable types are numeric, boolean, and array variables.
A variable’s type defines what values it can hold and what can be done with it. For example, string variables can be split and joined to form new strings, and numeric variables can have mathematical operations performed on them.
Usage of Quotes to Define Strings
var myString = "this is a string!";
Single Line Strings
Single line strings can be defined using single or double quotes:
var myString = 'this is a string!'; var myOtherString = "this is a string too!";
Multi Line Strings
Strings spanning multiple lines can be defined using backticks instead of quotes:
var myString = `this is a string spanning several lines!`;
What are Escape Characters?
That’s all pretty simple, but there’s a problem – what if you want your string to contain the same quote character which was used to define the string?
var myString = "Some guy once said "To be or not to be", or something to that effect.";
The above code will produce a syntax error, as the quotes we wish to be included in the string are interrupting the correct usage of double quotes used to define the string.
var myString = "Some guy once said \"To be or not to be\", or something to that effect."; console.log(myString);
The above example will output the following to the console:
Some guy once said "To be or not to be", or something to that effect.
Escaping Escape Characters
Of course, you’ll probably also want to use a \ (backslash) character in your strings at some point too. Never fear, you can also escape the escape character:
var myString = "\\"; console.log(myString);
The above code will output the following to the console: