Declare a String in JavaScript JavaScript String Declaration

Like other JavaScript variables, you do not have to declare strings before being able to use them in your scripts. But declaring all variables makes your scripts easier to understand and maintain. Some JavaScript libraries even require all variables to be declared before they can be used.

Three Ways to Declare Strings in JavaScript

You can declare JavaScript strings either by using the "new String()" string constructor, by equating a declared variable to quoted text, or by assigning the return value of methods that return strings.

JavaScript String Constructor

We can explicitly declare a string using "new String()" to create the string in memory: this is the JavaScript string constructor function. An optional string argument can also be passed to the constructor.

// Declare string variable with string constructor
var carter1 = new String("I learn JavaScript");

// Declare an empty string
var carter2 = new String();
alert( "|"+ carter2 +"|" );

We first declared an empty string: the JavaScript interpreter now understands the variable to be of string data type, even if it has not yet been initialized. An empty string is an absence of text, but still text. Out last line of code displays an empty string enclosed between pipe characters: the pipe characters are not needed, but help you see the limits of the empty string. JavaScript empty string

Quoted Text String Assignment

Unlike other programming languages, JavaScript accepts both 'single quotes' and "double quotes" to indicate strings. (JavaScript doesn't have a character data type to be opposed to the string data type: all strings are an object.)

// Declare a string with single quotes
var carter3 = 'I learn JavaScript';

// Declare the same string with double quotes
var carter4 = "I learn JavaScript";

// Ensure resulting strings are identical
alert( carter3 === carter4 );

We declared above two strings: both have the same assigned value, first single-quoted, than double-quoted. Our last line of code confirms that both strings have exactly the same value, and are of the same type: JavaScript strings declaration

The JavaScript identity operator (===) tests for actual identity, rather than simple equality. From our example: not only are the two strings equal in value, they are also both of the same type (String).

Here are a couple more strings: (don't let the values fool you)

var carter5 = "23"; // This is a string, not a number
var carter6 = "true"; // This is a string, not a boolean

Anything JavaScript value enclosed in single- or double-quotes is a string

Implicit String Declaration

JavaScript also lets you create strings indirectly, by assigning the "result" of a method which returns a value of String data type:

// Create an string from a method's return value
var arlene = new Array( "I", "learn", "JavaScript" );
var carter = arlene.join(" ");

We indirectly created a string by using the Array.join() method; several other JavaScript methods return a string value. As illustration, the string returned by the Array.join() method is identical to the one declared below.

var carter = new String("I learn JavaScript");

Declaring strings with escaped characters

When you declare a string, the content of that string variable consists of the characters between the bounding single-quotes or double-quotes: so, how do you declare strings containing single quotes or double-quotes? Easy: either declare the string using the other quote to enclose the quote you want:

// Enclose your string declaration with the other quote
var carter1 = "Today is Megan's birthday";
var carter2 = 'A "string" with double-quotes';

…Or escape the quote inside the string value:

// Place a backslash inside the string value:
var carter = 'Today is Megan\'s birthday';

By the same token, if you want to declare a string that contains a new line (which will cause problems in many scenarios), you can simply use the escaped lowercase "n" in your string declaration:

var carter = "A line \n And another line...";

…which results, when displayed in an alert(), for example, as a two-line string. (We surrounded the newline character with spaces only for visual clarity.)

Why should you initialize declared strings?

While JavaScript lets you use "uninitialized" variables, it is good programming practice to initialize variables you declare (strings or otherwise) before using them. A string variable that has been declared, but not initialized, will hold the special value of NULL (as any other type of uninitialized JavaScript variable).

To avoid hard-to-troubleshoot errors in your scripts, develop the habit of initializing any JavaScript string you declare, if only by setting its value to the empty string (""), as follows:

var carter = ""; // We just declared an empty string...

Since JavaScript lets you use single- or double-quote for strings, the following code is equivalent, and will also declare an empty string:

var carter = ''; // Empty string declaration, with single quotes

Tip: the empty string has a length property of zero. It is essentially empty, but since the JavaScript interpreter now knows that the variable is of type "string", it allows access to string properties and methods, like the length property — which measures the number of characters contained in a string variable.

Lifespan of JavaScript Strings

Declared strings remain available to the JavaScript interpreter for the life of your script, or for the scope of the string variables — whichever ends first.

// Declare a global string:
var string1 = "test1";

function doesNothing() {
  // Declare a string inside a function:
  var string2 = "test2";
}

// Works fine, this is a global string variable
alert(string1);

// Does not work: that string was declared inside the function
alert(string2);

The string variable we declared at the top of the script ("string1") is visible in the entire script: it has a "global scope". The string we declared inside the body of the function "doesNothing()", however, is only visible inside the function: that variable's scope is the function's body - it does not exist before the function is executed, and it is flushed from memory after exiting the function.

Local variables vs. global variables

In other words, any string you declare inside a loop, a function, custom objects, etc. - will only exist and be accessible from within that scope.

The reason global variables (strings and other JavaScript objects) are visible to the whole script is because they stay in memory, and are only "destroyed" (flushed from memory) once the user navigates to way from the current web page. To make your scripts as memory-efficient as possible, you should avoid declaring global variables except where absolutely necessary.

Declaring strings in JavaScript vs. declaring strings in other popular web development programming languages like PHP or ASP.NET

In a programming language like C#, single quotes are reserved for single-character strings, and using them to declare a multi-character string will return a compiler error; the JavaScript interpreter does not have any preference, and only the convention of using double-quotes first* could influence your choice.

A programming language like PHP lets you declare strings with either single- and double-quotes: strings you declared with double-quotes will be sent to the PHP interpreter to be parsed for PHP code, while single-quoted strings are treated as string literals (and thus not parsed by the interpreter). JavaScript handles strings you declared with single-quotes and double-quotes in exactly the same way - no difference in handling, and no difference in performance either.

* When attaching a string-containing inline JavaScript event for example — notice the single-quotes enclosed inside double-quotes:

<button onclick="alert('Hello!')">Click me</button>