Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 118684 of Literals

  • Revision slug: JavaScript/Guide/Obsolete_Pages/Literals
  • Revision title: Literals
  • Revision id: 118684
  • Created:
  • Creator: user01
  • Is current revision? No
  • Comment Replaced note with template; 12 words added, 14 words removed

Revision Content

{{ mergedInto("en/Core_JavaScript_1.5_Guide/Core_Language_Features#Literals") }}

Literals

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

  • {{ Anch("Array Literals") }}
  • {{ Anch("Boolean Literals") }}
  • {{ Anch("Floating-Point Literals") }}
  • {{ Anch("Integers") }}
  • {{ Anch("Object Literals") }}
  • {{ Anch("String Literals") }}

Array Literals

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

The following example creates the coffees array with three elements and a length of three:

var coffees = ["French Roast", "Colombian", "Kona"];

Note An array literal is a type of object initializer. See Using Object Initializers.

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Array literals are also Array objects. See Array Object for details on Array objects.

Extra Commas in Array Literals

You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with spaces for the unspecified elements. The following example creates the fish array:

var fish = ["Lion", , "Angel"];

This array has two elements with values and one empty element (fish{{ mediawiki.external("0") }} is "Lion", fish{{ mediawiki.external("1") }} is undefined, and fish{{ mediawiki.external("2") }} is "Angel").

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList{{ mediawiki.external("3") }}. All other commas in the list indicate a new element.

var myList = ['home', , 'school', ];

In the following example, the length of the array is four, and myList{{ mediawiki.external("0") }} and myList{{ mediawiki.external("2") }} are missing.

var myList = [ , 'home', , 'school'];

In the following example, the length of the array is four, and myList{{ mediawiki.external("1") }} and myList{{ mediawiki.external("3") }} are missing. Only the last comma is ignored.

var myList = ['home', , 'school', , ];

Boolean Literals

The Boolean type has two literal values: true and false.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See Boolean Object for more information.

Integers

Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.

Octal integer literals are deprecated and have been removed from the ECMA-262, Edition 3 standard. JavaScript 1.5 still supports them for backward compatibility.

Some examples of integer literals are:

0, 117 and -345 (decimal, base 10)
015, 0001 and -077 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)

Floating-Point Literals

A floating-point literal can have the following parts:

  • A decimal integer which can be signed (preceded by "+" or "-"),
  • A decimal point ("."),
  • A fraction (another decimal number),
  • An exponent.

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12.

More succinctly, the syntax is:

[digits][.digits][(E|e)[(+|-)]digits]

For example:

3.14
2345.789
.3333333333333333333

Object Literals

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (CarTypes("Honda")); the third element, the special property, uses an existing variable (Sales).

var Sales = "Toyota";

function CarTypes(name) {
  if (name == "Honda")
     return name;
  else
     return "Sorry, we don't sell " + name + ".";
}

var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };

document.write(car.myCar); // Saturn
document.write(car.getCar); // Honda
document.write(car.special); // Toyota

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

var car = { manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda" };

document.write(car.manyCars.b); // Jeep
document.write(car[7]); // Mazda

Please note:

var foo = {a: "alpha", 2: "two"};
document.write(foo.a);    // alpha
document.write(foo[2]);   // two
//document.write(foo.2);  // Error: missing ) after argument list
//document.write(foo[a]); // Error: a is not defined
document.write(foo["a"]); // alpha
document.write(foo["2"]); // two

String Literals

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

  • "foo"
  • 'bar'
  • "1234"
  • "one line \n another line"
  • "John's cat"

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

  • "John's cat".length

You should use string literals unless you specifically need to use a String object. See String Object for details on String objects.

Using Special Characters in Strings

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

"one line \n another line"

The following table lists the special characters that you can use in JavaScript strings.

Character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\' Apostrophe or single quote
\" Double quote
\\ Backslash character (\).
\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXX The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.

Table 2.1: JavaScript special characters

Escaping Characters

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
document.write(quote);

The result of this would be:

He read "The Cremation of Sam McGee" by R.W. Service.

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

var home = "c:\\temp";

{{ PreviousNext("Core_JavaScript_1.5_Guide:Constants", "Core_JavaScript_1.5_Guide:Unicode") }}

{{ languages( { "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/字面表達", "es": "es/Gu\u00eda_JavaScript_1.5/Literales", "fr": "fr/Guide_JavaScript_1.5/Constantes_litt\u00e9rales", "ja": "ja/Core_JavaScript_1.5_Guide/Literals", "ko": "ko/Core_JavaScript_1.5_Guide/Literals", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Litera\u0142y", "zh-cn": "cn/Core_JavaScript_1.5_Guide/\u6587\u672c\u5316" } ) }}

Revision Source

<p>{{ mergedInto("en/Core_JavaScript_1.5_Guide/Core_Language_Features#Literals") }}</p>
<h3 name="Literals">Literals</h3>
<p>You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p>
<ul> <li>{{ Anch("Array Literals") }}</li> <li>{{ Anch("Boolean Literals") }}</li> <li>{{ Anch("Floating-Point Literals") }}</li> <li>{{ Anch("Integers") }}</li> <li>{{ Anch("Object Literals") }}</li> <li>{{ Anch("String Literals") }}</li>
</ul>
<h4 name="Array_Literals">Array Literals</h4>
<p>An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.</p>
<p>The following example creates the <code>coffees</code> array with three elements and a length of three:</p>
<pre class="eval">var coffees = ["French Roast", "Colombian", "Kona"];
</pre>
<p><strong>Note</strong> An array literal is a type of object initializer. See <a href="/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_Object_Initializers" title="en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_Object_Initializers">Using Object Initializers</a>.</p>
<p>If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.</p>
<p>Array literals are also Array objects. See <a href="/en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Array_Object" title="en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Array_Object">Array Object</a> for details on Array objects.</p>
<p><strong>Extra Commas in Array Literals</strong></p>
<p>You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with spaces for the unspecified elements. The following example creates the <code>fish</code> array:</p>
<pre class="eval">var fish = ["Lion", , "Angel"];
</pre>
<p>This array has two elements with values and one empty element (<code>fish{{ mediawiki.external("0") }}</code> is "Lion", <code>fish{{ mediawiki.external("1") }}</code> is <code>undefined</code>, and <code>fish{{ mediawiki.external("2") }}</code> is "Angel").</p>
<p>If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no <code>myList{{ mediawiki.external("3") }}</code>. All other commas in the list indicate a new element.</p>
<pre class="eval">var myList = ['home', , 'school', ];
</pre>
<p>In the following example, the length of the array is four, and <code>myList{{ mediawiki.external("0") }}</code> and <code>myList{{ mediawiki.external("2") }}</code> are missing.</p>
<pre class="eval">var myList = [ , 'home', , 'school'];
</pre>
<p>In the following example, the length of the array is four, and <code>myList{{ mediawiki.external("1") }}</code> and <code>myList{{ mediawiki.external("3") }}</code> are missing. Only the last comma is ignored.</p>
<pre class="eval">var myList = ['home', , 'school', , ];
</pre>
<h4 name="Boolean_Literals">Boolean Literals</h4>
<p>The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p>
<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See <a href="/en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Boolean_Object" title="en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Boolean_Object">Boolean Object</a> for more information.</p>
<h4 name="Integers">Integers</h4>
<p>Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.</p>
<p>Octal integer literals are deprecated and have been removed from the ECMA-262, Edition 3 standard. JavaScript 1.5 still supports them for backward compatibility.</p>
<p>Some examples of integer literals are:</p>
<pre class="eval">0, 117 and -345 (decimal, base 10)
015, 0001 and -077 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
</pre>
<h4 name="Floating-Point_Literals">Floating-Point Literals</h4>
<p>A floating-point literal can have the following parts:</p>
<ul> <li>A decimal integer which can be signed (preceded by "+" or "-"),</li> <li>A decimal point ("."),</li> <li>A fraction (another decimal number),</li> <li>An exponent.</li>
</ul>
<p>The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").</p>
<p>Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12.</p>
<p>More succinctly, the syntax is:</p>
<pre class="eval">[digits][.digits][(E|e)[(+|-)]digits]
</pre>
<p>For example:</p>
<pre class="eval">3.14
2345.789
.3333333333333333333
</pre>
<h4 name="Object_Literals">Object Literals</h4>
<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.</p>
<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>; the second element, the <code>getCar</code> property, invokes a function <code>(CarTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>Sales</code>).</p>
<pre class="eval">var Sales = "Toyota";

function CarTypes(name) {
  if (name == "Honda")
     return name;
  else
     return "Sorry, we don't sell " + name + ".";
}

var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };

document.write(car.myCar); // Saturn
document.write(car.getCar); // Honda
document.write(car.special); // Toyota
</pre>
<p>Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.</p>
<pre class="eval">var car = { manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda" };

document.write(car.manyCars.b); // Jeep
document.write(car[7]); // Mazda
</pre>
<p>Please note:</p>
<pre class="eval">var foo = {a: "alpha", 2: "two"};
document.write(foo.a);    // alpha
document.write(foo[2]);   // two
//document.write(foo.2);  // Error: missing ) after argument list
//document.write(foo[a]); // Error: a is not defined
document.write(foo["a"]); // alpha
document.write(foo["2"]); // two
</pre>
<h4 name="String_Literals">String Literals</h4>
<p>A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:</p>
<ul> <li>"foo"</li> <li>'bar'</li> <li>"1234"</li> <li>"one line \n another line"</li> <li>"John's cat"</li>
</ul>
<p>You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the <code>String.length</code> property with a string literal:</p>
<ul> <li>"John's cat".length</li>
</ul>
<p>You should use string literals unless you specifically need to use a String object. See <a href="/en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/String_Object" title="en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/String_Object">String Object</a> for details on String objects.</p>
<h5 name="Using_Special_Characters_in_Strings">Using Special Characters in Strings</h5>
<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p>
<pre class="eval">"one line \n another line"
</pre>
<p>The following table lists the special characters that you can use in JavaScript strings.</p>
<table class="fullwidth-table"> <tbody> <tr> <th>Character</th> <th>Meaning</th> </tr> <tr> <td>\b</td> <td>Backspace</td> </tr> <tr> <td>\f</td> <td>Form feed</td> </tr> <tr> <td>\n</td> <td>New line</td> </tr> <tr> <td>\r</td> <td>Carriage return</td> </tr> <tr> <td>\t</td> <td>Tab</td> </tr> <tr> <td>\v</td> <td>Vertical tab</td> </tr> <tr> <td>\'</td> <td>Apostrophe or single quote</td> </tr> <tr> <td>\"</td> <td>Double quote</td> </tr> <tr> <td>\\</td> <td>Backslash character (\).</td> </tr> <tr> <td>\<em>XXX</em></td> <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> </tr> <tr> <td>\x<em>XX</em></td> <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> </tr> <tr> <td>\u<em>XXXX</em></td> <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a class="internal" href="/en/Core_JavaScript_1.5_Guide/Unicode#Unicode_escape_sequences" title="en/Core JavaScript 1.5 Guide/Unicode#Unicode escape sequences">Unicode escape sequences</a>.</td> </tr> </tbody>
</table>
<p><small><strong>Table 2.1: JavaScript special characters</strong></small></p>
<h5 name="Escaping_Characters">Escaping Characters</h5>
<p>For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p>
<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p>
<pre class="eval">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
document.write(quote);
</pre>
<p>The result of this would be:</p>
<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service.
</pre>
<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p>
<pre class="eval">var home = "c:\\temp";
</pre>
<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Constants", "Core_JavaScript_1.5_Guide:Unicode") }}</p>
<p>{{ languages( { "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/字面表達", "es": "es/Gu\u00eda_JavaScript_1.5/Literales", "fr": "fr/Guide_JavaScript_1.5/Constantes_litt\u00e9rales", "ja": "ja/Core_JavaScript_1.5_Guide/Literals", "ko": "ko/Core_JavaScript_1.5_Guide/Literals", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Litera\u0142y", "zh-cn": "cn/Core_JavaScript_1.5_Guide/\u6587\u672c\u5316" } ) }}</p>
Revert to this revision