JavaScript Tutorial
4. Literals
You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. Examples of literals include: 1234, "This is a literal," and true.
4.1. 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.
Some examples of integer literals are: 42, 0xFFF, and -345.
4.2. Floating-point literals
A floating-point literal can have the following parts: a decimal integer, a decimal point ("."), a fraction (another decimal number), an exponent, and a type suffix. 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, plus either a decimal point or "e" (or "E").
Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12
4.3. Boolean literals
The Boolean type has two literal values: true and false.
4.4. 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 double quotation marks. The following are examples of string literals:
- "blah"
- 'blah'
- "1234"
- "one line \n another line"
Character | Meaning |
---|---|
\b | backspace |
\f | form feed |
\n | form feed |
\r | carriage return |
\t | tab |
\\ | backslash character |
4.5. Escaping characters
For characters not listed in the preceding table, a preceding backslash is ignored, with the exception of a quotation mark and the backslash character itself.
You can insert quotation marks inside strings by preceding them with a backslash. This is known as escaping the quotation marks. 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"