Categories
JavaScript Tutorials

String Type

The String data type represents a sequence of zero or more 16-bit Unicode characters. Strings can be delineated by either double quotes (“) or single quotes (‘), so both of the following are legal:

var firstName = "Nicholas";
var lastName = 'Zakas';

Unlike PHP, for which using double or single quotes changes how the string is interpreted, there is no difference in the two syntaxes in ECMAScript. A string using double quotes is exactly the same as a string using single quotes. Note, however, that a string beginning with a double quote must end with a double quote, and a string beginning with a single quote must end with a single quote. For example, the following will cause a syntax error:

var firstName = "Nicholas';

The length of any string can be returned by using the length property as follows:

var text = 'hello';
alert(text.length);
 //outputs 5


The Nature of Strings

Strings are immutable in ECMAScript, meaning that once they are created, their values cannot change. To change the string held by a variable, the original string must be destroyed and the variable filled with another string containing a new value, like this:

var lang = "Java";
lang = lang + "Script";

Here, the variable lang is defined to contain the string “Java”. On the next line, lang is redefined to combine “Java” with “Script”, making its value “JavaScript”. This happens by creating a new string with enough space for 10 characters and then filling that string with “Java” and “Script”. The last step in the process is to destroy the original string “Java” and the string “Script”, because neither is necessary anymore.