MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

이 페이지에서는 JavaScript의 문법(lexical grammar)에 대해 설명합니다. ECMAScript 스크립트 소스 본문은 왼쪽에서 오른쪽 방향으로 분석되고 토큰, 제어문자, 줄바꿈, 주석, 또는 공백으로 구성되는 입력 요소 시퀀스로 바뀝니다. 또한 ECMAScript는 특별한 키워드와 구문(literal)을 정의하고 있으며  명령문 끝에 자동으로 세미콜론을 추가하는 규칙들이 있습니다. 

제어 문자(Control characters)

제어문자는 눈에 보이지 않지만 스크립트 소스 본문 해석을 제어하는 데 사용됩니다.

유니코드로 표기한 제어 문자(Unicode format-control characters)
Code point Name 축약형 설명
U+200C Zero width non-joiner <ZWNJ>

특정 언어에서 문자들이 연결선으로 묶이지 않게 하기 위해 문자 사이에 위치한다(Wikipedia).

U+200D Zero width joiner <ZWJ>

특정 언어에서, 보통은 연결되지 않는 문자이나 해당 문자를 연결된 형태로 그리기 위해서(to be rendered) 사용하며 문자 사이에 위치한다(Wikipedia).

U+FEFF Byte order mark <BOM>

스크립트 맨 앞에 두어 스크립트 본문의 byte order와 유니코드를 표시하는 데에 사용한다.(Wikipedia).

공백(White space)

공백 문자는 소스 본문을 읽기 좋게 만들고 토큰을 구분합니다. 이 공백 문자들은 보통 코드의 기능에 필요한 것은 아닙니다. 최소화 도구(Minification tools)는 종종 전송해야하는 데이터 크기를 줄이기 위해서 공백을 제거합니다.

공백 문자(White space characters)
Code point Name Abbreviation Description Escape sequence
U+0009 Character tabulation <HT> Horizontal tabulation \t
U+000B Line tabulation <VT> Vertical tabulation \v
U+000C Form feed <FF> Page breaking control character (Wikipedia). \f
U+0020 Space <SP> Normal space  
U+00A0 No-break space <NBSP> Normal space, but no point at which a line may break  
Others Other Unicode space characters <USP> Spaces in Unicode on Wikipedia  

라인 종결자(Line terminators)

공백문자와 더불어, 라인 종결자는 소스 본문의 가독성을 향상시킵니다. 하지만, 몇몇 상황에서 라인 종결자는 코드 내부에 숨겨지기 때문에 자바스크립트 코드 실행에 영향을 미칩니다. 라인 종결자는 자동 새미콜론 삽입(automatic semicolon insertion) 규칙에도 영향을 줍니다. 라인 종결자는 표준 표현방식(regular expressions)의 클래스인 \s로 매치됩니다. 

아래의 유니코드 문자만이 ECMAScript에서 라인 종결자로 다뤄지며, 라인을 바꾸는 다른 문자들은 공백으로 생각하시면 됩니다(예를 들어, Next Line, NEL, U+0085는 공백으로 간주).

라인 종결문자(Line terminator characters)
Code point Name Abbreviation Description Escape sequence
U+000A Line Feed <LF> New line character in UNIX systems. \n
U+000D Carriage Return <CR> New line character in Commodore and early Mac systems. \r
U+2028 Line Separator <LS> Wikipedia  
U+2029 Paragraph Separator <PS> Wikipedia  

주석, 첨언(Comments)

주석은 힌트, 필기, 제안이나 주의할 점들을 자바스크립트 코드에 넣을 때 사용합니다. 이는 더 쉽게 읽고 이해할 수 있게 도와줍니다. 또한 특정 코드가 실행되지 않도록 막아주기도 합니다. 따라서 주석은 유용한 디버깅 도구라고도 할 수 있습니다.

자바스크립트에는 코드 속에 주석을 쓰는 두 가지 방식이 있습니다.

첫 번째, '//'로 첨언하기입니다. 이는 아래의 예시처럼 같은 줄에 있는 모든 코드를 주석으로 바꿉니다.

function comment() {
  // 자바스크립트의 각주 한 줄입니다.
  console.log("Hello world!");
}
comment();

두 번째, 좀 더 유연하게 쓸 수 있는  '/* */'로 첨언하기입니다. 

예를 들면, 한 줄에 첨언할 때는 이렇게 쓸 수 있습니다 :

function comment() {
  /* 자바스크립트 각주 한 줄입니다. */
  console.log("Hello world!");
}
comment();

여러 줄로 첨언할 때는, 이렇게 씁니다 :

function comment() {
  /* This comment spans multiple lines. Notice
     that we don't need to end the comment until we're done. */
  console.log("Hello world!");
}
comment();

You can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution:

function comment(x) {
  console.log("Hello " + x /* insert the value of x */ + " !");
}
comment("world");

In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:

function comment() {
  /* console.log("Hello world!"); */
}
comment();

In this case, the console.log() call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.

Keywords

Reserved keywords as of ECMAScript 6

Future reserved keywords

The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.

These are always reserved:

  • enum

The following are only reserved when they are found in strict mode code:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static

The following are only reserved when they are found in module code:

  • await

Future reserved keywords in older standards

The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).

  • abstract
  • boolean
  • byte
  • char
  • double
  • final
  • float
  • goto
  • int
  • long
  • native
  • short
  • synchronized
  • throws
  • transient
  • volatile

Additionally, the literals null, true, and false cannot be used as identifiers in ECMAScript.

Reserved word usage

Reserved words actually only apply to Identifiers (vs. IdentifierNames) . As described in es5.github.com/#A.1, these are all IdentifierNames which do not exclude ReservedWords.

a.import
a["import"]
a = { import: "test" }.

On the other hand the following is illegal because it's an Identifier, which is an IdentifierName without the reserved words. Identifiers are used for FunctionDeclaration and FunctionExpression.

function import() {} // Illegal.

Literals

Null literal

See also null for more information.

null

Boolean literal

See also Boolean for more information.

true
false

Numeric literals

Decimal

1234567890
42

// Caution when using with a leading zero:
0888 // 888 parsed as decimal
0777 // parsed as octal, 511 in decimal

Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see bug 957513. See also the page about parseInt().

Binary

Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (0b or 0B). Because this syntax is new in ECMAScript 6, see the browser compatibility table, below. If the digits after the 0b are not 0 or 1, the following SyntaxError is thrown: "Missing binary digits after 0b".

var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607

Octal

Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (0o or 0O). Because this syntax is new in ECMAScript 6, see the browser compatibility table, below. If the digits after the 0o are outside the range (01234567), the following SyntaxError is thrown:  "Missing octal digits after 0o".

var n = 0O755; // 493
var m = 0o644; // 420

// Also possible with just a leading zero (see note about decimals above)
0755
0644

Hexadecimal

Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (0x or 0X). If the digits after 0x are outside the range (0123456789ABCDEF),  the following SyntaxError is thrown: "Identifier starts immediately after numeric literal".

0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF   // 81985529216486900
0XA                 // 10

Object literals

See also Object and Object initializer for more information.

var o = { a: "foo", b: "bar", c: 42 };

// shorthand notation. New in ES6
var a = "foo", b = "bar", c = 42;
var o = {a, b, c};

// instead of
var o = { a: a, b: b, c: c };

Array literals

See also Array for more information.

[1954, 1974, 1990, 2014]

String literals

'foo'
"bar"

Hexadecimal escape sequences

'\xA9' // "©"

Unicode escape sequences

The Unicode escape sequences require at least four characters following \u.

'\u00A9' // "©"

Unicode code point escapes

New in ECMAScript 6. With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to 0x10FFFF. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same.

See also String.fromCodePoint() or String.prototype.codePointAt().

'\u{2F804}'

// the same with simple Unicode escapes
'\uD87E\uDC04'

Regular expression literals

See also RegExp for more information.

/ab+c/g

// An "empty" regular expression literal
// The empty non-capturing group is necessary 
// to avoid ambiguity with single-line comments.
/(?:)/

Template literals

See also template strings for more information.

`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

Automatic semicolon insertion

Some JavaScript statements must be terminated with semicolons and are therefore affected by automatic semicolon insertion (ASI):

  • Empty statement
  • let, const, variable statement
  • import, export, module declaration
  • Expression statement
  • debugger
  • continue, break, throw
  • return

The ECMAScript specification mentions three rules of semicolon insertion.

1.  A semicolon is inserted before, when a Line terminator or "}" is encountered that is not allowed by the grammar.

{ 1 2 } 3 

// is transformed by ASI into 

{ 1 2 ;} 3;

2.  A semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input stream as a complete program.

Here ++ is not treated as a postfix operator applying to variable b, because a line terminator occurs between b and ++.

a = b
++c

// is transformend by ASI into

a = b;
++c;

3. A semicolon is inserted at the end, when a statement with restricted productions in the grammar is followed by a line terminator. These statements with "no LineTerminator here" rules are:

  • PostfixExpressions (++ and --)
  • continue
  • break
  • return
  • yield, yield*
  • module
return
a + b

// is transformed by ASI into

return;
a + b;

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'Lexical Conventions' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Lexical Grammar' in that specification.
Standard Added: Binary and Octal Numeric literals, Unicode code point escapes, Templates
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Lexical Grammar' in that specification.
Draft  

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Binary and octal numeric literals
(0b and 0o)
41 12 25 (25) ? 28 9
Unicode code point escapes
(\u{})
44 12 40 (40) No support 31 9
Shorthand notation for object literals 43 12 33 (33) No support 30 9
Template literals 41 12 34 (34) No support 28 9
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Binary and octal numeric literals (0b and 0o) ? 41 33.0 (33) ? ? ?
Unicode code point escapes (\u{}) ? ? 40.0 (40) ? ? ?
Shorthand notation for object literals No support No support 33.0 (33) No support No support No support
Template literals No support No support 34.0 (34) No support No support No support

Firefox-specific notes

  • Prior to Firefox 5 (JavaScript 1.8.6), future reserved keywords could be used when not in strict mode. This ECMAScript violation was fixed in Firefox 5.

See also

문서 태그 및 공헌자

 이 페이지의 공헌자: Roomination, paranbaram
 최종 변경: Roomination,