[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Grammar_and_types#declarations [Back]  [Original]

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

JavaScript

In this article

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

Comments

C++

js
// a one line comment

/* this is a longer,
   multi-line comment
 */

/* You can't, however, /* nest comments */ SyntaxError */

Declarations

JavaScript

var

let

const

Variables

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

js
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

js
var input;
if (input === undefined) {
  doThis();
} else {
  doThat();
}

undefined false myFunction myArray undefined

js
var myArray = [];
if (!myArray[0]) myFunction();

undefined NaN

js
var a;
a + 2; // Evaluates to NaN

null null 0 false

js
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 { }

js
if (true) {
  var x = 5;
}
console.log(x); // x is 5

ECMAScript 2015 let y if { } ReferenceError

js
if (true) {
  let y = 5;
}
console.log(y); // ReferenceError: y is not defined (y)

JavaScript , hoisting JavaScript hoistedliftedfunctionstatement hoistedundefinedundefined

js
/**
 * 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";
})();

:

js
/**
 * 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

js
console.log(x); // ReferenceError
let x = 3;

(function declaration)(function exprssion)

js
/* Function declaration */

foo(); // "bar"

function foo() {
  console.log("bar");
}

/* Function expression */

baz(); // TypeError: baz is not a function

var baz = function () {
  console.log("bar2");
};

(Global variables)

window window.variable

Consequently, window frame window frame phoneNumber iframe parent.phoneNumber

(Constants)

const : ($)

js
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.

:

js
// THIS WILL CAUSE AN ERROR
function f() {}
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
  const g = 5;
  var g;

  //statements
}

js
const MY_OBJECT = { key: "value" };
MY_OBJECT.key = "otherValue";

(Data types)

ECMAScript :

  • (primitives) :

    • Boolean. true and false.
    • null. A special keyword denoting a null value. Because JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant.
    • undefined. A top-level property whose value is undefined.
    • Number. 42 or 3.14159.
    • String. "Howdy"
    • Symbol (new in ECMAScript 2015). A data type whose instances are unique and immutable.
  • and Object

. ,.

JavaScript

js
var answer = 42;

js
answer = "Thanks for all the fish...";

Javascript

+ JavaScript

js
x = "The answer is " + 42; // "The answer is 42"
y = 42 + " is the answer"; // "42 is the answer"

JavaScript

js
"37" - 7; // 30
"37" + 7; // "377"

parseInt parseInt

+ (unary plus) :

js
'1.1' + '1.1' = '1.11.1'
(+'1.1') + (+'1.1') = 2.2
// : .

Literals

JavaScript

(Array literals)

[]

coffees 3

js
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.

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 undefined for the unspecified elements. The following example creates the fish array:

js
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.

js
var myList = ["home", , "school"];

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

js
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.

js
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.

(Boolean literals)

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.

(Numerical literals)

  • 0
  • 0 0o 0O 0-7
  • 0x 0X 0-9 A-F a-f
  • 0b 0B 0 1

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.

(Floating-point literals)

  • ( "+" "-" )
  • "."
  • ()

"e" "E" "+" "-" "e" ( "E")

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

3.1415926
-.123456789
-3.1E+12
.1e-23

(Object literals)

{} "{" (block)

car

  • myCar 'Saturn'
  • getCar carTypes('Honda')
  • special sales
js
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

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

console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda

JavaScript (.) "[]"

js
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!

Enhanced Object literals

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.

js
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:

js
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

(RegExp literals)

js
var re = /ab+c/;

(String literals)

"'

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

String - JavaScript String String String.length

js
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.

js
// 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.

js
"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.

Escaping characters

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:

js
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:

js
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.

js
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:

js
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!

js
var poem = `Roses are red,
Violets are blue.
Sugar is sweet,
and so is foo.`;

More information

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.


Web Proxy Viewer  |  New URL  |  Original Page