JavaScript String Literals, Objects, Concatenation, Comparison
Here you will learn what string is, how to create, compare and concatenate strings in JavaScript.
String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in single or double quotation marks.
"Hello World"
'Hello World'
String value can be assigned to a variable using equal to (=) operator.
var str1 = "Hello World";
var str2 = 'Hello World';
A string can also be treated like zero index based character array.
var str = 'Hello World';
str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o
str.length // 11
Since, string is character index, it can be accessed using for loop and for-of loop.
var str = 'Hello World';
for(var i =0; i< str.length; i++)
console.log(str[i]);
for(var ch of str)
console.log(ch);
Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+) operator in JavaScript.
var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher ';
Include quotation marks inside string
Use quotation marks inside string value that does not match the quotation marks surrounding the string value. For example, use single quotation marks if the whole string is enclosed with double quotation marks and visa-versa.
var str1 = "This is 'simple' string";
var str2 = 'This is "simple" string';
If you want to include same quotes in a string value as surrounding quotes then use backward slash (\) before quotation mark inside string value.
var str1 = "This is \"simple\" string";
var str2 = 'This is \'simple\' string';
String object
Above, we assigned a string literal to a variable. JavaScript allows you to create a String object using the new keyword, as shown below.
var str1 = new String();
str1 = 'Hello World';
// or
var str2 = new String('Hello World');
In the above example, JavaScript returns String object instead of primitive string type. It is recommended to use primitive string instead of String object.
Caution:
Be careful while working with String object because comparison of string objects using == operator compares String objects and not the values. Consider the following example.
var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;
str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true
typeof(str1); // object
typeof(str3); //string
Learn about JavaScript string properties and methods in the next section.

- JavaScript string must be enclosed in double or single quotes (" " or ' ').
- String can be assigned to a variable using = operator.
- Multiple strings can be concatenated using + operator.
- A string can be treated as character array.
- Use back slash (\) to include quotation marks inside string.
- String objects can be created using new keyword. e.g.
var str = new String();
- String methods are used to perform different task on strings.