| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Grammar_and_types#variable_hoisting | [Back] [Original] |
Get to know MDN better
JavaScript JavaC C++ AwkPerl Python
JavaScript Case-sensitive Unicode Frh ("early")
var Frh = "foobar";
frh Frh JavaScript
JavaScript Statements;Tab JavaScript TokenControl charactersline terminatorsCommentsWithespaceECMAScript Statement Statement
C++
// a one line comment
/* this is a longer,
multi-line comment
*/
/* You can't, however, /* nest comments */ SyntaxError */
JavaScript
variablevalue identifiers
JavaScript letter_$0-9JavaScript case sensitive'A' ~ 'Z''a' ~ 'z'
You can use most of ISO 8859-1 or Unicode letters such as and in identifiers (for more details see this blog post). You can also use the Unicode escape sequences as characters in identifiers.
Some examples of legal names are Number_hits, temp99, $credit, and _name.
var let undefined ReferenceError
var a;
console.log("The value of a is " + a); // The value of a is undefined
console.log("The value of b is " + b); // The value of b is undefined
var b;
console.log("The value of c is " + c); // Uncaught ReferenceError: c is not defined
let x;
console.log("The value of x is " + x); // The value of x is undefined
console.log("The value of y is " + y); // Uncaught ReferenceError: y is not defined
let y;
undefined input if true
var input;
if (input === undefined) {
doThis();
} else {
doThat();
}
undefined false myFunction myArray undefined
var myArray = [];
if (!myArray[0]) myFunction();
undefined NaN
var a;
a + 2; // Evaluates to NaN
var n = null;
console.log(n * 32); // Will log 0 to the console
(global variable), (local variable)
!! ECMAScript 2015 JavaScript (block statement)
5 x if { }
if (true) {
var x = 5;
}
console.log(x); // x is 5
ECMAScript 2015 let y if { } ReferenceError
if (true) {
let y = 5;
}
console.log(y); // ReferenceError: y is not defined (y)
JavaScript , hoisting JavaScript hoistedliftedfunctionstatement hoistedundefinedundefined
/**
* Example 1
*/
console.log(x === undefined); // true
var x = 3;
/**
* Example 2
*/
// will return a value of undefined
var myvar = "my value";
(function () {
console.log(myvar); // undefined
var myvar = "local value";
})();
:
/**
* Example 1
*/
var x;
console.log(x === undefined); // true
x = 3;
/**
* Example 2
*/
var myvar = "my value";
(function () {
var myvar;
console.log(myvar); // undefined
myvar = "local value";
})();
(hoisting)(function) var (function)
ECMAScript 2015 letconstblock ReferenceErrorblocktemporal dead zone
console.log(x); // ReferenceError
let x = 3;
(function declaration)(function exprssion)
/* Function declaration */
foo(); // "bar"
function foo() {
console.log("bar");
}
/* Function expression */
baz(); // TypeError: baz is not a function
var baz = function () {
console.log("bar2");
};
window window.variable
Consequently, window frame window frame phoneNumber iframe parent.phoneNumber
const : ($)
const PI = 3.14;
The scope rules for constants are the same as those for let block-scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.
:
// THIS WILL CAUSE AN ERROR
function f() {}
const f = 5;
// THIS WILL CAUSE AN ERROR ALSO
function f() {
const g = 5;
var g;
//statements
}
const MY_OBJECT = { key: "value" };
MY_OBJECT.key = "otherValue";
ECMAScript :
(primitives) :
true and false.null is not the same as Null, NULL, or any other variant.42 or 3.14159.and Object
JavaScript
var answer = 42;
answer = "Thanks for all the fish...";
Javascript
+ JavaScript
x = "The answer is " + 42; // "The answer is 42"
y = 42 + " is the answer"; // "42 is the answer"
JavaScript
"37" - 7; // 30
"37" + 7; // "377"
parseInt parseInt
+ (unary plus) :
'1.1' + '1.1' = '1.11.1'
(+'1.1') + (+'1.1') = 2.2
// : .
JavaScript
[]
coffees 3
var coffees = ["French Roast", "Colombian", "Kona"];
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 and Indexed collections for details on Array objects.
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 undefined 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[0] is "Lion", fish[1] is undefined, and fish[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[3]. All other commas in the list indicate a new element.
Trailing commas can create errors in older browser versions and it is a best practice to remove them.
var myList = ["home", , "school"];
In the following example, the length of the array is four, and myList[0] and myList[2] are missing.
var myList = [, "home", , "school"];
In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.
var myList = ["home", , "school", ,];
Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as undefined will increase your code's clarity and maintainability.
true 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 for more information.
0, 117 and -345 (decimal, base 10) 015, 0001 and -0o77 (octal, base 8) 0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16) 0b11, 0b0011 and -0b11 (binary, base 2)
Numeric literals in the Lexical grammar reference.
"e" "E" "+" "-" "e" ( "E")
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
3.1415926 -.123456789 -3.1E+12 .1e-23
{} "{" (block)
car
myCar 'Saturn'getCar carTypes('Honda')special 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 };
console.log(car.myCar); // Saturn
console.log(car.getCar); // Honda
console.log(car.special); // Toyota
var car = { manyCars: { a: "Saab", b: "Jeep" }, 7: "Mazda" };
console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda
var unusualPropertyNames = {
'': 'An empty string',
'!': 'Bang!'
}
console.log(unusualPropertyNames.''); // SyntaxError: Unexpected string
console.log(unusualPropertyNames['']); // An empty string
console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token !
console.log(unusualPropertyNames['!']); // Bang!
In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for handler: handler
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
["prop_" + (() => 42)()]: 42,
};
Please note:
var foo = { a: "alpha", 2: "two" };
console.log(foo.a); // alpha
console.log(foo[2]); // two
//console.log(foo.2); // Error: missing ) after argument list
//console.log(foo[a]); // Error: a is not defined
console.log(foo["a"]); // alpha
console.log(foo["2"]); // two
var re = /ab+c/;
"'
"foo";
"bar";
"1234";
"one line \n another line";
"John's cat";
String - JavaScript String String String.length
console.log("John's cat".length);
// Will print the number of symbols in the string including whitespace.
// In this case, 10.
In ES2015, template literals are also available. Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.
// Basic literal string creation
`In JavaScript '\n' is a line-feed.` // Multiline strings
`In JavaScript template strings can run
over multiple lines, but double and single
quoted strings cannot.`;
// String interpolation
var name = "Bob",
time = "today";
`Hello ${name}, how are you ${time}?`;
// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
Content-Type: application/json
X-Credentials: ${credentials}
{ "foo": ${foo},
"bar": ${bar}}`(myOnReadyStateChangeHandler);
You should use string literals unless you specifically need to use a String object. See String for details on String objects.
"one line \n another line";
JavaScript
\0 |
Null Byte |
\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. |
\u{XXXXX} |
Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04. |
For characters not listed in the table, 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.';
console.log(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";
You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.
var str =
"this string \
is broken \
across multiple \
lines.";
console.log(str); // this string is broken across multiplelines.
Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:
var poem =
"Roses are red,\n\
Violets are blue.\n\
Sugar is sweet,\n\
and so is foo.";
ECMAScript 2015 introduces a new type of literal, namely template literals. This allows for many new features including multiline strings!
var poem = `Roses are red,
Violets are blue.
Sugar is sweet,
and so is foo.`;
This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:
In the next chapter, we will have a look at control flow constructs and error handling.
This page was last modified on 2026526 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |