String Variables and Literals

Of all the JavaScript data types, you will probably work most often with the string data type.

Strings are simply any series of characters between quotes. Form element values are stored as strings, pathnames to files and images are referred to as strings, and almost all method parameters are strings. Below is an example of a string used as the parameter of the alert() method:
alert("Hello World")

Variables and Literals

The string, "Hello World" is an example of a string literal. It is considered a literal value because it is a raw string of quoted text. A string variable then, is a variable name that is assigned to a literal. Variables are used in place of string literals to make repeated references to the same string more efficient.

The exact same results can be achieved by using a variable which has been assigned to a literal as the parameter of the alert() method.
var stuff = "Hello World"
Note that even though a string value is quoted in JavaScript syntax, when the value is displayed via an alert, it will not have the quotes attached. To include quotes as part of a string, see the Escape Character lesson.

String or No?

Like form field values, many values are stored in their object or property - they're not written out in your script as string literals. So to a beginner, it is sometimes unclear whether or not a stored value is a string. To find out, just use the typeof operator with the alert method.

A great example of this is with the returned values of the location object and the location object's href property. Both refer to the URL in the browser window, making you think both values are the same type.
<a href="javascript: alert(location)">alert the value of the location object</a>

<a href="javascript: alert(location.href)">alert the value of location object's href property</a>
Both return the URL of this page. Now lets test the type of data the returned values are:
<a href="javascript: alert(typeof location)">what kind of value is returned by location?</a>

<a href="javascript: alert(typeof location.href)">what kind of value is returned by location.href?</a>
As you can see, one value is an object, and the other is a string. Later in this tutorial and especially in the string method tutorials, you'll see why this is important. But for right now, just keep in mind that values which look the same may actually be different types.
>>String Literals and String Variables
>>Nesting Quotes And The Escape Character
>>String Concatenation and String Operators
>>Creating Line Breaks
>>Strings To Numbers: Data Type Conversion
>>Strings and The Write Method


View Source | Home | Contact