From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../reference/operators/addition/index.html | 77 +++ .../operators/arithmetic_operators/index.html | 290 +++++++++++ .../operators/assignment_operators/index.html | 394 +++++++++++++++ .../reference/operators/async_function/index.html | 96 ++++ .../reference/operators/await/index.html | 137 ++++++ .../operators/bitwise_operators/index.html | 540 +++++++++++++++++++++ .../reference/operators/class/index.html | 100 ++++ .../reference/operators/comma_operator/index.html | 91 ++++ .../operators/comparison_operators/index.html | 215 ++++++++ .../operators/conditional_operator/index.html | 193 ++++++++ .../reference/operators/delete/index.html | 282 +++++++++++ .../operators/destructuring_assignment/index.html | 409 ++++++++++++++++ .../reference/operators/equality/index.html | 123 +++++ .../operators/expression_closures/index.html | 79 +++ .../reference/operators/function/index.html | 154 ++++++ .../reference/operators/function_star_/index.html | 85 ++++ .../operators/generator_comprehensions/index.html | 174 +++++++ .../reference/operators/grouping/index.html | 92 ++++ .../javascript/reference/operators/in/index.html | 188 +++++++ .../web/javascript/reference/operators/index.html | 304 ++++++++++++ .../reference/operators/instanceof/index.html | 161 ++++++ .../reference/operators/new.target/index.html | 93 ++++ .../javascript/reference/operators/new/index.html | 187 +++++++ .../nullish_coalescing_operator/index.html | 161 ++++++ .../operators/object_initializer/index.html | 302 ++++++++++++ .../operators/optional_chaining/index.html | 187 +++++++ .../operators/pipeline_operator/index.html | 76 +++ .../operators/property_accessors/index.html | 153 ++++++ .../reference/operators/remainder/index.html | 73 +++ .../reference/operators/spread_syntax/index.html | 255 ++++++++++ .../reference/operators/super/index.html | 176 +++++++ .../javascript/reference/operators/this/index.html | 398 +++++++++++++++ .../reference/operators/typeof/index.html | 227 +++++++++ .../javascript/reference/operators/void/index.html | 122 +++++ .../reference/operators/yield/index.html | 182 +++++++ .../reference/operators/yield_star_/index.html | 164 +++++++ .../index.html" | 249 ++++++++++ .../operators/\353\260\260\354\227\264/index.html" | 200 ++++++++ .../index.html" | 462 ++++++++++++++++++ 39 files changed, 7851 insertions(+) create mode 100644 files/ko/web/javascript/reference/operators/addition/index.html create mode 100644 files/ko/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/assignment_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/async_function/index.html create mode 100644 files/ko/web/javascript/reference/operators/await/index.html create mode 100644 files/ko/web/javascript/reference/operators/bitwise_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/class/index.html create mode 100644 files/ko/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/comparison_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/conditional_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/delete/index.html create mode 100644 files/ko/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/ko/web/javascript/reference/operators/equality/index.html create mode 100644 files/ko/web/javascript/reference/operators/expression_closures/index.html create mode 100644 files/ko/web/javascript/reference/operators/function/index.html create mode 100644 files/ko/web/javascript/reference/operators/function_star_/index.html create mode 100644 files/ko/web/javascript/reference/operators/generator_comprehensions/index.html create mode 100644 files/ko/web/javascript/reference/operators/grouping/index.html create mode 100644 files/ko/web/javascript/reference/operators/in/index.html create mode 100644 files/ko/web/javascript/reference/operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/instanceof/index.html create mode 100644 files/ko/web/javascript/reference/operators/new.target/index.html create mode 100644 files/ko/web/javascript/reference/operators/new/index.html create mode 100644 files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/ko/web/javascript/reference/operators/optional_chaining/index.html create mode 100644 files/ko/web/javascript/reference/operators/pipeline_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/property_accessors/index.html create mode 100644 files/ko/web/javascript/reference/operators/remainder/index.html create mode 100644 files/ko/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/ko/web/javascript/reference/operators/super/index.html create mode 100644 files/ko/web/javascript/reference/operators/this/index.html create mode 100644 files/ko/web/javascript/reference/operators/typeof/index.html create mode 100644 files/ko/web/javascript/reference/operators/void/index.html create mode 100644 files/ko/web/javascript/reference/operators/yield/index.html create mode 100644 files/ko/web/javascript/reference/operators/yield_star_/index.html create mode 100644 "files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" create mode 100644 "files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" create mode 100644 "files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" (limited to 'files/ko/web/javascript/reference/operators') diff --git a/files/ko/web/javascript/reference/operators/addition/index.html b/files/ko/web/javascript/reference/operators/addition/index.html new file mode 100644 index 0000000000..0a624fdd16 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/addition/index.html @@ -0,0 +1,77 @@ +--- +title: Addition (+) +slug: Web/JavaScript/Reference/Operators/Addition +translation_of: Web/JavaScript/Reference/Operators/Addition +--- +
{{jsSidebar("Operators")}}
+ +

증가 연산자addition operator (+)는 숫자 또는 여러 문자열의 더합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-addition.html")}}
+ +
+ + + +

Syntax

+ +
Operator: x + y
+
+ +

Examples

+ +

Numeric addition

+ +
// Number + Number -> addition
+1 + 2 // 3
+
+// Boolean + Number -> addition
+true + 1 // 2
+
+// Boolean + Boolean -> addition
+false + false // 0
+
+ +

String concatenation

+ +
// String + String -> concatenation
+'foo' + 'bar' // "foobar"
+
+// Number + String -> concatenation
+5 + 'foo' // "5foo"
+
+// String + Boolean -> concatenation
+'foo' + false // "foofalse"
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-addition-operator-plus', 'Addition operator')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.addition")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..8b2b274aa6 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html @@ -0,0 +1,290 @@ +--- +title: 산술 연산자 +slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

산술 연산자는 숫자 값(리터럴 또는 변수)을 피연산자로 받아 하나의 숫자 값을 반환합니다. 표준 산술 연산자는 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/)입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}
+ + + +

덧셈 (+)

+ +

덧셈 연산자는 숫자 피연산자를 더한 값, 또는 문자열을 연결한 값을 생성합니다.

+ +

구문

+ +
연산자: x + y
+
+ +

예제

+ +
// Number + Number -> 합
+1 + 2 // 3
+
+// Boolean + Number -> 합
+true + 1 // 2
+
+// Boolean + Boolean -> 합
+false + false // 0
+
+// Number + String -> 연결
+5 + "foo" // "5foo"
+
+// String + Boolean -> 연결
+"foo" + false // "foofalse"
+
+// String + String -> 연결
+"foo" + "bar" // "foobar"
+
+ +

뺄셈 (-)

+ +

뺄셈 연산자는 두 개의 피연산자를 뺀 값을 생성합니다.

+ +

구문

+ +
연산자: x - y
+
+ +

예제

+ +
5 - 3 // 2
+3 - 5 // -2
+"foo" - 3 // NaN
+ +

나눗셈 (/)

+ +

나눗셈 연산자는 왼쪽 피연산자를 피제수로, 오른쪽 피연산자를 제수로 한 몫을 생성합니다.

+ +

구문

+ +
연산자: x / y
+
+ +

예제

+ +
1 / 2      // JavaScript에선 0.5
+1 / 2      // Java에선 0
+// (양쪽 피연산자 모두 명시적인 부동소수점 숫자가 아님)
+
+1.0 / 2.0  // JavaScript와 Java 둘 다 0.5
+
+2.0 / 0    // JavaScript에서 Infinity
+2.0 / 0.0  // 동일하게 Infinity
+2.0 / -0.0 // JavaScript에서 -Infinity
+ +

곱셈 (*)

+ +

곱셈 연산자는 두 연산자의 곱을 생성합니다.

+ +

구문

+ +
연산자: x * y
+
+ +

예제

+ +
2 * 2 // 4
+-2 * 2 // -4
+Infinity * 0 // NaN
+Infinity * Infinity // Infinity
+"foo" * 2 // NaN
+
+ +

나머지 (%)

+ +

나머지 연산자는 왼쪽 피연산자를 오른쪽 피연산자로 나눴을 때의 나머지를 반환합니다. 결과는 항상 피제수의 부호를 따라갑니다.

+ +

구문

+ +
연산자: var1 % var2
+
+ +

예제

+ +
12 % 5 // 2
+-1 % 2 // -1
+NaN % 2 // NaN
+1 % 2 // 1
+2 % 3 // 2
+-4 % 2 // -0
+5.5 % 2 // 1.5
+
+ +

거듭제곱 (**)

+ +

거듭제곱 연산자는 첫 번째 피연산자를 밑으로, 두 번째 피연산자를 지수로 한 값을 생성합니다. 즉, var1var2가 변수일 때, var1var2의 값을 생성합니다. 거듭제곱 연산자는 우결합성을 가집니다. 따라서 a ** b ** ca ** (b ** c)와 같습니다.

+ +

구문

+ +
연산자: var1 ** var2
+
+ +

참고

+ +

PHP와 Python 등 거듭제곱 연산자를 가진 대부분의 언어는 거듭제곱 연산자의 우선순위가 +와 - 등 단항 연산자보다 높습니다. 그러나 Bash는 단항 연산자가 거듭제곱 연산자보다 우선순위가 높은 등 일부 예외도 있습니다. JavaScript는 단항 연산자(+/-/~/!/delete/void/typeof)를 왼쪽 피연산자 앞에 배치할 수 없으므로, 모호한 표현도 작성할 수 없습니다.

+ +
-2 ** 2;
+// Bash에서 4, 다른 언어에서는 -4.
+// 모호한 표현이므로 JavaScript에서는 유효하지 않음
+
+
+-(2 ** 2);
+// JavaScript에서 -4, 작성자의 의도가 명확함
+
+ +

예제

+ +
2 ** 3 // 8
+3 ** 2 // 9
+3 ** 2.5 // 15.588457268119896
+10 ** -1 // 0.1
+NaN ** 2 // NaN
+
+2 ** 3 ** 2 // 512
+2 ** (3 ** 2) // 512
+(2 ** 3) ** 2 // 64
+
+ +

결과의 부호를 뒤집으려면 다음과 같이 작성합니다.

+ +
-(2 ** 2) // -4
+
+ +

거듭제곱의 밑을 음수로 강제하려면 다음과 같이 작성합니다.

+ +
(-2) ** 2 // 4
+
+ +
+

참고: JavaScript는 비트 연산자 ^ (논리 XOR)도 가지고 있습니다. **^는 다릅니다. (예 : 2 ** 3 === 8이지만 2 ^ 3 === 1)

+
+ +

증가 (++)

+ +

증가 연산자는 피연산자를 증가(1을 덧셈)시키고, 그 값을 반환합니다.

+ + + +

구문

+ +
연산자: x++ or ++x
+
+ +

예제

+ +
// 접미사
+var x = 3;
+y = x++; // y = 3, x = 4
+
+// 접두사
+var a = 2;
+b = ++a; // a = 3, b = 3
+
+ +

감소 (--)

+ +

감소 연산자는 피연산자를 감소(1을 뺄셈)시키고, 그 값을 반환합니다.

+ + + +

구문

+ +
연산자: x-- or --x
+
+ +

예제

+ +
// 접미사
+var x = 3;
+y = x--; // y = 3, x = 2
+
+// 접두사
+var a = 2;
+b = --a; // a = 1, b = 1
+
+ +

단항 부정 (-)

+ +

단항 부정 연산자는 피연산자의 앞에 위치하며 부호를 뒤집습니다.

+ +

구문

+ +
연산자: -x
+
+ +

예제

+ +
var x = 3;
+y = -x; // y = -3, x = 3
+
+// 단항 부정 연산자는 숫자가 아닌 값을 숫자로 변환함
+var x = "4";
+y = -x; // y = -4
+ +

단항 양부호 (+)

+ +

단항 양부호 연산자는 피연산자의 앞에 위치하며 피연산자의 값 그대로 평가되지만, 값이 숫자가 아닐 경우 숫자로 변환을 시도합니다. 단항 부정(-) 연산자도 숫자가 아닌 값을 변환할 수 있지만, 단항 양부호가 속도도 제일 빠르고 다른 연산도 수행하지 않으므로 선호해야 할 방법입니다. 문자열로 표현한 정수 및 부동소수점 실수, 문자열이 아닌 true, false, null도 변환할 수 있습니다. 10진수와 (앞에 "0x"가 붙은) 16진수 정수 모두 지원합니다. 음수도 지원하지만 16진수 음수에는 사용할 수 없습니다. 어떤 값을 분석할 수 없으면 {{jsxref("NaN")}}으로 평가됩니다.

+ +

구문

+ +
연산자: +x
+
+ +

예제

+ +
+3     // 3
++"3"   // 3
++true  // 1
++false // 0
++null  // 0
++function(val) { return val } // NaN
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.arithmetic")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/assignment_operators/index.html b/files/ko/web/javascript/reference/operators/assignment_operators/index.html new file mode 100644 index 0000000000..d7f195c803 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/assignment_operators/index.html @@ -0,0 +1,394 @@ +--- +title: 할당 연산자 +slug: Web/JavaScript/Reference/Operators/Assignment_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators#Assignment_operators +--- +
{{jsSidebar("Operators")}}
+ +

할당 연산자는 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-assignment.html")}}
+ + + +

개요

+ +

기본 할당연산자는 등호(=)로, 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다. 즉, x = yy의 값을 x에 할당힙니다. 다른 할당 연산자는 보통 표준 연산의 축약형으로, 다음 표에서 종류와 예시를 확인할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
이름단축 연산자의미
할당x = yx = y
덧셈 할당x += yx = x + y
뺄셈 할당x -= yx = x - y
곱셈 할당x *= yx = x * y
나눗셈 할당x /= yx = x / y
나머지 연산 할당x %= yx = x % y
지수 연산 할당x **= yx = x ** y
왼쪽 시프트 할당x <<= yx = x << y
오른쪽 시프트 할당x >>= yx = x >> y
부호없는 오른쪽 시프트 할당x >>>= yx = x >>> y
비트 AND 할당x &= yx = x & y
비트 XOR 할당x ^= yx = x ^ y
비트 OR 할당x |= yx = x | y
+ +

할당

+ +

단순 할당 연산자는 값을 변수에 할당합니다. 할당 연산자는 할당의 결과값으로 평가됩니다. 할당 연산자를 연속해서 사용해, 다수의 변수에 하나의 값을 한꺼번에 할당할 수 있습니다. 예제를 참고하세요.

+ +

구문

+ +
연산자: x = y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  x = 5
+//  y = 10
+//  z = 25
+
+x = y     // x는 10
+x = y = z // x, y, z 모두 25
+
+ +

덧셈 할당

+ +

덧셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 더하고, 그 결과를 변수에 할당합니다. 두 피연산자의 자료형이 덧셈 할당 연산자의 행동을 결정합니다. 덧셈 연산자처럼 합 또는 연결이 가능합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "덧셈 연산자", "#Addition", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x += y
+의미: x = x + y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  foo = "foo"
+//  bar = 5
+//  baz = true
+
+
+// Number + Number -> 합
+bar += 2 // 7
+
+// Boolean + Number -> 합
+baz += 1 // 2
+
+// Boolean + Boolean -> 합
+baz += false // 1
+
+// Number + String -> 연결
+bar += 'foo' // "5foo"
+
+// String + Boolean -> 연결
+foo += false // "foofalse"
+
+// String + String -> 연결
+foo += 'bar' // "foobar"
+
+ +

뺄셈 할당

+ +

뺄셈 할당 연산자는 변수에서 오른쪽 피연산자의 값을 빼고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "뺄셈 연산자", "#Subtraction", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x -= y
+의미: x = x - y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar -= 2     // 3
+bar -= "foo" // NaN
+
+ +

곱셈 할당

+ +

곱셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 곱하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "곱셈 연산자", "#Multiplication", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x *= y
+의미: x = x * y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar *= 2     // 10
+bar *= "foo" // NaN
+
+ +

나눗셈 할당

+ +

나눗셈 할당 연산자는 변수를 오른쪽 피연산자로 나누고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나눗셈 연산자", "#Division", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x /= y
+의미: x = x / y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar /= 2     // 2.5
+bar /= "foo" // NaN
+bar /= 0     // Infinity
+
+ +

나머지 연산 할당

+ +

나머지 연산 할당은 변수를 오른쪽 피연산자로 나눈 나머지를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나머지 연산자", "#Remainder", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x %= y
+의미: x = x % y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar %= 2     // 1
+bar %= "foo" // NaN
+bar %= 0     // NaN
+
+ +

거듭제곱 할당

+ +

거듭제곱 할당 연산자는 변수를 오른쪽 피연산자만큼 거듭제곱한 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "거듭제곱 연산자", "#Exponentiation", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x **= y
+의미: x = x ** y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar **= 2     // 25
+bar **= "foo" // NaN
+ +

왼쪽 시프트 할당

+ +

왼쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 왼쪽으로 이동하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "left shift operator", "#Left_shift", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x <<= y
+의미: x = x << y
+
+ +

예제

+ +
var bar = 5; //  (00000000000000000000000000000101)
+bar <<= 2; // 20 (00000000000000000000000000010100)
+
+ +

오른쪽 시프트 할당

+ +

오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "right shift operator", "#Right_shift", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x >>= y
+의미: x = x >> y
+
+ +

예제

+ +
var bar = 5; //   (00000000000000000000000000000101)
+bar >>= 2;   // 1 (00000000000000000000000000000001)
+
+var bar -5; //    (-00000000000000000000000000000101)
+bar >>= 2;  // -2 (-00000000000000000000000000000010)
+
+ +

부호 없는 오른쪽 시프트 할당

+ +

부호 없는 오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", " unsigned right shift operator", "#Unsigned_right_shift", 1)}}을 참고하세요.

+ +

구문

+ +
연산자: x >>>= y
+의미: x = x >>> y
+
+ +

예제

+ +
var bar = 5; //   (00000000000000000000000000000101)
+bar >>>= 2;  // 1 (00000000000000000000000000000001)
+
+var bar = -5; // (-00000000000000000000000000000101)
+bar >>>= 2; // 1073741822 (00111111111111111111111111111110)
+ +

비트 AND 할당

+ +

비트 AND 할당 연산자는 양쪽 피연산자의 이진 표현을 AND 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은{{jsxref("Operators/Bitwise_Operators", "bitwise AND operator", "#Bitwise_AND", 1)}}을 참고하세요.

+ +

구문

+ +
연산자: x &= y
+의미: x = x & y
+
+ +

예제

+ +
var bar = 5;
+// 5:     00000000000000000000000000000101
+// 2:     00000000000000000000000000000010
+bar &= 2; // 0
+
+ +

비트 XOR 할당

+ +

비트 XOR 할당 연산자는 양쪽 피연산자의 이진 표현을 XOR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise XOR operator", "#Bitwise_XOR", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x ^= y
+의미: x = x ^ y
+
+ +

예제

+ +
var bar = 5;
+bar ^= 2; // 7
+// 5: 00000000000000000000000000000101
+// 2: 00000000000000000000000000000010
+// -----------------------------------
+// 7: 00000000000000000000000000000111
+
+ +

비트 OR 할당

+ +

비트 OR 할당 연산자는 양쪽 피연산자의 이진 표현을 OR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise OR operator", "#Bitwise_OR", 1)}}를 참고하세요.

+ +

문법

+ +
연산자: x |= y
+의미: x = x | y
+
+ +

예제

+ +
var bar = 5;
+bar |= 2; // 7
+// 5: 00000000000000000000000000000101
+// 2: 00000000000000000000000000000010
+// -----------------------------------
+// 7: 00000000000000000000000000000111
+
+ +

예제

+ +

다른 할당 연산자를 갖는 왼쪽 피연산자

+ +

드물게, 할당 연산자(예: x += y)와 그 의미를 나타낸 표현(x = x + y)이 동일하지 않은 경우가 있습니다. 할당 연산자의 왼쪽 피연산자가 다른 할당 연산자를 포함할 때, 왼쪽 피연산자는 한 번만 평가됩니다. 예를 들면 다음과 같습니다.

+ +
a[i++] += 5         // i는 한 번만 평가됨
+a[i++] = a[i++] + 5 // i는 두 번 평가됨
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.assignment")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/async_function/index.html b/files/ko/web/javascript/reference/operators/async_function/index.html new file mode 100644 index 0000000000..d1ec146ca4 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/async_function/index.html @@ -0,0 +1,96 @@ +--- +title: async function 표현식 +slug: Web/JavaScript/Reference/Operators/async_function +translation_of: Web/JavaScript/Reference/Operators/async_function +--- +
{{jsSidebar("Operators")}}
+ +

async function 키워드는 표현식 내에서 async 함수를 정의하기 위해 사용됩니다.

+ +

또한 async function statement을 사용하여 async 함수를 정의할 수 있습니다.

+ +

문법

+ +
async function [name]([param1[, param2[, ..., paramN]]]) { statements }
+ +

ES2015에서와 같이 arrow functions를 사용해도 됩니다.

+ +

인수

+ +
+
name
+
함수 이름. 생략가능하며 이경우함수는 anonymous 형식임  이름은 함수 몸체에 대해 지역적으로 사용.
+
paramN
+
함수에 전달될 인수의 이름.
+
statements
+
함수 몸체를 구성하는 명령문들.
+
+ +

설명

+ +

async function 표현식은 {{jsxref('Statements/async_function', 'async function 선언')}} 문법과 유사하며, 거의 동일합니다. async function 표현식과 async function 선언문의 주요 차이점은 익명함수로써의 사용 여부로, async function 표현식은 함수 이름을 생략하면 익명함수를 만듭니다. async function 표현식은 {{Glossary("IIFE")}}(즉시실행함수)로 사용할 수 있습니다. functions문서를 참고하세요.

+ +

Examples

+ +

Simple example

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+};
+
+
+var add = async function(x) { // async function 표현식을 변수에 할당
+  var a = await resolveAfter2Seconds(20);
+  var b = await resolveAfter2Seconds(30);
+  return x + a + b;
+};
+
+add(10).then(v => {
+  console.log(v);  // 4초 뒤에 60 출력
+});
+
+
+(async function(x) { // async function 표현식을 IIFE로 사용
+  var p_a = resolveAfter2Seconds(20);
+  var p_b = resolveAfter2Seconds(30);
+  return x + await p_a + await p_b;
+})(10).then(v => {
+  console.log(v);  // 2초 뒤에 60 출력
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
+ +

Browser compatibility

+ +
{{Compat("javascript.operators.async_function_expression")}} 
+ +
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/await/index.html b/files/ko/web/javascript/reference/operators/await/index.html new file mode 100644 index 0000000000..00b5fd3eff --- /dev/null +++ b/files/ko/web/javascript/reference/operators/await/index.html @@ -0,0 +1,137 @@ +--- +title: await +slug: Web/JavaScript/Reference/Operators/await +translation_of: Web/JavaScript/Reference/Operators/await +--- +
{{jsSidebar("Operators")}}
+ +
await연산자는 {{jsxref("Promise")}}를 기다리기 위해 사용됩니다. 연산자는 {{jsxref("Statements/async_function", "async function")}} 내부에서만 사용할 수 있습니다.
+ +

구문

+ +
[rv] = await expression;
+ +
+
expression
+
{{jsxref("Promise")}} 혹은 기다릴 어떤 값입니다.
+
rv
+
+

{{jsxref("Promise")}}에 의해 만족되는 값이 반환됩니다. {{jsxref("Promise")}}가 아닌 경우에는 그 값 자체가 반환됩니다.

+
+
+ +

설명

+ +

await 문은 Promise가 fulfill되거나 reject 될 때까지 async 함수의 실행을 일시 정지하고, Promise가 fulfill되면 async 함수를 일시 정지한 부분부터 실행합니다. 이때  await 문의 반환값은 Promise 에서 fulfill된 값이 됩니다.

+ +

만약 Promisereject되면, await 문은 reject된 값을 throw합니다.

+ +

await 연산자 다음에 나오는 문의 값이 Promise가 아니면 해당 값을 resolved Promise로 변환시킵니다.

+ +

An await can split execution flow, allowing the caller of the await's function to resume execution before the deferred continuation of the await's function. After the await defers the continuation of its function, if this is the first await executed by the function, immediate execution also continues by returning to the function's caller a pending Promise for the completion of the await's function and resuming execution of that caller.

+ +

예제

+ +

만약 Promiseawait에 넘겨지면, awaitPromise가 fulfill되기를 기다렸다가, 해당 값을 리턴합니다.

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+}
+
+async function f1() {
+  var x = await resolveAfter2Seconds(10);
+  console.log(x); // 10
+}
+
+f1();
+
+ +

{{jsxref("Global_Objects/Promise/then", "Thenable objects")}} will be fulfilled just the same.

+ +
async function f2() {
+  const thenable = {
+    then: function(resolve, _reject) {
+      resolve('resolved!')
+    }
+  };
+  console.log(await thenable); // resolved!
+}
+
+f2();
+ +

만약 값이 Promise가 아니라면, 해당 값은 resolvePromise로 변환되며 이를 기다립니다.

+ +
async function f2() {
+  var y = await 20;
+  console.log(y); // 20
+}
+f2();
+
+ +

만약 Promisereject되면, reject된 값이 throw됩니다.

+ +
async function f3() {
+  try {
+    var z = await Promise.reject(30);
+  } catch(e) {
+    console.log(e); // 30
+  }
+}
+f3();
+
+ +

try블럭 없이 rejected Promise다루기

+ +
var response = await promisedFunction().catch((err) => { console.error(err); });
+// response will be undefined if the promise is rejected
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("ESDraft", "#sec-async-function-definitions", "async functions")}}{{Spec2("ESDraft")}}
{{SpecName("ES2018", "#sec-async-function-definitions", "async functions")}}{{Spec2("ES2018")}}
{{SpecName("ES2017", "#sec-async-function-definitions", "async functions")}}{{Spec2("ES2017")}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("javascript.operators.await")}}

+
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/bitwise_operators/index.html b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html new file mode 100644 index 0000000000..e94e176e08 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html @@ -0,0 +1,540 @@ +--- +title: 비트 연산자 +slug: Web/JavaScript/Reference/Operators/Bitwise_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

비트 연산자는 피연산자를 10진수, 16진수, 8진수가 아니라, 32개의 비트(0과 1) 집합으로 취급합니다. 예를 들어, 10진수 9의 2진수 표기법은 1001입니다. 이렇게, 비트 연산자는 값의 2진수 표현을 사용해 연산하지만, 결과는 표준 JavaScript 숫자 값으로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-bitwiseoperators.html")}}
+ + + +

다음은 JavaScript의 비트 연산자를 요약한 표입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
연산자사용방법설명
비트 ANDa & b피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이면 그 비트값에 1을 반환.
비트 ORa | b피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이거나 한 쪽이 1이면 1을 반환.
비트 XORa ^ b피연산자를 비트로 바꿨을 때 대응하는 비트가 서로 다르면 1을 반환.
비트 NOT~ a피연산자의 반전된 값을 반환.
왼쪽 시프트a << bShifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.
부호 유지 오른쪽 시프트a >> bShifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
부호 버림 오른쪽 시프트a >>> bShifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.
+ +

부호 있는 32비트 정수

+ +

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format, except for zero-fill right shift which results in an unsigned 32-bit integer.

+ +

Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, or ones' complement of the number) plus one.

+ +

For example, the following encodes the integer 314:

+ +
00000000000000000000000100111010
+
+ +

The following encodes ~314, i.e. the one's complement of 314:

+ +
11111111111111111111111011000101
+
+ +

Finally, the following encodes -314, i.e. the two's complement of 314:

+ +
11111111111111111111111011000110
+
+ +

The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the sign bit.

+ +

The number 0 is the integer that is composed completely of 0 bits.

+ +
0 (base 10) = 00000000000000000000000000000000 (base 2)
+
+ +

The number -1 is the integer that is composed completely of 1 bits.

+ +
-1 (base 10) = 11111111111111111111111111111111 (base 2)
+
+ +

The number -2147483648 (hexadecimal representation: -0x80000000) is the integer that is composed completely of 0 bits except the first (left-most) one.

+ +
-2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
+
+ +

The number 2147483647 (hexadecimal representation: 0x7fffffff) is the integer that is composed completely of 1 bits except the first (left-most) one.

+ +
2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
+
+ +

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable throught a 32bit signed number.

+ +

비트 논리 연산자

+ +

비트 논리 연산자는 다음과 같이 사용됩니다.

+ + + +

& (비트 AND)

+ +

비트 연산자 AND를 비트 쌍으로 실행합니다.

+ +

Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The truth table for the AND operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba AND b
000
010
100
111
+ +
     9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
+
+ +

Bitwise ANDing any number x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.

+ +

| (비트 OR)

+ +

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba OR b
000
011
101
111
+ +
     9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
+
+ +

Bitwise ORing any number x with 0 yields x.

+ +

Bitwise ORing any number x with -1 yields -1.

+ +

^ (비트 XOR)

+ +

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba XOR b
000
011
101
110
+ +
     9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
+
+ +

Bitwise XORing any number x with 0 yields x.

+ +

Bitwise XORing any number x with -1 yields ~x.

+ +

~ (비트 NOT)

+ +

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a. The truth table for the NOT operation is:

+ + + + + + + + + + + + + + + + +
aNOT a
01
10
+ +
 9 (base 10) = 00000000000000000000000000001001 (base 2)
+               --------------------------------
+~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
+
+ +

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

+ +

비트 시프트 연산자

+ +

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

+ +

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.

+ +

<< (Left shift)

+ +

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

+ +

For example, 9 << 2 yields 36:

+ +
     9 (base 10): 00000000000000000000000000001001 (base 2)
+                  --------------------------------
+9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
+
+ +

Bitwise shifting any number x to the left by y bits yields x * 2^y.

+ +

>> (Sign-propagating right shift)

+ +

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".

+ +

For example, 9 >> 2 yields 2:

+ +
     9 (base 10): 00000000000000000000000000001001 (base 2)
+                  --------------------------------
+9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
+
+ +

Likewise, -9 >> 2 yields -3, because the sign is preserved:

+ +
     -9 (base 10): 11111111111111111111111111110111 (base 2)
+                   --------------------------------
+-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
+
+ +

>>> (Zero-fill right shift)

+ +

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.

+ +

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:

+ +
      9 (base 10): 00000000000000000000000000001001 (base 2)
+                   --------------------------------
+9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
+
+ +

However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):

+ +
      -9 (base 10): 11111111111111111111111111110111 (base 2)
+                    --------------------------------
+-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
+
+ +

예제

+ +

Flags and bitmasks

+ +

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).

+ +

Suppose there are 4 flags:

+ + + +

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:

+ +
var flags = 5;   // binary 0101
+
+ +

This value indicates:

+ + + +

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

+ +

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

+ +
var FLAG_A = 1; // 0001
+var FLAG_B = 2; // 0010
+var FLAG_C = 4; // 0100
+var FLAG_D = 8; // 1000
+
+ +

New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

+ +
var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
+
+ +

Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask masks out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:

+ +
// if we own a cat
+if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
+   // do stuff
+}
+
+ +

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

+ +
// if we own a bat or we own a cat
+if ((flags & FLAG_B) || (flags & FLAG_C)) { // (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
+   // do stuff
+}
+
+ +
// if we own a bat or cat
+var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
+if (flags & mask) { // 0101 & 0110 => 0100 => true
+   // do stuff
+}
+
+ +

Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1100 can be used to set flags C and D:

+ +
// yes, we own a cat and a duck
+var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
+flags |= mask;   // 0101 | 1100 => 1101
+
+ +

Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:

+ +
// no, we don't have an ant problem or own a cat
+var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
+flags &= mask;   // 1101 & 1010 => 1000
+
+ +

The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):

+ +
// no, we don't have an ant problem, and we don't own a cat
+var mask = ~FLAG_A & ~FLAG_C;
+flags &= mask;   // 1101 & 1010 => 1000
+
+ +

Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:

+ +
// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat
+// same thing for cats
+var mask = FLAG_B | FLAG_C;
+flags = flags ^ mask;   // 1100 ^ 0110 => 1010
+
+ +

Finally, the flags can all be flipped with the NOT operator:

+ +
// entering parallel universe...
+flags = ~flags;    // ~1010 => 0101
+
+ +

Conversion snippets

+ +

Convert a binary string to a decimal number:

+ +
var sBinString = "1011";
+var nMyNumber = parseInt(sBinString, 2);
+alert(nMyNumber); // prints 11, i.e. 1011
+
+ +

Convert a decimal number to a binary string:

+ +
var nMyNumber = 11;
+var sBinString = nMyNumber.toString(2);
+alert(sBinString); // prints 1011, i.e. 11
+
+ +

Automate Mask Creation

+ +

If you have to create many masks from some boolean values, you can automatize the process:

+ +
function createMask () {
+  var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;
+  for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
+  return nMask;
+}
+var mask1 = createMask(true, true, false, true); // 11, i.e.: 1011
+var mask2 = createMask(false, false, true); // 4, i.e.: 0100
+var mask3 = createMask(true); // 1, i.e.: 0001
+// etc.
+
+alert(mask1); // prints 11, i.e.: 1011
+
+ +

Reverse algorithm: an array of booleans from a mask

+ +

If you want to create an array of booleans from a mask you can use this code:

+ +
function arrayFromMask (nMask) {
+  // nMask must be between -2147483648 and 2147483647
+  if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("arrayFromMask - out of range"); }
+  for (var nShifted = nMask, aFromMask = []; nShifted; aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1);
+  return aFromMask;
+}
+
+var array1 = arrayFromMask(11);
+var array2 = arrayFromMask(4);
+var array3 = arrayFromMask(1);
+
+alert("[" + array1.join(", ") + "]");
+// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011
+
+ +

You can test both algorithms at the same time…

+ +
var nTest = 19; // our custom mask
+var nResult = createMask.apply(this, arrayFromMask(nTest));
+
+alert(nResult); // 19
+
+ +

For didactic purpose only (since there is the Number.toString(2) method), we show how it is possible to modify the arrayFromMask algorithm in order to create a string containing the binary representation of a number, rather than an array of booleans:

+ +
function createBinaryString (nMask) {
+  // nMask must be between -2147483648 and 2147483647
+  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
+  return sMask;
+}
+
+var string1 = createBinaryString(11);
+var string2 = createBinaryString(4);
+var string3 = createBinaryString(1);
+
+alert(string1);
+// prints 00000000000000000000000000001011, i.e. 11
+
+ +

명세

+ + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-bitwise-not-operator', 'Bitwise NOT Operator')}}
{{SpecName('ESDraft', '#sec-binary-bitwise-operators', 'Binary Bitwise Operators')}}
{{SpecName('ESDraft', '#sec-bitwise-shift-operators', 'Bitwise Shift Operators')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.bitwise")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/class/index.html b/files/ko/web/javascript/reference/operators/class/index.html new file mode 100644 index 0000000000..d15b532fbc --- /dev/null +++ b/files/ko/web/javascript/reference/operators/class/index.html @@ -0,0 +1,100 @@ +--- +title: class 식 +slug: Web/JavaScript/Reference/Operators/class +tags: + - ECMAScript 2015 + - Expression + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/class +--- +
{{jsSidebar("Operators")}}
+ +

class 표현식은 ECMAScript 2015 (ES6)에서 클래스를 정의하는 한 방법입니다. function 식과 비슷하게, class 식은 기명(named) 또는 익명(unnamed)일 수 있습니다. 기명인 경우, 클래스명은 클래스 본체(body)에서만 지역(local)입니다. JavaScript 클래스는 프로토타입(원형) 기반 상속을 사용합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-classexpression.html")}}
+ + + +

구문

+ +
var MyClass = class [className] [extends] {
+  // class body
+};
+ +

설명

+ +

class 식은 class 문과 구문이 비슷합니다. 그러나, class 식의 경우 클래스명("binding identifier")을 생략할 수 있는데 class 문으로는 할 수 없습니다.

+ +

class 문과 같이, class 식의 본체는 엄격 모드에서 실행됩니다.

+ + + +

예제

+ +

간단한 class 식

+ +

이게 바로 변수 "Foo"를 사용하여 참조할 수 있는 간단한 익명 class 식입니다.

+ +
var Foo = class {
+  constructor() {}
+  bar() {
+    return "Hello World!";
+  }
+};
+
+var instance = new Foo();
+instance.bar(); // "Hello World!"
+Foo.name; // ""
+
+ +

Named  class 식

+ +

당신이 클래스 몸통 내에서 현재 클래스를 참조하고 싶다면, 유명 class 식을 만들 수 있습니다. 이 이름은 오직 class 식 자체 범위에서만 볼 수 있습니다.

+ +
var Foo = class NamedFoo {
+  constructor() {}
+  whoIsThere() {
+    return NamedFoo.name;
+  }
+}
+var bar = new Foo();
+bar.whoIsThere(); // "NamedFoo"
+NamedFoo.name; // ReferenceError: NamedFoo가 정의되지 않음
+Foo.name; // "NamedFoo"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.class")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/comma_operator/index.html b/files/ko/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..d2c4caae0e --- /dev/null +++ b/files/ko/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,91 @@ +--- +title: 쉼표 연산자 +slug: Web/JavaScript/Reference/Operators/Comma_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +
{{jsSidebar("Operators")}}
+ +

쉼표 연산자는 각각의 피연산자를 왼쪽에서 오른쪽 순서로 평가하고, 마지막 연산자의 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
+ + + +

구문

+ +
expr1, expr2, expr3...
+ +

매개변수

+ +
+
expr1, expr2, expr3...
+
아무 표현식.
+
+ +

설명

+ +

단일 표현식을 요구하는 곳에 복수의 표현식을 사용하고 싶을 때 쉼표 연산자를 사용할 수 있습니다. 가장 흔히 사용되는 곳은 for 반복문에 다수의 매개변수를 제공할 때입니다.

+ +

쉼표 연산자는 배열, 객체, 함수의 매개변수와 호출 인수에서 사용하는 쉼표와는 전혀 다릅니다.

+ +

예제

+ +

a를 한 행에 10개의 요소를 가진 2차원 배열이라고 가정할 때, 아래 예제는 쉼표 연산자를 사용해 한 번에 i는 증가시키고 j는 감소시킵니다.

+ +

다음 코드는 2차원 배열의 대각선에 위치하는 요소의 값을 출력합니다.

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  console.log("a[" + i + "][" + j + "] = " + a[i][j]);
+
+ +

쉼표 연산자를 할당에 사용하면, 할당 연산이 표현식에 포함되지 않아 예상한 결과와는 다소 다를 수 있습니다. 다음 예제에서, ab = 3의 값(3)을 할당받지만, c = 4 표현식 역시 평가되어 콘솔에 기록됩니다. 연산자 우선순위와 결합성 때문입니다.

+ +
var a, b, c;
+
+a = b = 3, c = 4; // 콘솔에는 4를 반환
+console.log(a); // 3 (제일 왼쪽)
+
+var x, y, z;
+
+x = (y = 5, z = 6); // 콘솔에는 6을 반환
+console.log(x); // 6 (제일 오른쪽)
+
+ +

연산 후 반환

+ +

쉼표 연산자를 사용하는 다른 방법은 값을 반환하기 전에 연산을 수행하는 것입니다. 쉼표 연산자는 마지막 표현식의 평가 결과만 반환하지만, 이전 피연산자에 대해서도 평가는 수행하므로 다음과 같은 코드를 작성할 수 있습니다.

+ +
function myFunc () {
+  var x = 0;
+
+  return (x += 1, x); // ++x 와 같은 효과
+}
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.comma")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/comparison_operators/index.html b/files/ko/web/javascript/reference/operators/comparison_operators/index.html new file mode 100644 index 0000000000..ecfd46d6e5 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/comparison_operators/index.html @@ -0,0 +1,215 @@ +--- +title: 비교 연산자 +slug: Web/JavaScript/Reference/Operators/Comparison_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

JavaScript는 엄격한 비교와 형변환 비교 두 가지의 비교 방법을 모두 가지고 있습니다. 엄격(일치) 비교(===)는 두 피연산자가 같은 자료형에, 그 내용도 일치해야만 참입니다. 추상(동등) 비교(==)는 비교 전에 두 피연산자를 동일한 자료형으로 변환합니다. 관계 추상 비교(<=)의 경우 {{glossary("primitive", "원시값")}}으로 바꾸고, 같은 자료형으로 다시 바꾼후 비교를 수행합니다.

+ +

문자열의 경우 {{glossary("unicode", "유니코드")}} 값을 사용한 사전순으로 비교합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-comparisonoperators.html")}}
+ + + +

비교 연산의 특징은 다음과 같습니다.

+ + + +

동치 연산자

+ +

동등 연산자 (==)

+ +

동등 연산자는 두 피연산자의 자료형이 같지 않은 경우 같아지도록 변환한 후, 엄격 비교를 수행합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 둘 다 메모리의 같은 객체를 바라보고 있는지 판별합니다.

+ +

구문

+ +
x == y
+
+ +

예제

+ +
  1   ==  1        // true
+ "1"  ==  1        // true
+  1   == '1'       // true
+  0   == false     // true
+  0   == null      // false
+
+  0   == undefined // false
+null  == undefined // true
+
+ +

부등 연산자 (!=)

+ +

부등 연산자는 두 피연산자가 같지 않은 경우 참을 반환합니다. 피연산자의 자료형이 일치하지 않는 경우 적절한 자료형으로의 변환을 시도합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 서로 메모리의 다른 객체를 바라보고 있는지 판별합니다.

+ +

구문

+ +
x != y
+ +

예제

+ +
1 !=   2     // true
+1 !=  "1"    // false
+1 !=  '1'    // false
+1 !=  true   // false
+0 !=  false  // false
+
+ +

일치 연산자 (===)

+ +

일치 연산자는 자료형 변환 없이 두 연산자가 엄격히 같은지 판별합니다.

+ +

구문

+ +
x === y
+ +

예제

+ +
3 === 3   // true
+3 === '3' // false
+ +

불일치 연산자 (!==)

+ +

일치 연산자는 두 연산자가 같지 않거나, 같은 자료형이 아닐 때 참을 반환합니다.

+ +

구문

+ +
x !== y
+ +

예제

+ +
3 !== '3' // true
+4 !== 3   // true
+
+ +

관계 연산자

+ +

이 항목의 모든 연산자는 비교 전에 피연산자를 {{glossary("primitive", "원시값")}}으로 변환합니다. 둘 다 문자열이 되는 경우 사전순으로 비교하고, 그렇지 않으면 숫자로 변환합니다. {{jsxref("NaN")}}과의 비교는 항상 false를 반환합니다.

+ +

초과 연산자 (>)

+ +

초과 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 큰 경우 참을 반환합니다.

+ +

구문

+ +
x > y
+ +

예제

+ +
4 > 3 // true
+
+ +

이상 연산자 (>=)

+ +

이상 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같으면 참을 반환합니다.

+ +

구문

+ +
 x >= y
+ +

예제

+ +
4 >= 3 // true
+3 >= 3 // true
+
+ +

미만 연산자 (<)

+ +

미만 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작은 경우 참을 반환합니다.

+ +

구문

+ +
x < y
+ +

예제

+ +
3 < 4 // true
+ +

이하 연산자 (<=)

+ +

이하 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같으면 참을 반환합니다.

+ +

구문

+ +
 x <= y
+ +

예제

+ +
3 <= 4 // true
+
+ +

동치 연산자 사용하기

+ +

표준 동치, 동등 연산자(==, !=)는 두 피연산자를 비교하기 위해 추상 동치 비교 알고리즘(Abstract Equlity Comparison Algorithm)을 사용합니다. 피연산자 간 자료형이 일치하지 않으면 우선 변환을 시도합니다. 예를 들어 표현식 5 == '5'에서는 비교 전 오른쪽 문자열을 {{jsxref("Number")}}로 변환합니다.

+ +

엄격 동치, 일치 연산자(===, !==)는 엄격 동치 비교 알고리즘(Strict Equality Comparison Algorithm)을 사용하며, 같은 자료형을 가진 피연산자를 비교하기 위해 사용합니다. 피연산자 간 자료형이 일치하지 않으면 항상 false이므로, 5 !== '5'입니다.

+ +

피연산자의 값은 물론 특정 자료형이어야 하는 경우 일치 연산자를 사용하세요. 그렇지 않은 경우 형변환을 자동으로 해주는 동등 연산자를 사용할 수도 있습니다.

+ +

비교 과정에 자료형 변환이 필요한 경우 JavaScript는 {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 자료형을 다음과 같이 변환합니다.

+ + + +
참고: String 객체는 자료형 객체지, 문자열이 아닙니다! String 객체는 거의 쓰이지 않으며, 이런 성질로 인해 아래의 결과는 예상치 못한 값일 수 있습니다.
+ +
// true as both operands are type String (i.e. string primitives):
+'foo' === 'foo'
+
+var a = new String('foo');
+var b = new String('foo');
+
+// false as a and b are type Object and reference different objects
+a == b
+
+// false as a and b are type Object and reference different objects
+a === b
+
+// true as a and 'foo' are of different type and, the Object (a)
+// is converted to String 'foo' before comparison
+a == 'foo'
+ +

명세

+ + + + + + + + + + + + + +
Status
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality Operators')}}
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.comparison")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/conditional_operator/index.html b/files/ko/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..90f59ea4cd --- /dev/null +++ b/files/ko/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,193 @@ +--- +title: 삼항 조건 연산자 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

조건부 삼항 연산자는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자입니다. 보통 if 명령문의 단축 형태로 쓰입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
+ + + +

구문

+ +
condition ? exprIfTrue : exprIfFalse 
+ +

매개변수

+ +
+
condition
+
An expression whose value is used as a condition.
+
exprIfTrue
+
An expression which is evaluated if the condition evaluates to a {{Glossary("truthy")}} value (one which equals or can be converted to true).
+
exprIfFalse
+
An expression which is executed if the condition is {{Glossary("falsy")}} (that is, has a value which can be converted to false).
+
+ +

설명

+ +

condition이 true이면, 연산자는 expr1의 값을 반환하며, 반대의 경우 expr2를 반환한다.

+ +

예제

+ +

여러분이 술을 마실수 있는지 확인할 수 있는 간단한 예제가 여기 있습니다.

+ +
var age = 29;
+var canDrinkAlcohol = (age > 19) ? "True, over 19" : "False, under 19";
+console.log(canDrinkAlcohol); // "True, over 19"
+
+ +

isMember 변수의 값을 기준으로 다른 메시지를 보여주고자 한다면, 다음과 같이 표현할 수 있다.

+ +
"The fee is " + (isMember ? "$2.00" : "$10.00")
+
+ +

또한 다음과 같이 삼항(ternary)의 결과에 따라 변수를 할당할 수도 있다.

+ +
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
+ +

다음의 예제처럼, 다중 삼항(ternary) 평가도 가능하다(주의: 조건 연산은 우측부터 그룹핑 됩니다.)

+ +
var firstCheck = false,
+    secondCheck = false,
+    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
+
+console.log( access ); // logs "Access granted"
+ +

또한 다중 조건 IF 문과 같은 방식으로 여러개의 조건을 사용할 수도 있습니다.

+ +
var condition1 = true,
+    condition2 = false,
+    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
+
+console.log(access); // logs "true false"
+ +

참고 : 괄호는 필수는 아니며 기능에 영향을주지 않습니다. 결과가 어떻게 처리되는지 시각화하는 데 도움이됩니다.

+ +

삼항(ternary) 평가는 다른 연산을 하기 위해 쓸 수도 있습니다.

+ +
var stop = false, age = 16;
+
+age > 18 ? location.assign("continue.html") : stop = true;
+
+ +

하나의 케이스 당 둘 이상의 단일 작업을 수행하려면 쉼표로 구분하고 괄호로 묶으세요.

+ +
var stop = false, age = 23;
+
+age > 18 ? (
+    alert("OK, you can go."),
+    location.assign("continue.html")
+) : (
+    stop = true,
+    alert("Sorry, you are much too young!")
+);
+
+ +

또한, 값을 할당하는 동안 하나 이상의 연산도 가능합니다. 이 경우에, 괄호 안의 값중 마지막 쉼표 (,) 다음의 값이 최종 할당 값이 됩니다.

+ +
var age = 16;
+
+var url = age > 18 ? (
+    alert("OK, you can go."),
+    // alert returns "undefined", but it will be ignored because
+    // isn't the last comma-separated value of the parenthesis
+    "continue.html" // the value to be assigned if age > 18
+) : (
+    alert("You are much too young!"),
+    alert("Sorry :-("),
+    // etc. etc.
+    "stop.html" // the value to be assigned if !(age > 18)
+);
+
+location.assign(url); // "stop.html"
+ + + +

삼항 연산자로 반환하기

+ +

삼항 연산자는 if / else 문을 사용하는 함수를 반환하는 데 적합합니다.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else { return value2 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1 : value2
+}
+ +

다음과 같이 법적으로 술을 마실수 있는지 여부를 반환하는 함수를 만들수 있습니다.

+ +
function canDrinkAlcohol(age) {
+  return (age > 21) ? "True, over 21" : "False, under 21";
+}
+var output = canDrinkAlcohol(26);
+console.log(output); // "True, over 21"
+ +

if / else 문을 대체하는 삼항연산자가 return을 여러 번 사용하고 if 블록 내부에서 한줄만 나올때 return을 대체 할 수 있는 좋은 방법이됩니다.

+ +

삼항연산자를 여러 행으로 나누고 그 앞에 공백을 사용하면 긴 if / else 문을 매우 깔끔하게 만들 수 있습니다. 이것은 동일한 로직을 표현하지만 코드를 읽기 쉽게 만들어 줍니다.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else if (condition2) { return value2 }
+  else if (condition3) { return value3 }
+  else { return value4 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1
+       : condition2 ? value2
+       : condition3 ? value3
+       :              value4
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.conditional")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/delete/index.html b/files/ko/web/javascript/reference/operators/delete/index.html new file mode 100644 index 0000000000..037c3bcd98 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/delete/index.html @@ -0,0 +1,282 @@ +--- +title: delete 연산자 +slug: Web/JavaScript/Reference/Operators/delete +tags: + - JavaScript + - Operator + - Property + - Reference +translation_of: Web/JavaScript/Reference/Operators/delete +--- +
{{jsSidebar("Operators")}}
+ +

delete 연산자는 객체의 속성을 제거합니다. 제거한 객체의 참조를 어디에서도 사용하지 않는다면 나중에 자원을 회수합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}
+ + + +

구문

+ +
delete expression 
+ +

expression은 속성 참조여야 합니다. 예컨대,

+ +
delete object.property
+delete object['property']
+
+ +

매개변수

+ +
+
object
+
객체의 이름, 또는 평가했을 때 객체를 반환하는 표현식.
+
property
+
제거하려는 속성.
+
+ +

반환 값

+ +

true. 단, 비엄격 모드에서 속성이 {{jsxref("Object.prototype.hasOwnProperty", "자신의 속성", "", 0)}}이며 설정 불가능한 경우 false.

+ +

예외

+ +

엄격 모드에서, 속성이 자신의 속성이며 설정 불가능한 경우 {{jsxref("TypeError")}}.

+ +

설명

+ +

일반적으로 생각하고 있는것과는 다르게 delete 는 메모리 해제에 관하여 직접적으로 어떠한 작업도 하지 않습니다. 메모리 관리는 breaking references를 통하여 간접적으로 일어납니다. 자세한 걸 알고 싶다면 memory management 를 보세요.

+ +

delete연산자는 오브젝트로 부터 해당 프로퍼티를 삭제합니다. 삭제를 하면 true를 반환, 아니면 false를 반환합니다. 그렇지만 아래 경우를 고려해야만 합니다. 

+ + + +

간단한 예제입니다.

+ +
var Employee = {
+  age: 28,
+  name: 'abc',
+  designation: 'developer'
+}
+
+console.log(delete Employee.name);   // returns true
+console.log(delete Employee.age);    // returns true
+
+// 존재하지 않는 속성을 삭제하려하면
+// true를 리턴합니다.
+console.log(delete Employee.salary); // returns true
+
+ +

설정 불가능한 속성

+ +

non-configurable 속성은 delete로 삭제할 수 없으며, false를 반환할 것입니다(*strict mode에서는 SyntaxError를 발생시킴).

+ +
var Employee = {};
+Object.defineProperty(Employee, 'name', {configurable: false});
+
+console.log(delete Employee.name);  // returns false
+
+ +

{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}}, {{jsxref("Statements/const","const")}}로 선언된 변수는 non-configurable 속성으로 구분되며, delete로 삭제될 수 없습니다.

+ +
var nameOther = 'XYZ';
+
+// 우리는 이를 사용해 글로벌 속성에 접근 할 수 있습니다:
+Object.getOwnPropertyDescriptor(window, 'nameOther');
+
+// output: Object { value: "XYZ",
+//                  writable: true,
+//                  enumerable: true,
+//                  configurable: false }
+
+// "nameOther"은 var로 선언되었기 때문에
+// 이는 "non-configurable" 속성으로 구분됩니다.
+
+delete nameOther;   // return false
+ +

strict mode, this would have raised an exception.

+ +

엄격 vs. 비엄격 모드

+ +

엄격 모드에서 delete로 변수나 함수를 삭제하려고 하면 {{jsxref("SyntaxError")}}가 발생합니다. 

+ +

var로 정의된 변수는 non-configurable로 구분됩니다. 다음 예제에서, salary는 non-configurable이며 삭제될 수 없습니다. non-strict mode에서 non-configurable에 delete를 쓰면 false를 반환합니다.

+ +
function Employee() {
+  delete salary;
+  var salary;
+}
+
+Employee();
+
+ +

그러나 strict mode에서는 false를 반환하는 대신, SyntaxError를 발생시킵니다.

+ +
"use strict";
+
+function Employee() {
+  delete salary;  // SyntaxError
+  var salary;
+}
+
+// 이와 마찬가지로, delete로 함수를 삭제하는 것도
+// SyntaxError를 발생시킵니다.
+
+function DemoFunction() {
+  //some code
+}
+
+delete DemoFunction; // SyntaxError
+
+ +

예제

+ +
// 전역스코프에 adminName라는 프로퍼티를 만듭니다.
+adminName = 'xyz';
+
+// 전역스코프에 empCount라는 프로퍼티를 만듭니다.
+// var를 사용해서 선언했으므로, 이는 non-configurable로 구분됩니다.
+// let 이나 const를 사용하더라도 마찬가지로 non-configurable 입니다.
+var empCount = 43;
+
+EmployeeDetails = {
+  name: 'xyz',
+  age: 5,
+  designation: 'Developer'
+};
+
+// adminName은 전역변수입니다.
+// 이는 var를 사용하여 선언되지 않았기에 configurable하며 delete로 삭제될 수 있습니다.
+delete adminName;       // returns true
+
+// 이와 반대로, empCount는 var를 사용하였기에 non-configurable이며
+// 그러므로 delete로 삭제할 수 없습니다.
+delete empCount;       // returns false
+
+// delete는 객체의 프로퍼티를 지울 때 사용됩니다.
+delete EmployeeDetails.name; // returns true
+
+// 해당 프로퍼티가 존재하지 않는 상황에서도 "true"를 리턴합니다.
+delete EmployeeDetails.salary; // returns true
+
+// 내장되어있는 정적 프로퍼티에는 delete가 영향을 미치지 않습니다.
+delete Math.PI; // returns false
+
+// EmployeeDetails 은 전역스코프의 프로퍼티 입니다.
+// "var"를 사용하지 않고 선언되었기 때문에 이는 configurable입니다.
+delete EmployeeDetails;   // returns true
+
+function f() {
+  var z = 44;
+
+  // 지역변수에는 delete가 영향을 미치지 않습니다.
+  delete z;     // returns false
+}
+ +

delete와 프로토타입 체인

+ +

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

+ +
function Foo() {
+  this.bar = 10;
+}
+
+Foo.prototype.bar = 42;
+
+var foo = new Foo();
+
+// Returns true, since the own property
+// has been deleted on the foo object
+delete foo.bar;
+
+// foo.bar is still available, since it
+// is available in the prototype chain.
+console.log(foo.bar);
+
+// We delete the property on the prototype
+delete Foo.prototype.bar;
+
+// logs "undefined" since the property
+// is no longer inherited
+console.log(foo.bar);           
+ +

객체 요소 제거하기

+ +

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

+ +

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.

+ +
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
+delete trees[3];
+if (3 in trees) {
+    // this does not get executed
+}
+ +

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

+ +
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
+trees[3] = undefined;
+if (3 in trees) {
+    // this gets executed
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-delete-operator', 'The delete Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-delete-operator', 'The delete Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.4.1', 'The delete Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.4.1', 'The delete Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2.
+ +

브라우저 호환성

+ +
{{Compat("javascript.operators.delete")}}
+ +

크로스 브라우저 참고사항

+ +

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

+ +

If you want to use an ordered associative array in a cross-browser environment, use a {{jsxref("Map")}} object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html b/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..d078e94c38 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,409 @@ +--- +title: 구조 분해 할당 +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +tags: + - Destructuring + - ECMAScript 2015 + - JavaScript + - Operator + - Reference + - 구조 분해 +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +

구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html")}}
+ + + +

구문

+ +
var a, b, rest;
+[a, b] = [10, 20];
+console.log(a); // 10
+console.log(b); // 20
+
+[a, b, ...rest] = [10, 20, 30, 40, 50];
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // [30, 40, 50]
+
+({ a, b } = { a: 10, b: 20 });
+console.log(a); // 10
+console.log(b); // 20
+
+
+// Stage 4(finished) proposal
+({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // {c: 30, d: 40}
+
+ +

설명

+ +

객체 및 배열 리터럴 표현식을 사용하면 즉석에서 쉽게 데이터 뭉치를 만들 수 있습니다.

+ +
var x = [1, 2, 3, 4, 5];
+ +

구조 분해 할당의 구문은 위와 비슷하지만, 대신 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의합니다.

+ +
var x = [1, 2, 3, 4, 5];
+var [y, z] = x;
+console.log(y); // 1
+console.log(z); // 2
+
+ +

구조 분해 할당은 Perl이나 Python 등 다른 언어가 가지고 있는 기능입니다.

+ +

배열 구조 분해

+ +

기본 변수 할당

+ +
var foo = ["one", "two", "three"];
+
+var [one, two, three] = foo;
+console.log(one); // "one"
+console.log(two); // "two"
+console.log(three); // "three"
+
+ +

선언에서 분리한 할당

+ +

변수의 선언이 분리되어도 구조 분해를 통해 값을 할당할 수 있습니다.

+ +
var a, b;
+
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+ +

기본값

+ +

변수에 기본값을 할당하면, 분해한 값이 {{jsxref("undefined")}}일 때 그 값을 대신 사용합니다.

+ +
var a, b;
+
+[a=5, b=7] = [1];
+console.log(a); // 1
+console.log(b); // 7
+
+ +

변수 값 교환하기

+ +

하나의 구조 분해 표현식만으로 두 변수의 값을 교환할 수 있습니다.

+ +

구조 분해 할당 없이 두 값을 교환하려면 임시 변수가 필요합니다. (일부 로우 레벨 언어에서는 XOR 교체 트릭을 사용할 수 있습니다)

+ +
var a = 1;
+var b = 3;
+
+[a, b] = [b, a];
+console.log(a); // 3
+console.log(b); // 1
+
+ +

함수가 반환한 배열 분석

+ +

함수는 이전부터 배열을 반환할 수 있었습니다. 구조 분해를 사용하면 반환된 배열에 대한 작업을 더 간결하게 수행할 수 있습니다.

+ +

아래 예제에서 f()는 출력으로 배열 [1, 2]을 반환하는데, 하나의 구조 분해만으로 값을 분석할 수 있습니다.

+ +
function f() {
+  return [1, 2];
+}
+
+var a, b;
+[a, b] = f();
+console.log(a); // 1
+console.log(b); // 2
+
+ +

일부 반환 값 무시하기

+ +

다음과 같이 필요하지 않은 반환 값을 무시할 수 있습니다.

+ +
function f() {
+  return [1, 2, 3];
+}
+
+var [a, , b] = f();
+console.log(a); // 1
+console.log(b); // 3
+
+ +

반환 값을 모두 무시할 수도 있습니다.

+ +
[,,] = f();
+
+ +

변수에 배열의 나머지를 할당하기

+ +

배열을 구조 분해할 경우, 나머지 구문을 이용해 분해하고 남은 부분을 하나의 변수에 할당할 수 있습니다.

+ +
var [a, ...b] = [1, 2, 3];
+console.log(a); // 1
+console.log(b); // [2, 3]
+
+ +

나머지 요소의 오른쪽 뒤에 쉼표가 있으면 {{jsxref("SyntaxError")}}가 발생합니다.

+ +
var [a, ...b,] = [1, 2, 3];
+// SyntaxError: rest element may not have a trailing comma
+
+ +

정규 표현식과 일치하는 값 해체하기

+ +

정규 표현식의 exec() 메서드는 일치하는 부분를 찾으면 그 문자열에서 정규식과 일치하는 부분 전체를 배열의 맨 앞에, 그리고 그 뒤에 정규식에서 괄호로 묶인 각 그룹과 일치하는 부분을 포함하는 배열을 반환합니다. 구조 분해 할당은 필요하지 않은 경우 일치하는 전체 부분은 무시하고 필요한 부분만 쉽게 빼올 수 있습니다.

+ +
function parseProtocol(url) {
+  var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+  if (!parsedURL) {
+    return false;
+  }
+  console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
+
+  var [, protocol, fullhost, fullpath] = parsedURL;
+  return protocol;
+}
+
+console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"
+ +

객체 구조 분해

+ +

기본 할당

+ +
var o = {p: 42, q: true};
+var {p, q} = o;
+
+console.log(p); // 42
+console.log(q); // true
+
+ +

선언 없는 할당

+ +

구조 분해를 통해 변수의 선언과 분리하여 변수에 값을 할당할 수 있습니다.

+ +
var a, b;
+
+({a, b} = {a: 1, b: 2});
+ +
+

참고: 할당 문을 둘러싼 ( .. )는 선언 없이 객체 리터럴(object literal) 비구조화 할당을 사용할 때 필요한 구문입니다.

+ +

{a, b} = {a:1, b:2}는 유효한 독립 구문이 아닙니다. 좌변의 {a, b}이 객체 리터럴이 아닌 블록으로 간주되기 때문입니다.

+ +

하지만, ({a, b} = {a:1, b:2})는 유효한데, var {a, b} = {a:1, b:2}와 같습니다.

+ +

( .. ) 표현식 앞에는 세미콜론이 있어야 합니다. 그렇지 않을 경우 이전 줄과 연결되어 함수를 실행하는데 이용될 수 있습니다.

+
+ +

새로운 변수 이름으로 할당하기

+ +

객체로부터 속성을 해체하여 객체의 원래 속성명과는 다른 이름의 변수에 할당할 수 있습니다.

+ +
var o = {p: 42, q: true};
+var {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true
+ +

기본값

+ +

객체로부터 해체된 값이 undefined인 경우, 변수에 기본값을 할당할 수 있습니다.

+ +
var {a = 10, b = 5} = {a: 3};
+
+console.log(a); // 3
+console.log(b); // 5
+ +

기본값 갖는 새로운 이름의 변수에 할당하기

+ +

새로운 변수명 할당과 기본값 할당을 한번에 할 수 있습니다.

+ +
var {a: aa = 10, b: bb = 5} = {a: 3};
+
+console.log(aa); // 3
+console.log(bb); // 5
+
+ +

함수 매개변수의 기본값 설정하기

+ +

ES5 버전

+ +
function drawES5Chart(options) {
+  options = options === undefined ? {} : options;
+  var size = options.size === undefined ? 'big' : options.size;
+  var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
+  var radius = options.radius === undefined ? 25 : options.radius;
+  console.log(size, cords, radius);
+  // 이제 드디어 차트 그리기 수행
+}
+
+drawES5Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +

ES2015 버전

+ +
function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
+  console.log(size, cords, radius);
+  // 차트 그리기 수행
+}
+
+drawES2015Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +
+

위의 drawES2015Chart 함수의 원형에서 구조 분해된 좌변에 빈 오브젝트 리터럴을 할당하는 것을 볼 수 있습니다 {size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}. 빈 오브젝트를 우변에 할당하지 않고도 함수를 작성할 수 있습니다. 하지만, 지금의 형태에서는 단순히 drawES2015Chart()와 같이 어떤 매개변수 없이도 호출할 수 있지만, 우변의 빈 오브젝트 할당을 없앤다면 함수 호출시 적어도 하나의 인자가 제공되어야만 합니다. 이 함수가 어떠한 매개변수 없이도 호출할 수 있길 원한다면 지금 형태가 유용하고, 무조건 객체를 넘기길 원하는 경우에는 빈 객체 할당을 하지 않는 것이 유용할 수 있습니다.

+
+ +

중첩된 객체 및 배열의 구조 분해

+ +
var metadata = {
+    title: "Scratchpad",
+    translations: [
+       {
+        locale: "de",
+        localization_tags: [ ],
+        last_edit: "2014-04-14T08:43:37",
+        url: "/de/docs/Tools/Scratchpad",
+        title: "JavaScript-Umgebung"
+       }
+    ],
+    url: "/en-US/docs/Tools/Scratchpad"
+};
+
+var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
+
+console.log(englishTitle); // "Scratchpad"
+console.log(localeTitle);  // "JavaScript-Umgebung"
+ +

for of 반복문과 구조 분해

+ +
var people = [
+  {
+    name: "Mike Smith",
+    family: {
+      mother: "Jane Smith",
+      father: "Harry Smith",
+      sister: "Samantha Smith"
+    },
+    age: 35
+  },
+  {
+    name: "Tom Jones",
+    family: {
+      mother: "Norah Jones",
+      father: "Richard Jones",
+      brother: "Howard Jones"
+    },
+    age: 25
+  }
+];
+
+for (var {name: n, family: { father: f } } of people) {
+  console.log("Name: " + n + ", Father: " + f);
+}
+
+// "Name: Mike Smith, Father: Harry Smith"
+// "Name: Tom Jones, Father: Richard Jones"
+ +

함수 매개변수로 전달된 객체에서 필드 해체하기

+ +
function userId({id}) {
+  return id;
+}
+
+function whois({displayName: displayName, fullName: {firstName: name}}){
+  console.log(displayName + " is " + name);
+}
+
+var user = {
+  id: 42,
+  displayName: "jdoe",
+  fullName: {
+      firstName: "John",
+      lastName: "Doe"
+  }
+};
+
+console.log("userId: " + userId(user)); // "userId: 42"
+whois(user); // "jdoe is John"
+ +

이 예제는 user 객체로부터 id, displayNamefirstName 을 해체해 출력합니다.

+ +

계산된 속성 이름과 구조 분해

+ +

계산된 속성 이름(computed property name)은, 객체 리터럴과 비슷하게 구조 분해에도 사용될 수 있습니다.

+ +
let key = "z";
+let { [key]: foo } = { z: "bar" };
+
+console.log(foo); // "bar"
+
+ +

객체 구조 분해에서 Rest

+ +

Rest/Spread Properties for ECMAScript 제안(stage 3)에서는 구조 분해에 rest 구문을 추가하고 있습니다. rest 속성은 구조 분해 패턴으로 걸러지지 않은 열거형 속성의 키를 가진 나머지 항목들을 모읍니다.

+ +
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
+a; // 10
+b; // 20
+rest; // { c: 30, d: 40 }
+
+ +

속성 이름이 유효한 JavaScript 식별자명이 아닌 경우

+ +

구조 분해는 JavaScript {{glossary("Identifier", "식별자")}} 이름으로 적합하지 않은 속성명이 제공된 경우에도 이용할 수 있습니다. 이 때는 대체할 유효한 식별자명을 제공해야 합니다.

+ +
const foo = { 'fizz-buzz': true };
+const { 'fizz-buzz': fizzBuzz } = foo;
+
+console.log(fizzBuzz); // "true"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+
+ + +

{{Compat("javascript.operators.destructuring")}}

+
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/equality/index.html b/files/ko/web/javascript/reference/operators/equality/index.html new file mode 100644 index 0000000000..5ebe238590 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/equality/index.html @@ -0,0 +1,123 @@ +--- +title: 동등 연산자(==) +slug: Web/JavaScript/Reference/Operators/Equality +translation_of: Web/JavaScript/Reference/Operators/Equality +--- +
{{jsSidebar("Operators")}}
+ +

동등 연산자(==)는 두 개의 피연산자가 동일한지 확인하며, Boolean값을 반환합니다. 일치 연산자(===)와는 다르게 다른 타입의 피연산자들끼리의 비교를 시도합니다. 

+ +
{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}
+ + + +

문법

+ +
x == y
+
+ +

상세 설명

+ +

동등 연산자 (== 와 !=)는 두 피연산자를 비교하기 위해 Abstract Equality Comparison Algorithm를 사용합니다. 다음과 같이 간략히 설명할 수 있습니다:

+ + + +

일치연산자 (===)와의 가장 두드러지는 차이점은 일치 연산자는 타입변환을 시도하지 않는다는 것입니다. 일치 연산자는 다른 타입을 가진 피연산자는 다르다고 판단합니다.

+ +

예시

+ +

타입변환 없이 비교

+ +
1 == 1;              // true
+"hello" == "hello";  // true
+ +

타입변환을 이용한 비교

+ +
"1" ==  1;            // true
+1 == "1";             // true
+0 == false;           // true
+0 == null;            // false
+0 == undefined;       // false
+0 == !!null;          // true, look at Logical NOT operator
+0 == !!undefined;     // true, look at Logical NOT operator
+null == undefined;    // true
+
+const number1 = new Number(3);
+const number2 = new Number(3);
+number1 == 3;         // true
+number1 == number2;   // false
+ +

객체들 간의 비교

+ +
const object1 = {"key": "value"}
+const object2 = {"key": "value"};
+
+object1 == object2 // false
+object2 == object2 // true
+ +

String과 String objects의 비교

+ +

new String() 을 통해 생성된 문자열들은 객체입니다. 이 객체중 하나를 문자열과 비교한다면, String 객체가 문자열로 변환된 후 비교될 것입니다. 그러나 두개의 피연산자 모두 String 객체라면, 객체로써 비교가 이루어지기 때문에 같은 값으로 취급될려면 같은 객체를 참조하고 있어야 합니다:

+ +
const string1 = "hello";
+const string2 = String("hello");
+const string3 = new String("hello");
+const string4 = new String("hello");
+
+console.log(string1 == string2); // true
+console.log(string1 == string3); // true
+console.log(string2 == string3); // true
+console.log(string3 == string4); // false
+console.log(string4 == string4); // true
+ +

Comparing Dates and strings

+ +
const d = new Date('December 17, 1995 03:24:00');
+const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
+console.log(d == s);    //true
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.equality")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/expression_closures/index.html b/files/ko/web/javascript/reference/operators/expression_closures/index.html new file mode 100644 index 0000000000..bf44be6cd7 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/expression_closures/index.html @@ -0,0 +1,79 @@ +--- +title: 표현식 클로저 +slug: Web/JavaScript/Reference/Operators/Expression_closures +tags: + - Function + - JavaScript + - Non-standard + - Obsolete + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Expression_closures +--- +
{{JSSidebar("Operators")}}{{Non-standard_Header}}{{Obsolete_Header("gecko60")}} +
Non-standard. Do not use!
+The expression closure syntax is a deprecated Firefox-specific feature and has been removed starting with Firefox 60. For future-facing usages, consider using arrow functions.
+
+ +

클로져는 간단한 함수를 작성하기 위한 짧은 함수구문 입니다.

+ +

Syntax

+ +
function [name]([param1[, param2[, ..., paramN]]])
+   expression
+
+ +

Parameters

+ +
+
name
+
함수의 이름입니다. 익명함수의 경우에는 생략할 수 있습니다. 이름은 함수본문에만 국한됩니다.
+
paramN
+
함수에 전달할 인수의 이름입니다. 함수는 최대 255개의 인수를 가질 수 있습니다.
+
expression
+
함수의 본문을 구성하는 표현식입니다.
+
+ +

Description

+ +

이 추가적인 기능은 람다 표기법과 비슷한 언어를 제공하기위해 간단한 기능을 작성하는데 필요한 단축형일 뿐입니다.

+ +

JavaScript 1.7 and older:

+ +
function(x) { return x * x; }
+ +

JavaScript 1.8:

+ +
function(x) x * x
+ +

이 구문을 사용하면 중괄호나 'return'문을 생략하여 암시적으로 만들 수 있습니다. 코드를 더 짧게 만들 수 있는 것 이외의 이방법으로 얻을 수 있는 추가 이점은 없습니다.

+ +

Examples

+ +

바인딩 이벤트 리스너의 간단한 예제:

+ +
 document.addEventListener('click', function() false, true);
+
+ +

JavaScript 1.6의 일부 배열 함수에 이 표기법을 사용합니다:

+ +
elems.some(function(elem) elem.type == 'text');
+
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.expression_closures")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/function/index.html b/files/ko/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..5f4977bfc7 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/function/index.html @@ -0,0 +1,154 @@ +--- +title: 함수 표현식 +slug: Web/JavaScript/Reference/Operators/function +tags: + - Function + - JavaScript + - Operator + - Primary Expressions +translation_of: Web/JavaScript/Reference/Operators/function +--- +
{{jsSidebar("Operators")}}
+ +

function 키워드는 어떤 표현식(expression) 내에서 함수를 정의하는 데 사용될 수 있습니다.

+ +

또한 Function 생성자와 함수 선언(function declaration)을 이용해 함수를 정의할 수도 있습니다.  

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html")}}
+ + + +

구문

+ +
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) { statements };
+ +

ES2015에서 화살표 함수(arrow functions)를 사용할 수도 있습니다.

+ +

매개변수

+ +
+
name
+
함수 이름. 함수가 이름 없는(anonymous) 함수인 경우, 생략될 수 있음. 이 함수 이름은 함수의 몸통 내에서만 사용할 수 있습니다.
+
paramN
+
함수로 전달되는 인수(argument) 의 이름.
+
statements
+
함수 몸통을 구성하는 문(statement).
+
+ +

설명

+ +

함수 표현식(function expression)은 function 문과 매우 비슷하고 구문(syntax)이 거의 같습니다 (자세한 사항은 function 문 참조). 함수 표현식과 function 문 사이의 주요 차이점은 함수 이름으로, 함수 표현식으로 익명 함수를 만들 경우 이 이름을 생략할 수 있습니다. 함수 표현식은 정의하자마자 실행되는  IIFE (즉시 호출되는 함수 표현식)로 사용될 수 있습니다. 더 자세한 정보는 함수 장 참조.

+ +

Function expression 끌어올리기

+ +

자바스크립트에서 함수 표현식은 {{jsxref("Statements/function", "함수 선언", "#Function_declaration_hoisting")}}과는 달리 끌어올려지지 않습니다. 함수 표현식을 정의하기 전에는 사용할 수 없습니다.

+ +
console.log(notHoisted) // undefined
+//even the variable name is hoisted, the definition wasn't. so it's undefined.
+notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log('bar');
+};
+ +

유명(named) 함수 표현식

+ +

함수 몸통 안 쪽에서 현재 함수를 참고하고 싶다면, 유명 함수를 생성해야 합니다. 이 함수 이름은 함수의 몸통(범위) 안에서만 사용할 수 있습니다. 이로써 비표준 arguments.callee 속성을 사용하는 것을 피할 수도 있습니다.

+ +
var math = {
+  'factit': function factorial(n) {
+    console.log(n)
+    if (n <= 1)
+      return 1;
+    return n * factorial(n - 1);
+  }
+};
+
+math.factit(3) //3;2;1;
+
+ +

함수가 할당된 변수는 name 속성을 가지게됩니다. 다른 변수에 할당되더라도 그 name 속성의 값은 변하지 않습니다. 함수의 이름이 생략되었다면, name 속성의 값은 그 변수의 이름(암묵적 이름)이 될 것입니다. 함수의 이름이 있다면 name 속성의 값은 그 함수의 이름(명시적 이름)이 될 것입니다. 이는 화살표 함수(arrow functions)에도 적용됩니다 (화살표 함수는 이름을 가지지 않으므로 해당 변수에 암묵적인 이름만 줄 수 있습니다).

+ +
var foo = function() {}
+foo.name // "foo"
+
+var foo2 = foo
+foo2.name // "foo"
+
+var bar = function baz() {}
+bar.name // "baz"
+
+console.log(foo === foo2); // true
+console.log(typeof baz); // undefined
+console.log(bar === baz); // false (errors because baz == undefined)
+
+ +

 

+ +

Examples

+ +

다음 예제는 이름 없는 함수를 정의하고 그 함수를 x에 할당합니다. 함수는 인수의 제곱을 반환합니다:

+ +
var x = function(y) {
+   return y * y;
+};
+ +

callback으로 더 자주 사용됩니다:

+ +
button.addEventListener('click', function(event) {
+    console.log('button is clicked!')
+})
+ +

 

+ +

 

+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.5에서 구현됨.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.function")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/operators/function_star_/index.html b/files/ko/web/javascript/reference/operators/function_star_/index.html new file mode 100644 index 0000000000..7187f985bc --- /dev/null +++ b/files/ko/web/javascript/reference/operators/function_star_/index.html @@ -0,0 +1,85 @@ +--- +title: function* expression +slug: Web/JavaScript/Reference/Operators/function* +tags: + - ECMAScript6 + - Function + - Generator + - JavaScript +translation_of: Web/JavaScript/Reference/Operators/function* +--- +
{{jsSidebar("Operators")}}
+ +

function* keyword 는 표현식 내에서 generator function 을 정의합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}
+ +

Syntax

+ +
function* [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+}
+ +

Parameters

+ +
+
name
+
함수명. 생략하면, 익명 함수가 됩니다.  함수명은 함수내에만 한정됩니다.
+
paramN
+
함수에 전달되는 인수의 이름. 함수는 최대 255 개의 인수를 가질 수 있습니다.
+
statements
+
함수의 본체를 구성하는 구문들.
+
+ +

Description

+ +

function* expression 은 {{jsxref('Statements/function*', 'function* statement')}} 과 매우 유사하고 형식도 같습니다. function* expression 과 function* statement 의 주요한 차이점은 함수명으로, function* expressions 에서는 익명 함수로 만들기 위해 함수명이 생략될 수 있습니다.보다 자세한 내용은 functions 을 참조하십시오.

+ +

Examples

+ +

아래의 예제는 이름이 없는 generator function 을 정의하고 이를 x 에 할당합니다. function 은 인자로 들어온 값의 제곱을 생산(yield)합니다.

+ +
var x = function*(y) {
+   yield y * y;
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{Compat("javascript.operators.function_star")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html b/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html new file mode 100644 index 0000000000..927b613dc6 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html @@ -0,0 +1,174 @@ +--- +title: 생성기 내포 +slug: Web/JavaScript/Reference/Operators/Generator_comprehensions +tags: + - JavaScript + - Non-standard + - Obsolete + - Reference +translation_of: Archive/Web/JavaScript/Generator_comprehensions +--- +
{{JSSidebar("Operators")}}{{Non-standard_Header}}{{Obsolete_Header("gecko58")}} +
+

Non-standard. Do not use!
+ The generator comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using {{JSxRef("Statements/function*", "generator", "", 1)}}.

+
+
+ +

The generator comprehension syntax was a JavaScript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. However, it has been removed from the standard and the Firefox implementation. Do not use it!

+ +

Syntax

+ +
(for (x of iterable) x)
+(for (x of iterable) if (condition) x)
+(for (x of iterable) for (y of iterable) x + y)
+
+ +

Description

+ +

Inside generator comprehensions, these two kinds of components are allowed:

+ + + +

The for-of iteration is always the first component. Multiple for-of iterations or if statements are allowed.

+ +

A significant drawback of {{JSxRef("Operators/Array_comprehensions","array comprehensions","","true")}} is that they cause an entire new array to be constructed in memory. When the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a new array can be problematic.

+ +

Generators enable lazy computation of sequences, with items calculated on-demand as they are needed. Generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily. You can think of them as short hand syntax for creating generators.

+ +

Suppose we have an iterator it which iterates over a large sequence of integers. We want to create a new iterator that will iterate over their doubles. An array comprehension would create a full array in memory containing the doubled values:

+ +
var doubles = [for (i in it) i * 2];
+
+ +

A generator comprehension on the other hand would create a new iterator which would create doubled values on demand as they were needed:

+ +
var it2 = (for (i in it) i * 2);
+console.log(it2.next()); // The first value from it, doubled
+console.log(it2.next()); // The second value from it, doubled
+
+ +

When a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted:

+ +
var result = doSomething(for (i in it) i * 2);
+
+ +

The significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.

+ +

Examples

+ +

Simple generator comprehensions

+ +
(for (i of [1, 2, 3]) i * i );
+// generator function which yields 1, 4, and 9
+
+[...(for (i of [1, 2, 3]) i * i )];
+// [1, 4, 9]
+
+var abc = ['A', 'B', 'C'];
+(for (letters of abc) letters.toLowerCase());
+// generator function which yields "a", "b", and "c"
+
+ +

Generator comprehensions with if statement

+ +
var years = [1954, 1974, 1990, 2006, 2010, 2014];
+
+(for (year of years) if (year > 2000) year);
+// generator function which yields 2006, 2010, and 2014
+
+(for (year of years) if (year > 2000) if (year < 2010) year);
+// generator function which yields 2006, the same as below:
+
+(for (year of years) if (year > 2000 && year < 2010) year);
+// generator function which yields 2006
+
+ +

Generator comprehensions compared to generator function

+ +

An easy way to understand generator comprehension syntax, is to compare it with the generator function.

+ +

Example 1: Simple generator.

+ +
var numbers = [1, 2, 3];
+
+// Generator function
+(function*() {
+  for (let i of numbers) {
+    yield i * i;
+  }
+})();
+
+// Generator comprehension
+(for (i of numbers) i * i );
+
+// Result: both return a generator which yields [1, 4, 9]
+
+ +

Example 2: Using if in generator.

+ +
var numbers = [1, 2, 3];
+
+// Generator function
+(function*() {
+  for (let i of numbers) {
+    if (i < 3) {
+      yield i * 1;
+    }
+  }
+})();
+
+// Generator comprehension
+(for (i of numbers) if (i < 3) i);
+
+// Result: both return a generator which yields [1, 2]
+ +

Specifications

+ +

Generator comprehensions were initially in the ECMAScript 2015 draft, but got removed in revision 27 (August 2014). Please see older revisions of ES2015 for specification semantics.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.generator_comprehensions")}}

+ +

Differences to the older JS1.7/JS1.8 comprehensions

+ +
JS1.7/JS1.8 comprehensions are removed from Gecko 46 ({{bug(1220564)}}).
+ +

Old comprehensions syntax (do not use anymore!):

+ +
(X for (Y in Z))
+(X for each (Y in Z))
+(X for (Y of Z))
+
+ +

Differences:

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/grouping/index.html b/files/ko/web/javascript/reference/operators/grouping/index.html new file mode 100644 index 0000000000..a8823ff961 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/grouping/index.html @@ -0,0 +1,92 @@ +--- +title: 그룹 연산자 +slug: Web/JavaScript/Reference/Operators/Grouping +tags: + - JavaScript + - Operator + - Primary Expressions + - Reference +translation_of: Web/JavaScript/Reference/Operators/Grouping +--- +
{{jsSidebar("Operators")}}
+ +

그룹 연산자 ()는 표현식 내에서 평가의 우선순위를 제어합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-groupingoperator.html")}}
+ + + +

구문

+ +
 ( )
+ +

설명

+ +

그룹 연산자는 표현식이나 중첩 표현식 주위를 감싸는 한 쌍의 괄호로 이루어진 연산자로, 감싸인 식이 더 높은 우선순위를 갖도록 일반적인 연산자 우선순위를 재정의합니다. 이름 그대로, 그룹 연산자는 괄호 안의 내용을 묶습니다.

+ +

예제

+ +

다음 예제에서는 곱셈과 나눗셈 이후 덧셈과 뺄셈을 사용하는 일반적인 연산 순서를 그룹 연산자를 사용해 바꿉니다.

+ +
var a = 1;
+var b = 2;
+var c = 3;
+
+// 기본 우선순위
+a + b * c     // 7
+// 이것과 같음
+a + (b * c)   // 7
+
+// 더하기를 곱하기보다 먼저 하도록
+// 우선순위 변경
+(a + b) * c   // 9
+
+// 이것과 같음
+a * c + b * c // 9
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-grouping-operator', 'The Grouping Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-grouping-operator', 'The Grouping Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.6', 'The Grouping Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.1.4', 'The Grouping Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.grouping")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/in/index.html b/files/ko/web/javascript/reference/operators/in/index.html new file mode 100644 index 0000000000..dea26b496d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/in/index.html @@ -0,0 +1,188 @@ +--- +title: in 연산자 +slug: Web/JavaScript/Reference/Operators/in +tags: + - JavaScript + - Operator + - Relational Operators + - 관계형 연산자 + - 연산자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Operators/in +--- +
{{jsSidebar("Operators")}}
+ +

 in 연산자는 명시된 속성이 명시된 객체에 존재하면 true를 반환합니다.

+ +

구문

+ +
속성 in 객체명
+ +

인자

+ +
+
속성
+
속성의 이름이나 배열의 인덱스를 뜻하는 문자열 또는 수 값입니다.
+
+ +
+
객체명
+
객체의 이름입니다.
+
+ +

설명

+ +

 다음 예제들은 in 연산자의 용도를 보여 줍니다.

+ +
// 배열
+var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+0 in trees         // true를 반환합니다.
+3 in trees         // true를 반환합니다.
+(1 + 2) in trees   // true를 반환합니다. 연산자 우선 순위에 의하여 이 구문의 괄호는 없어도 됩니다.
+6 in trees         // false를 반환합니다.
+"bay" in trees     // false를 반환합니다. 당신은 배열의 내용이 아닌, 인덱스 값을 명시하여야 합니다.
+"length" in trees  // true를 반환합니다. length는 Array(배열) 객체의 속성입니다.
+
+// 미리 정의된 객체
+"PI" in Math       // true를 반환합니다.
+"P" + "I" in Math  // true를 반환합니다.
+
+// 사용자가 정의한 객체
+var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
+"company" in myCar // true를 반환합니다.
+"model" in myCar   // true를 반환합니다.
+
+ +

 당신은 반드시 in 연산자의 오른쪽에 객체를 명시하여야 합니다. 예컨대 당신은 String 생성자로 만들어진 문자열을 명시할 수 있지만 문자열 리터럴은 명시할 수 없습니다.

+ +
var color1 = new String("green");
+"length" in color1 // true를 반환합니다.
+
+var color2 = "coral";
+"length" in color2 // color2는 String 객체가 아니기에 오류를 냅니다.
+
+ +

제거되었거나 정의되지 않은 속성에 대하여 in 연산자 사용하기

+ +

 in 연산자는 delete 연산자로 제거된 속성에 대하여 false를 반환합니다.

+ +
var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
+delete myCar.company;
+"company" in myCar; // false를 반환합니다.
+
+var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+delete trees[3];
+3 in trees; // false를 반환합니다.
+
+ +

 만약 당신이 속성을 {{jsxref("Global_Objects/undefined", "undefined")}}로 설정하였는데 그것을 제거하지 않으면, in 연산자는 그 속성에 대하여 true를 반환합니다.

+ +
var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
+myCar.company = undefined;
+"company" in myCar; // true를 반환합니다.
+
+ +
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+trees[3] = undefined;
+3 in trees; // true를 반환합니다.
+
+ +

상속된 속성

+ +

 in 연산자는 프로토타입 체인에 의하여 접근할 수 있는 속성에 대하여 true를 반환합니다.

+ +
"toString" in {}; // true를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세StatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES3')}}초기의 정의가 담겨 있습니다. JavaScript 1.4에 추가되었습니다.
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
기능ChromeFirefox (Gecko)Internet ExplorerOperaSafari
지원{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
기능AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
지원{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/operators/index.html b/files/ko/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..9605b84278 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/index.html @@ -0,0 +1,304 @@ +--- +title: 식 및 연산자 +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - Operators + - Overview + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

이 장은 JavaScript의 모든 연산자operator, 식expression 및 키워드를 나열합니다.

+ +

항목별 식 및 연산자

+ +

알파벳순 목록은 왼쪽 사이드바를 보세요.

+ +

기본 식

+ +

기본 키워드 및 JavaScript의 일반 식.

+ +
+
{{JSxRef("Operators/this", "this")}}
+
this 키워드는 실행 문맥의 특별한 속성을 가리킵니다.
+
{{JSxRef("Operators/function", "function")}}
+
function 키워드는 함수를 정의합니다.
+
{{JSxRef("Operators/class", "class")}}
+
class 키워드는 클래스를 정의합니다.
+
{{JSxRef("Operators/function*", "function*")}}
+
function* 키워드는 생성기generator 함수 식을 정의합니다.
+
{{JSxRef("Operators/yield", "yield")}}
+
생성기 함수를 일시정지 및 재개합니다.
+
{{JSxRef("Operators/yield*", "yield*")}}
+
다른 생성기 함수 또는 순회가능 객체로 위임합니다.
+
{{JSxRef("Operators/async_function", "async function")}}
+
async function은 비동기 함수 표현식을 정의합니다.
+
+ +
+
{{JSxRef("Operators/await", "await")}}
+
비동기 함수를 일시 중지했다가 다시 시작하고 promise의 resolution/rejection을 ​​기다립니다.
+
+ +
+
{{JSxRef("Global_Objects/Array", "[]")}}
+
배열 초기자 및 리터럴 구문.
+
{{JSxRef("Operators/Object_initializer", "{}")}}
+
객체 초기자 및 리터럴 구문.
+
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
+
정규식 리터럴 구문.
+
{{JSxRef("Operators/Grouping", "( )")}}
+
그룹 연산자.
+
+ +

좌변 식

+ +

좌변값은 할당 대상입니다.

+ +
+
{{JSxRef("Operators/Property_accessors", "Property accessors", "", 1)}}
+
속성 접근자는 객체의 속성 또는 메서드에 대한 접근 방법을 제공합니다.
+ (object.property, object["property"])
+
{{JSxRef("Operators/new", "new")}}
+
new 연산자는 생성자의 인스턴스를 만듭니다.
+
{{JSxRef("Operators/new%2Etarget", "new.target")}}
+
생성자 문맥에서, new.target은 {{jsxref("Operators/new", "new")}}에 의해 호출된 생성자를 말합니다.
+
{{JSxRef("Operators/super", "super")}}
+
super 키워드는 부모 생성자를 호출합니다.
+
{{JSxRef("Operators/Spread_syntax", "...obj")}}
+
전개 연산자는 (함수 호출 시) 매개변수 여럿이나, (배열 리터럴에서) 다수의 요소를 필요로 하는 곳에서 표현식을 확장합니다.
+
+ +

증가 및 감소

+ +

접두/접미 증감 연산자입니다.

+ +
+
{{JSxRef("Operators/Increment", "A++")}}
+
접미 증가 연산자.
+
{{JSxRef("Operators/Decrement", "A--")}}
+
접미 감소 연산자.
+
{{JSxRef("Operators/Increment", "++A")}}
+
접두 증가 연산자.
+
{{JSxRef("Operators/Decrement", "--A")}}
+
접두 감소 연산자.
+
+ +

단항 연산자

+ +

단항 연산은 피연산자가 하나뿐인 연산입니다.

+ +
+
{{JSxRef("Operators/delete", "delete")}}
+
delete 연산자는 객체에서 속성을 지웁니다.
+
{{JSxRef("Operators/void", "void")}}
+
void 연산자는 식의 반환값을 버립니다.
+
{{JSxRef("Operators/typeof", "typeof")}}
+
typeof 연산자는 주어진 객체의 형을 판별합니다.
+
{{JSxRef("Operators/Unary_plus", "+")}}
+
단항 더하기 연산자는 피연산자를 숫자로 변환합니다.
+
{{JSxRef("Operators/Unary_negation", "-")}}
+
단항 부정 연산자는 피연산자를 숫자로 변환한 뒤 부호를 바꿉니다.
+
{{JSxRef("Operators/Bitwise_NOT", "~")}}
+
비트 NOT 연산자.
+
{{JSxRef("Operators/Logical_NOT", "!")}}
+
논리 NOT 연산자.
+
+ +

산술 연산자

+ +

산술 연산자는 피연산자로 숫자 값(리터럴이나 변수)을 취하고 숫자 값 하나를 반환합니다.

+ +
+
{{JSxRef("Operators/Addition", "+")}}
+
덧셈 연산자.
+
{{JSxRef("Operators/Subtraction", "-")}}
+
뺄셈 연산자.
+
{{JSxRef("Operators/Division", "/")}}
+
나눗셈 연산자.
+
{{JSxRef("Operators/Multiplication", "*")}}
+
곱셈 연산자.
+
{{JSxRef("Operators/Remainder", "%")}}
+
나머지 연산자.
+
+ +
+
{{JSxRef("Operators/Exponentiation", "**")}}
+
지수 연산자.
+
+ +

관계 연산자

+ +

비교 연산자는 피연산자를 비교하고, 비교가 참인지 여부를 나타내는 {{jsxref("Boolean")}} 값을 반환합니다.

+ +
+
{{JSxRef("Operators/in", "in")}}
+
in 연산자는 객체에 주어진 속성이 있는지를 결정합니다.
+
{{JSxRef("Operators/instanceof", "instanceof")}}
+
instanceof 연산자는 객체가 다른 객체의 인스턴스인지 판별합니다.
+
{{JSxRef("Operators/Less_than", "<")}}
+
작음 연산자.
+
{{JSxRef("Operators/Greater_than", ">")}}
+
큼 연산자.
+
{{JSxRef("Operators/Less_than_or_equal", "<=")}}
+
작거나 같음 연산자.
+
{{JSxRef("Operators/Greater_than_or_equal", ">=")}}
+
크거나 같음 연산자.
+
+ +
+

참고: => 는 연산자가 아니고, 화살표 함수의 표기법입니다.

+
+ +

같음 연산자

+ +

같음 연산자의 평가 결과는 항상 {{jsxref("Boolean")}} 형으로 비교가 참인지 나타냅니다.

+ +
+
{{JSxRef("Operators/Equality", "==")}}
+
동등 연산자.
+
{{JSxRef("Operators/Inequality", "!=")}}
+
부등 연산자.
+
{{JSxRef("Operators/Strict_equality", "===")}}
+
일치identity 연산자.
+
{{JSxRef("Operators/Strict_inequality", "!==")}}
+
불일치 연산자.
+
+ +

비트 시프트 연산자

+ +

피연산자의 모든 비트를 이동shift하는 연산.

+ +
+
{{JSxRef("Operators/Left_shift", "<<")}}
+
비트 좌로 시프트 연산자.
+
{{JSxRef("Operators/Right_shift", ">>")}}
+
비트 우로 시프트 연산자.
+
{{JSxRef("Operators/Unsigned_right_shift", ">>>")}}
+
비트 부호 없는 우로 시프트 연산자.
+
+ +

이진 비트 연산자

+ +

비트 연산자는 피연산자를 32비트 집합(0과 1)으로 다루고 표준 JavaScript 숫자 값을 반환합니다.

+ +
+
{{JSxRef("Operators/Bitwise_AND", "&")}}
+
비트 AND.
+
{{JSxRef("Operators/Bitwise_OR", "|")}}
+
비트 OR.
+
{{JSxRef("Operators/Bitwise_XOR", "^")}}
+
비트 XOR.
+
+ +

이진 논리 연산자

+ +

논리 연산자는 보통 사용될 때 불리언(논리) 값으로 사용되고, 불리언 값을 반환합니다.

+ +
+
{{JSxRef("Operators/Logical_AND", "&&")}}
+
논리 AND.
+
{{JSxRef("Operators/Logical_OR", "||")}}
+
논리 OR.
+
{{JSxRef("Operators/Nullish_coalescing_operator", "??")}}
+
Nullish 통합 연산자.
+
+ +

조건부(삼항) 연산자

+ +
+
{{JSxRef("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+ +

조건부 연산자는 조건의 논리값에 따라 두 값 중 하나를 반환합니다.

+ +

선택적 연결 연산자

+ +
+
{{JSxRef("Operators/Optional_chaining", "?.")}}
+
+

선택적 연결 연산자는 참조가 nullish (null 또는 undefined) 인 경우 오류를 발생시키는 대신 undefined를 반환합니다.

+
+
+ +

할당 연산자

+ +

할당 연산자는 값을 그 우변 피연산자의 값에 따라 좌변 피연산자에 할당합니다.

+ +
+
{{JSxRef("Operators/Assignment", "=")}}
+
할당 연산자.
+
{{JSxRef("Operators/Multiplication_assignment", "*=")}}
+
곱셈 할당.
+
{{JSxRef("Operators/Exponentiation_assignment", "**=")}}
+
Exponentiation assignment.
+
{{JSxRef("Operators/Division_assignment", "/=")}}
+
나눗셈 할당.
+
{{JSxRef("Operators/Remainder_assignment", "%=")}}
+
나머지 할당.
+
{{JSxRef("Operators/Addition_assignment", "+=")}}
+
덧셈 할당.
+
{{JSxRef("Operators/Subtraction_assignment", "-=")}}
+
뺄셈 할당
+
{{JSxRef("Operators/Left_shift_assignment", "<<=")}}
+
좌로 이동 할당.
+
{{JSxRef("Operators/Right_shift_assignment", ">>=")}}
+
우로 이동 할당.
+
{{JSxRef("Operators/Unsigned_right_shift_assignment", ">>>=")}}
+
부호 없는 우로 이동 할당.
+
{{JSxRef("Operators/Bitwise_AND_assignment", "&=")}}
+
비트 AND 할당.
+
{{JSxRef("Operators/Bitwise_XOR_assignment", "^=")}}
+
비트 XOR 할당.
+
{{JSxRef("Operators/Bitwise_OR_assignment", "|=")}}
+
비트 OR 할당.
+
+ +
+
{{JSxRef("Operators/Logical_AND_assignment", "&&=")}}
+
논리적 AND 할당.
+
{{JSxRef("Operators/Logical_OR_assignment", "||=")}}
+
논리적 OR 할당.
+
{{JSxRef("Operators/Logical_nullish_assignment", "??=")}}
+
논리적 nullish 할당.
+
+ +
+
{{JSxRef("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{JSxRef("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

구조 분해 할당은 배열 또는 객체의 속성을 배열 또는 객체 리터럴과 비슷해 보이는 구문을 사용하여 변수에 할당할 수 있게 합니다.

+
+
+ +

쉼표 연산자

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
쉼표 연산자는 여러 식을 단문으로 평가되게 하고 마지막 식의 결과를 반환합니다.
+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/instanceof/index.html b/files/ko/web/javascript/reference/operators/instanceof/index.html new file mode 100644 index 0000000000..0ac15b7ffe --- /dev/null +++ b/files/ko/web/javascript/reference/operators/instanceof/index.html @@ -0,0 +1,161 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operators/instanceof +tags: + - JavaScript + - Operator + - Reference + - Relational Operators +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +
{{jsSidebar("Operators")}}
+ +

instanceof 연산자는 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-instanceof.html")}}
+ + + +

구문

+ +
object instanceof constructor
+ +

매개변수

+ +
+
object
+
판별할 객체.
+
constructor
+
판별 목표 함수.
+
+ +

설명

+ +

instanceof 연산자는 object의 프로토타입 체인에 constructor.prototype이 존재하는지 판별합니다.

+ +
// 생성자 정의
+function C(){}
+function D(){}
+
+var o = new C();
+
+// true, 왜냐하면 Object.getPrototypeOf(o) === C.prototype
+o instanceof C;
+
+// false, 왜냐하면 D.prototype이 o 객체의 프로토타입 체인에 없음
+o instanceof D;
+
+o instanceof Object; // true, 왜냐하면
+C.prototype instanceof Object // true
+
+C.prototype = {};
+var o2 = new C();
+
+o2 instanceof C; // true
+
+// false, 왜냐하면 C.prototype이
+// 더 이상 o의 프로토타입 체인에 없음
+o instanceof C;
+
+D.prototype = new C(); // C를 D의 [[Prototype]] 링크로 추가
+var o3 = new D();
+o3 instanceof D; // true
+o3 instanceof C; // true, 왜냐하면 이제 C.prototype이 o3의 프로토타입 체인에 존재
+
+ +

instanceof 의 값은 생성자 prototype 프로퍼티의 변화에 따라 바뀔수 있으며, Object.setPrototypeOf의 사용함에 따라서도 바뀔 수 있음에 주의하세요. 또한 non-standard의 __proto__ 슈도-프로퍼티도 사용할 수 있도록 만들어 줍니다.

+ +

instanceof 와 multiple context (예. 프레임 또는 창)

+ +

다른 스코프는 다른 실행 환경을 가집니다. 이것은 다른 스코프는 다른 고정된 요소들(다른 전역 오브젝트, 다른 생성자들 등)을 가지고 있음을 의미합니다. 이 사실은 예상치 못한 결과를 가져올 수도 있습니다. 예를 들면, []  instanceof window.frames[0].Arrayfalse를 리턴할 것입니다. 왜냐하면, Array.prototype !== window.frames[0].Array 이며, arrays 는 상위로부터 상속받기 때문입니다. 이것은 처음에는 말이 되지 않을 수도 있습니다. 하지만, 스크립트에서 여러 프레임이나 창을 다루며, 객체를 함수를 통하여 하나의 컨텍스트에서 다른 컨텍스트로 오브젝트를 넘기게 된다면,  이건 충분히 일어날 수 있는 일이며, 아주 큰 이슈가 될 것입니다. 예를 들어, 주어진 오브젝트가 실제로 Array.isArray(myObj)를 사용한 Array인지 안전하게 확인 할 수 있습니다. 

+ +
Mozilla 개발자들을 위한 메모:
+XPCOM instanceof 을 사용하는 코드에서는 특별한 효과를 가집니다. :  obj instanceof xpcomInterface (예. Components.interfaces.nsIFile)가 obj.QueryInterface(xpcomInterface) 호출하고, 만약 QueryInterface 가 성공하면 true 를 리턴합니다. 이 호출의 부가 효과로는 obj 에서 성공적인 instanceof 테스트 후에 xpcomInterface's의 프로퍼티를 사용할 수 있습니다. 스탠다드 JavaScript 전역속성들과는 달리, 테스트 obj instanceof xpcomInterface는 obj가 다른 스코프에 있더라도 작동합니다.
+ +

예제

+ +

String과 Date는 타입 Object이며, 예외적인 경우임을 입증하기

+ +

아래의 코드는 instanceofStringDate 오브젝트도 타입 Object임을 확인하기 위해 사용합니다.(이 오브젝트들은 Object 로부터 파생되었습니다.)

+ +

그러나, 여기서 오브젝트 리터럴 노테이션으로 생성된 오브젝트는 예외적입니다. : 비록 프로토 타입이 정의되지 않았지만, instanceof Object true를 리턴합니다.

+ +
var simpleStr = "This is a simple string";
+var myString  = new String();
+var newStr    = new String("String created with constructor");
+var myDate    = new Date();
+var myObj     = {};
+
+simpleStr instanceof String; // returns false, prototype chain을 확인하고, undefined를 찾는다.
+myString  instanceof String; // returns true
+newStr    instanceof String; // returns true
+myString  instanceof Object; // returns true
+
+myObj instanceof Object;    // returns true, undefined prototype 임에도 불구하고 true.
+({})  instanceof Object;    // returns true, 위의 경우와 동일.
+
+myString instanceof Date;   // returns false
+
+myDate instanceof Date;     // returns true
+myDate instanceof Object;   // returns true
+myDate instanceof String;   // returns false
+
+ +

mycar는 타입 Car와 타입 Object임을 입증하기

+ +

다음의 코드는 Car 오브젝트 타입과 그 오브젝트 타입의 인스턴스 mycar를 생성합니다. instanceof 연산자는 mycar 오브젝트는 타입 Car 와 타입 Object 라는 것은 보여줍니다.

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+var mycar = new Car("Honda", "Accord", 1998);
+var a = mycar instanceof Car;    // returns true
+var b = mycar instanceof Object; // returns true
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}} +

초기 정의. JavaScript 1.4에서 구현됨.

+
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.instanceof")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/new.target/index.html b/files/ko/web/javascript/reference/operators/new.target/index.html new file mode 100644 index 0000000000..9c480c1513 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/new.target/index.html @@ -0,0 +1,93 @@ +--- +title: new.target +slug: Web/JavaScript/Reference/Operators/new.target +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Operators/new.target +--- +
{{JSSidebar("Operators")}}
+ +

new.target 속성(property)은 함수 또는 생성자가 new 연산자를 사용하여 호출됐는지를 감지할 수 있습니다. new 연산자로 인스턴스화된 생성자 및 함수에서, new.target은 생성자 또는 함수 참조를 반환합니다. 일반 함수 호출에서는, new.target은 {{jsxref("undefined")}}입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-newtarget.html")}}
+ + + +

구문

+ +
new.target
+ +

설명

+ +

new.target 구문은 키워드 "new", 점 및 속성명 "target"으로 구성됩니다. 보통 "new."은 속성 접근을 위한 문맥(context)으로 제공하지만 여기서 "new."은 정말 객체가 아닙니다. 그러나, 생성자 호출에서 new.targetnew에 의해 호출된 생성자를 가리키고 그래서 "new."은 가상 문맥이 됩니다.

+ +

new.target 속성은 모든 함수가 이용할 수 있는 메타 속성입니다. 화살표 함수에서, new.target은 둘러싸는 함수의 new.target을 말합니다.

+ +

+ +

함수 호출에서 new.target

+ +

일반 함수 호출(생성자 함수 호출과는 반대로)에서, new.target은 {{jsxref("undefined")}}입니다. 이는 함수가 생성자로서 new로 호출된 경우를 감지할 수 있습니다.

+ +
function Foo() {
+  if (!new.target) throw "Foo() must be called with new";
+  console.log("Foo instantiated with new");
+}
+
+Foo(); // throws "Foo() must be called with new"
+new Foo(); // logs "Foo instantiated with new"
+
+ +

생성자에서 new.target

+ +

클래스 생성자에서, new.targetnew에 의해 직접 호출된 생성자를 가리킵니다. 이는 그 생성자가 부모 클래스에 있고 자식 생성자로부터 위임받은 경우도 그 경우입니다.

+ +
class A {
+  constructor() {
+    console.log(new.target.name);
+  }
+}
+
+class B extends A { constructor() { super(); } }
+
+var a = new A(); // logs "A"
+var b = new B(); // logs "B"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-built-in-function-objects', 'Built-in Function Objects')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-built-in-function-objects', 'Built-in Function Objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.new_target")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/new/index.html b/files/ko/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..a28d21de18 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/new/index.html @@ -0,0 +1,187 @@ +--- +title: new operator +slug: Web/JavaScript/Reference/Operators/new +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/new +--- +
{{jsSidebar("Operators")}}
+ +

new 연산자는 사용자 정의 객체 타입 또는 내장 객체 타입의 인스턴스를 생성한다.

+ +

{{EmbedInteractiveExample("pages/js/expressions-newoperator.html")}}

+ + + +

구문

+ +
new constructor[([arguments])]
+ +

매개변수

+ +
+
constructor
+
객체 인스턴스의 타입을 기술(명세)하는 함수
+
+ +
+
arguments
+
constructor와 함께 호출될 값 목록
+
+ +

설명

+ +

사용자 정의 객체를 생성에는 두 단계가 필요하다:

+ +
    +
  1. 함수를 작성하여 객체 타입을 정의한다.
  2. +
  3. new 연산자로 객체의 인스턴스를 생성한다.
  4. +
+ +

객체의 타입을 정의하기 위해, 객체의 이름과 속성을 명세하는 함수를 만든다. 객체는 그 자체가 또 다른 객체인 속성을 가질 수 있다. 아래의 예를 본다.

+ +

코드 new Foo(...)가 실행될 때 다음과 같은 일이 발생한다:

+ +
    +
  1. Foo.prototype을 상속하는 새로운 객체가 하나 생성된다.
  2. +
  3. 명시된 인자 그리고 새롭게 생성된 객체에 바인드된 this와 함께 생성자 함수 Foo가 호출된다.new Foonew Foo()와 동일하다. 즉 인자가 명시되지 않은 경우, 인자 없이 Foo가 호출된다.
  4. +
  5. 생성자 함수에 의해 리턴된 객체는 전체 new 호출 결과가 된다. 만약 생성자 함수가 명시적으로 객체를 리턴하지 않는 경우, 첫 번째 단계에서 생성된 객체가 대신 사용된다.(일반적으로 생성자는 값을 리턴하지 않는다. 그러나 일반적인 객체 생성을 재정의(override)하기 원한다면 그렇게 하도록 선택할 수 있다.)
  6. +
+ +

언제든 이전에 정의된 객체에 속성을 추가할 수 있다. 예를 들면, car1.color = "black" 구문은 color 속성을 car1에 추가하고 해당 속성에 "black"이란 값을 할당한다. 그러나, 이것이 다른 객체들에게는 영향을 주지 않는다. 동일한 타입의 모든 객체들에게 새로운 속성을 추가하려면, Car 객체 타입의 정의에 이 속성을 추가해야한다.

+ +

Function.prototype 속성을 사용하여 이전에 정의된 객체 타입에 공유 속성을 추가할 수 있다. 이것은 객체 타입의 인스턴스 하나에만 적용되는 것이 아니라 이 함수로 생성하는 모든 객체와 공유하는 속성을 정의한다.

+ +

다음의 코드는 car 타입의 모든 객체에 "original color" 값을 갖는 color 속성을 추가한다. 그리고 car1 객체 인스턴스에서만 이 값을 문자열 "black"으로 덮어쓴다. 더 많은 정보는 prototype을 참조한다.

+ +
function Car() {}
+car1 = new Car();
+car2 = new Car();
+
+console.log(car1.color);    // undefined
+
+Car.prototype.color = "original color";
+console.log(car1.color);    // original color
+
+car1.color = 'black';
+console.log(car1.color);   // black
+
+console.log(car1.__proto__.color) //original color
+console.log(car2.__proto__.color) //original color
+console.log(car1.color)  // black
+console.log(car2.color) // original color
+
+ +

예제

+ +

객체 타입과 객체 인스턴스

+ +

cars를 위한 객체 타입을 생성하기 원한다고 가정해 보자. 이 객체 타입이 car로 불리기 원하고, make, model, 그리고 year 속성을 갖게 하고 싶다. 이렇게 하기 위해서 다음과 같은 함수를 작성할 것이다:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

이제 다음과 같이, mycar로 불리는 객체를 생성할 수 있다:

+ +
var mycar = new Car("Eagle", "Talon TSi", 1993);
+
+ +

이 구문은 mycar 를 생성하고 명시한 값을 속성값으로 설정한다. 그래서 mycar.make의 값은 문자열 "Eagle"이고, mycar.year는 정수 1993이며 나머지도 마찬가지이다.

+ +

new를 호출해서 얼마든지 car 객체를 생성할 수 있다. 예를 들면:

+ +
var kenscar = new Car("Nissan", "300ZX", 1992);
+
+ +

속성 그 자신이 다른 객체인 객체의 속성

+ +

person이라고 불리는 객체를 다음과 같이 정의한다고 가정해보자:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

그리고 다음과 같이 두 개의 person 객체 인스턴스를 새롭게 생성한다:

+ +
var rand = new Person("Rand McNally", 33, "M");
+var ken = new Person("Ken Jones", 39, "M");
+
+ +

그런 다음 owner 속성을 포함하는 car의 정의를 다시 쓸 수 있다. 이 owner 속성은 다음과 같은 person 객체를 취한다:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

새로운 객체의 인스턴스를 생성하기 위해 다음과 같이 사용한다:

+ +
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
+var car2 = new Car("Nissan", "300ZX", 1992, ken);
+
+ +

새로운 객체를 생성할 때 문자열이나 숫자 값을 넘겨주는 대신에, 위의 구문은 owner를 위한 매개변수로 randken 객체를 넘겨준다. car2의 owner name을 확인해보기 위해서, 다음의 속성에 접근할 수 있다:

+ +
car2.owner.name
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.new")}}

+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html b/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html new file mode 100644 index 0000000000..cae74ea29d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html @@ -0,0 +1,161 @@ +--- +title: Nullish coalescing operator +slug: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +--- +

{{JSSidebar("Operators")}}

+ +

널 병합 연산자 (??) 는 왼쪽 피연산자가 {{jsxref("null")}} 또는 {{jsxref("undefined")}}일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자이다.

+ +

논리 연산자 OR (||)와 달리, 왼쪽 피연산자가 null 또는 undefined가 아닌 falsy 값이면 반환된다. 즉, 만약 다른 변수 foo에게 기본 값을 제공하기 위해 ||을 사용 경우, falsy 값( '' 또는 0)을 사용하는 것을 고려했다면 예기치 않는 동작이 발생할 수 있다. 더 많은 예제는 아래를 보자.

+ +
{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}}
+ + + +

문법

+ +
leftExpr ?? rightExpr
+
+ +

설명

+ +

널 병합 연산자는 만약 왼쪽 표현식이 {{jsxref("null")}} 또는 {{jsxref("undefined")}}인 경우, 오른쪽 표현식의 결과를 반환한다.

+ +

변수에 기본값 할당

+ +

이전에는 변수에 기본값을 할당하고 싶을 때, 논리 연산자 OR (||)을 사용하는 것이 일반적인 패턴이다:

+ +
let foo;
+...
+//  foo is never assigned any value so it is still undefined
+let someDummyText = foo || 'Hello!';
+ +

그러나 || boolean 논리 연산자 때문에, 왼쪽 피연산자는 boolean으로 강제로 변환되었고 falsy 한 값(0, '', NaN, null, undefined)은 반환되지 않았다. 이 동작은 만약 0, '' or NaN을 유효한 값으로 생각한 경우 예기치 않는 결과를 초래할 수 있다.

+ +
let count;
+let text;
+...
+count = 0;
+text = "";
+...
+let qty = count || 42;
+let message = text || "hi!";
+console.log(qty);     // 42 and not 0
+console.log(message); // "hi!" and not ""
+
+ +

널 병합 연산자는 첫 번째 연산자가 null 또는 undefined로 평가될 때만, 두 번째 피연산자를 반환함으로써 이러한 위험을 피한다:

+ +
let myText = ''; // An empty string (which is also a falsy value)
+
+let notFalsyText = myText || 'Hello world';
+console.log(notFalsyText); // Hello world
+
+let preservingFalsy = myText ?? 'Hi neighborhood';
+console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
+
+ +

단락

+ +

OR과 AND 같은 논리 연산자들과 마찬가지로, 만약 왼쪽이 null 또는 undefined가 아님이 판명되면 오른쪽 표현식은 평가되지 않는다.

+ +
function A() { console.log('A was called'); return undefined;}
+function B() { console.log('B was called'); return false;}
+function C() { console.log('C was called'); return "foo";}
+
+console.log( A() ?? C() );
+// logs "A was called" then "C was called" and then "foo"
+// as A() returned undefined so both expressions are evaluated
+
+console.log( B() ?? C() );
+// logs "B was called" then "false"
+// as B() returned false (and not null or undefined), the right
+// hand side expression was not evaluated
+
+ +

No chaining with AND or OR operators

+ +

AND (&&) 와 OR 연산자 (||)를 ??와 직접적으로 결합하여 사용하는 것은 불가능하다. 이 경우 SyntaxError가 발생된다.

+ +
null || undefined ?? "foo"; // raises a SyntaxError
+true || undefined ?? "foo"; // raises a SyntaxError
+ +

그러나 우선 순위를 명시적으로 나타내기 위해 괄호를 사용하면 가능하다:

+ +
(null || undefined ) ?? "foo"; // returns "foo"
+
+ +

Optional chaining 연산자(?.)와의 관계

+ +

널 병합 연산자는 명확한 값으로 undefined과 null을 처리하고, optional chaining 연산자 (?.)null or undefined일 수 있는 객체의 속성에 접근할 때 유용하다.

+ +
let foo = { someFooProp: "hi" };
+
+console.log(foo.someFooProp?.toUpperCase());  // "HI"
+console.log(foo.someBarProp?.toUpperCase()); // undefined
+
+ +

예제

+ +

이 예제는 기본 값을 제공하지만 null or undefined 이외의 값을 를 유지한다. 

+ +
function getMiscObj(){
+  return {
+    aNullProperty: null,
+    emptyText: "", // this is not falsy
+    someNumber: 42
+  };
+};
+
+const miscObj = getMiscObj();
+
+const newObj = {};
+newObj.propA = miscObj.aNullProperty ?? "default for A";
+newObj.propB = miscObj.emptyText ?? "default for B";
+newObj.propC = miscObj.someNumber ?? 0;
+
+console.log(newObj.propA); // "default for A"
+console.log(newObj.propB); // "" (as the empty string is not null or undefined)
+console.log(newObj.propC); // 42
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
Proposal for the "nullish coalescing" operatorStage 3
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.nullish_coalescing")}}

+ +

구현 진행

+ +

The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.

+ +
{{EmbedTest262ReportResultsTable("coalesce-expression")}}
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/operators/object_initializer/index.html b/files/ko/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..825c854848 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,302 @@ +--- +title: 객체 초기자 +slug: Web/JavaScript/Reference/Operators/Object_initializer +tags: + - ECMAScript 2015 + - ECMAScript6 + - JSON + - JavaScript + - Literal + - Methods + - Object + - Primary Expression + - computed + - mutation + - properties +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +
{{JsSidebar("Operators")}}
+ +

객체는 new Object(), Object.create() 또는 리터럴 표기법 (initializer 표기법)을 사용하여 초기화될 수 있습니다. 객체 초기자(object initializer)는 0개 이상인 객체 속성명 및 관련값 쌍 목록이 콤마로 분리되어 중괄호({})로 묶인 형태입니다.

+ +

{{EmbedInteractiveExample("pages/js/expressions-objectinitializer.html", "taller")}}

+ + + +

구문

+ +
var o = {};
+var o = { a: "foo", b: 42, c: {} };
+
+var a = "foo", b = 42, c = {};
+var o = { a: a, b: b, c: c };
+
+var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {},
+};
+
+ +

ECMAScript 2015의 새로운 표기법

+ +

이 표기법에 대한 지원은 호환성 표를 참조해 주세요. 비지원 환경에서, 이 표기법은 구문 오류로 이어집니다.

+ +
// 단축 속성명 (ES2015)
+let a = "foo", b = 42, c = {}
+let o = { a, b, c }
+
+// 단축 메서드명 (ES2015)
+var o = {
+  property([parameters]) {}
+}
+
+// 계산된 속성명 (ES2015)
+var prop = 'foo'
+var o = {
+  [prop]: 'hey',
+  ['b' + 'ar']: 'there'
+}
+ +

설명

+ +

객체 초기자는 {{jsxref("Object")}}의 초기화를 기술하는 표현식(expression)입니다. 객체는 객체를 설명하는 데 사용되는속성으로 구성됩니다. 객체의 속성값은 {{Glossary("primitive")}} 데이터 형 또는 다른 객체를 포함할 수 있습니다.

+ +

객체 리터럴 표기법 vs JSON

+ +

객체 리터럴 표기법은 JavaScript Object Notation (JSON)과 같지 않습니다. 비슷해 보이지만, 차이가 있습니다:

+ + + +

예제

+ +

객체 생성

+ +

속성이 없는 빈 객체는 다음과 같이 만들 수 있습니다:

+ +
var object = {};
+ +

그러나, 리터럴(literal) 또는 초기자(initializer) 표기법의 이점은, 빠르게 중괄호 내 속성이 있는 객체를 만들 수 있다는 것입니다. 당신은 그저 쉼표로 구분된 키: 값 쌍 목록을 표기합니다.

+ +

다음 코드는 키가 "foo", "age""baz"인 세 속성이 있는 객체를 만듭니다. 이들 키값은 문자열 "bar", 숫자 42 그리고 세 번째 속성은 그 값으로 다른 객체를 갖습니다.

+ +
var object = {
+  foo: "bar",
+  age: 42,
+  baz: { myProp: 12 },
+}
+ +

속성 접근

+ +

일단 객체를 생성하면, 읽거나 바꿀 수 있습니다. 객체 속성은 점 표기법 또는 각괄호 표기법을 사용하여 액세스될 수 있습니다. (자세한 사항은 속성 접근자 참조.)

+ +
object.foo; // "bar"
+object["age"]; // 42
+
+object.foo = "baz";
+
+ +

속성 정의

+ +

우리는 이미 초기자 구문을 사용한 속성 표기법을 배웠습니다. 가끔, 객체 안에 두고 싶은 코드 속 변수가 있습니다. 다음과 같은 코드가 보입니다:

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

ECMAScript 2015의 경우, 똑같은 일을 할 수 있는 더 짧은 표기법이 있습니다:

+ +
var a = "foo",
+    b = 42,
+    c = {};
+
+// 단축 속성명 (ES6)
+var o = { a, b, c }
+
+// 다시 말해서,
+console.log((o.a === {a}.a)) // true
+
+ +

중복된 속성명

+ +

속성이 같은 이름을 쓰는 경우, 두 번째 속성은 첫 번째를 겹쳐씁니다.

+ +
var a = {x: 1, x: 2};
+console.log(a); // {x: 2}
+
+ +

ECMAScript 5 엄격 모드 코드에서, 중복된 속성명은 {{jsxref("SyntaxError")}}로 간주됐습니다. 런타임에 중복을 가능케 하는 속성 계산명 도입으로, ECMAScript 2015는 이 제한을 제거했습니다.

+ +
function haveES6DuplicatePropertySemantics(){
+  "use strict";
+  try {
+    ({ prop: 1, prop: 2 });
+
+    // 오류 미 발생, 중복 속성명은 엄격 모드에서 허용됨
+    return true;
+  } catch (e) {
+    // 오류 발생, 중복은 엄격 모드에서 금지됨
+    return false;
+  }
+}
+ +

메서드 정의

+ +

객체의 속성은 함수getter 또는 setter 메서드를 참조할 수도 있습니다.

+ +
var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {},
+};
+ +

ECMAScript 2015에서는, 단축 표기법을 이용할 수 있습니다, 그래서 키워드 "function"은 더 이상 필요치 않습니다.

+ +
// 단축 메서드 명 (ES6)
+var o = {
+  property([parameters]) {},
+}
+ +

ECMAScript 2015에는 값이 생성기 함수인 속성을 간결하게 정의하는 법도 있습니다:

+ +
var o = {
+  *generator() {
+    ...........
+  }
+};
+ +

ECMAScript 5에서는 다음과 같이 작성할 수 있습니다 (하지만 ES5는 생성기가 없음을 주의하세요):

+ +
var o = {
+  generatorMethod: function* () {
+    ...........
+  }
+};
+ +

메서드에 관한 자세한 사항 및 예는, 메서드 정의 참조.

+ +

계산된 속성명

+ +

ECMAScript 2015를 시작으로, 객체 초기화 구문은 계산된 속성명(computed property name)도 지원합니다. 각괄호 [] 안에 식을 넣을 수 있고, 식이 계산되고 그 결과가 속성명으로 사용됩니다. 이는 이미 속성을 읽고 설정하는 데 사용했을 수 있는 속성 접근자 구문의 각괄호 표기법을 연상시킵니다.  

+ +

이제 당신은 객체 리터럴에서도 같은 구문을 쓸 수 있습니다:

+ +
// 계산된 속성명 (ES6)
+var i = 0;
+var a = {
+  ["foo" + ++i]: i,
+  ["foo" + ++i]: i,
+  ["foo" + ++i]: i
+};
+
+console.log(a.foo1); // 1
+console.log(a.foo2); // 2
+console.log(a.foo3); // 3
+
+var param = 'size';
+var config = {
+  [param]: 12,
+  ["mobile" + param.charAt(0).toUpperCase() + param.slice(1)]: 4
+};
+
+console.log(config); // { size: 12, mobileSize: 4 }
+ +

전개 속성

+ +

ECMASCript의 나머지/전개 속성 제안 (stage 4) 으로 전개(spread) 속성이 객체 리터럴에 추가됩니다. 이 속성은 제공된 객체의 열거 가능한(enumerable) 속성을 새 객체로 복사합니다.

+ +

(prototype을 제외하는) 얕은 복제(Shallow-cloning) 나 객체 합침(merging objects)이 이제{{jsxref("Object.assign()")}} 보다 짧은 문법으로 가능해집니다.

+ +
let obj1 = { foo: 'bar', x: 42 }
+let obj2 = { foo: 'baz', y: 13 }
+
+let clonedObj = { ...obj1 }
+// Object { foo: "bar", x: 42 }
+
+let mergedObj = { ...obj1, ...obj2 }
+// Object { foo: "baz", x: 42, y: 13 }
+ +
+

{{jsxref("Object.assign()")}}는 setters를 작동시키지만, 전개 연산자(spread operator)는 아니라는 걸 주목하세요!

+
+ +

프로토타입 변이

+ +

__proto__: value 또는 "__proto__": value 형태의 속성 정의는 이름이 __proto__인 속성을 만들지 않습니다. 대신, 제공된 값이 객체 또는 null이면, 생성된 객체의 [[Prototype]]을 그 값으로 바꿉니다. (값이 객체나 null이 아니면, 객체는 바뀌지 않습니다.)

+ +
var obj1 = {};
+assert(Object.getPrototypeOf(obj1) === Object.prototype);
+
+var obj2 = { __proto__: null };
+assert(Object.getPrototypeOf(obj2) === null);
+
+var protoObj = {};
+var obj3 = { "__proto__": protoObj };
+assert(Object.getPrototypeOf(obj3) === protoObj);
+
+var obj4 = { __proto__: "not an object or null" };
+assert(Object.getPrototypeOf(obj4) === Object.prototype);
+assert(!obj4.hasOwnProperty("__proto__"));
+
+ +

단일 프로토타입 변이(mutation)만 객체 리터럴에 허용됩니다: 다중 프로토타입 변이는 구문 오류입니다.

+ +

"colon" 표기법을 쓰지 않는 속성 정의는 프로토타입 변이가 아닙니다: 그들은 다른 이름을 사용하는 비슷한 정의와 동일하게 동작하는 속성 정의입니다.

+ +
var __proto__ = "variable";
+
+var obj1 = { __proto__ };
+assert(Object.getPrototypeOf(obj1) === Object.prototype);
+assert(obj1.hasOwnProperty("__proto__"));
+assert(obj1.__proto__ === "variable");
+
+var obj2 = { __proto__() { return "hello"; } };
+assert(obj2.__proto__() === "hello");
+
+var obj3 = { ["__prot" + "o__"]: 17 };
+assert(obj3.__proto__ === 17);
+
+ +

스펙

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.object_initializer")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/operators/optional_chaining/index.html b/files/ko/web/javascript/reference/operators/optional_chaining/index.html new file mode 100644 index 0000000000..cdf88c138b --- /dev/null +++ b/files/ko/web/javascript/reference/operators/optional_chaining/index.html @@ -0,0 +1,187 @@ +--- +title: Optional chaining +slug: Web/JavaScript/Reference/Operators/Optional_chaining +translation_of: Web/JavaScript/Reference/Operators/Optional_chaining +--- +
{{JSSidebar("Operators")}}
+ +

{{SeeCompatTable}}

+ +

optional chaining 연산자 ?. 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다. ?. 연산자는 . 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 {{glossary("nullish")}} ({{JSxRef("null")}} 또는 {{JSxRef("undefined")}})이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 undefined로 단락된다. 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.

+ +

이것은 참조가 누락될 가능성이 있는 경우 연결된 속성으로 접근할 때 더 짧고 간단한 표현식이 생성된다. 어떤 속성이 필요한지에 대한 보증이 확실하지 않는 경우 객체의 내용을 탐색하는 동안 도움이 될 수 있다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html")}}
+ +
+ + + +

문법

+ +
obj?.prop
+obj?.[expr]
+arr?.[index]
+func?.(args)
+
+ +

설명

+ +

optional chaining 연산자는 참조나 기능이 undefined 또는 null일 수 있을 때 연결된 객체의 값에 접근하는 단순화할 수 있는 방법을 제공한다.

+ +

예를 들어, 중첩된 구조를 가진 객체에서 obj가 있다. optional chaining이 없이 깊이 중첩된 하위 속성을 찾으려면, 다음과 같이 참조를 확인해야 한다:

+ +
let nestedProp = obj.first && obj.first.second;
+ +

obj.first의 값은 obj.first.second의 값에 접근하기 전에 null (그리고 undefined)가 아니라는 점을 검증한다. 이는 만약에 obj.first를 테스트 없이 obj.first.second 에 직접 접근할 때 일어날 수 있는 에러를 방지한다. 

+ +

그러나 optional chaining 연산자(?.)를 사용하여, obj.first.second 에 접근하기 전에 obj.first의 상태에 따라 명시적으로 테스트하거나 단락시키지 않아도 된다:

+ +
let nestedProp = obj.first?.second;
+ +

. 대신에 ?. 연산자를 사용함으로써, 자바스크립트는 obj.first.second에 접근하기 전에 obj.first가 null 또는 undefined가 아니라는 것을 암묵적으로 확인하는 것을 알고 있다. 만약 obj.firstnull 또는 undefined이라면, 그 표현식은 자동으로 단락되어 undefined가 반환된다.

+ +

이는 다음과 같다:

+ +
let nestedProp = ((obj.first === null || obj.first === undefined) ? undefined : obj.first.second);
+ +

함수의 호출과 Optional chaining

+ +

존재하지 않을 수 있는 매서드를 호출할 때, optional chaining을 사용할 수 있다. 예를 들어, 구현 기간이나 사용자 장치에서 사용할 수 없는 기능 때문에 메서드를 사용할 수 없는 API를 사용할 경우,  유용할 수 있다.

+ +

함수 호출과 optional chaining을 사용함으로써 메서드를 찾을 수 없는 경우에 예외를 발생시키는 것 대신에 그 표현식은 자동으로 undefined를 반환한다:

+ +
let result = someInterface.customMethod?.();
+ +
+

메모: 만약 속성에 해당 이름이 있지만 함수가 아니라면, ?.의 사용은 여전히 예외를 발생시킨다. {{JSxRef("TypeError")}} exception (x.y is not a function).

+
+ +

optional callbacks과 event handlers 다루기

+ +

만약 객체에서 destructuring assignment로 callbacks 또는 fetch 메서드를 사용한다면, 그 존재 여부를 테스트하지 않으면 함수로 호출할 수 없는 존재 하지 않는 값을 가질 수 있다. ?.을 사용하면, 다음 추가 테스트를 피할 수 있다:

+ +
// Written as of ES2019
+function doSomething(onContent, onError) {
+  try {
+    // ... do something with the data
+  }
+  catch (err) {
+    if (onError) { // Testing if onError really exists
+      onError(err.message);
+    }
+  }
+}
+
+ +
// Using optional chaining with function calls
+function doSomething(onContent, onError) {
+  try {
+   // ... do something with the data
+  }
+  catch (err) {
+    onError?.(err.message); // no exception if onError is undefined
+  }
+}
+
+ +

표현식에서 Optional chaining

+ +

optional chaining 연산자를 속성에 표현식으로 접근할 때 대괄호 표기법(the bracket notation of the property accessor)을 사용할 수 있다:

+ +
let nestedProp = obj?.['prop' + 'Name'];
+
+ +

Optional chaining으로 배열 항목에 접근하기

+ +
let arrayItem = arr?.[42];
+ +

예제

+ +

기본 예제

+ +

이 예제는 해당 멤버가 없을 때, map에서 멤버 bar의 name의 속성 값을 찾는다. 그러므로 결과는 undefined이다.

+ +
let myMap = new Map();
+myMap.set("foo", {name: "baz", desc: "inga"});
+
+let nameBar = myMap.get("bar")?.name;
+ +

단락 평가

+ +

표현식에서 optional chaining을 사용할 때, 만약 왼쪽에 있는 피연산자가 null or undefined인  경우, 그 표현식은 평가되지 않는다. 예들 들어:

+ +
let potentiallyNullObj = null;
+let x = 0;
+let prop = potentiallyNullObj?.[x++];
+
+console.log(x); // 0  x는 증가하지 않음
+
+ +

optional chaining 연산자 쌓기

+ +

중첩된 구조에서는 optional chaining을 여러 번 사용할 수 있다:

+ +
let customer = {
+  name: "Carl",
+  details: {
+    age: 82,
+    location: "Paradise Falls" // detailed address is unknown
+  }
+};
+let customerCity = customer.details?.address?.city;
+
+// … this also works with optional chaining function call
+let duration = vacations.trip?.getTime?.();
+
+ +

널 병합 연산자와 같이 사용하기

+ +

널 병합 연산자는 optional chaining를 사용한 후에 아무 값도 찾을 수 없을 때 기본 값을 주기 위해 사용될 수 있다:

+ +
let customer = {
+  name: "Carl",
+  details: { age: 82 }
+};
+const customerCity = customer?.city ?? "Unknown city";
+console.log(customerCity); // Unknown city
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
Proposal for the "optional chaining" operatorStage 4
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.operators.optional_chaining")}}

+
+ +

구현 진행

+ +

The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.

+ +
{{EmbedTest262ReportResultsTable("optional-chaining")}}
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/operators/pipeline_operator/index.html b/files/ko/web/javascript/reference/operators/pipeline_operator/index.html new file mode 100644 index 0000000000..42eb62e545 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/pipeline_operator/index.html @@ -0,0 +1,76 @@ +--- +title: 파이프 연산자 +slug: Web/JavaScript/Reference/Operators/Pipeline_operator +tags: + - Experimental + - JavaScript + - Operator +translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator +--- +
{{jsSidebar("Operators")}} {{SeeCompatTable}}
+ +

파이프 연산자(|>)는 실험적 기능(stage 1)으로, 표현식의 값을 함수에 전달합니다. 파이프 연산자를 활용하면 중첩 함수 호출을 좀 더 읽기 좋은 형식으로 작성할 수 있습니다. 결과물은 문법적 설탕syntactic sugar으로, 하나의 인수를 제공하는 함수 호출은 다음 코드처럼 쓸 수 있습니다.

+ +
let url = "%21" |> decodeURI;
+ +

전통적인 구문에서는 아래처럼 호출합니다.

+ +
let url = decodeURI("%21");
+
+ +

구문

+ +
expression |> function
+
+ +

지정한 expression의 값이 function의 유일한 매개변수로 전달됩니다.

+ +

예제

+ +

함수 체이닝

+ +

파이프 연산자를 사용해, 여러 번 중첩된 함수 호출을 읽기 편한 형태로 바꿀 수 있습니다.

+ +
const double = (n) => n * 2;
+const increment = (n) => n + 1;
+
+// 파이프 연산자 없이
+double(increment(double(double(5)))); // 42
+
+// 파이프 연산자 사용
+5 |> double |> double |> increment |> double; // 42
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
Pipeline operator draftStage 1Not part of the ECMAScript specification yet.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.operators.pipeline")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/property_accessors/index.html b/files/ko/web/javascript/reference/operators/property_accessors/index.html new file mode 100644 index 0000000000..83ae2e0b80 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/property_accessors/index.html @@ -0,0 +1,153 @@ +--- +title: 속성 접근자 +slug: Web/JavaScript/Reference/Operators/Property_Accessors +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Property_Accessors +--- +
{{jsSidebar("Operators")}}
+ +

속성 접근자는 점 또는 괄호 표기법으로 객체의 속성에 접근할 수 있도록 해줍니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-propertyaccessors.html")}}
+ + + +

구문

+ +
object.property
+object['property']
+
+ +

설명

+ +

객체는 속성의 이름을 키로 사용하는 연관 배열(다른 이름으로는 맵, 딕셔너리, 해시, 룩업 테이블)로 생각할 수 있습니다. 보통 객체의 속성을 메서드와 구별해서 말하곤 하지만, 서로의 차이는 관례에 불과합니다. 메서드는 호출할 수 있는 속성일 뿐으로, 속성의 값이 {{jsxref("Function")}}을 가리키는 참조라면 그 속성을 메서드라고 합니다.

+ +

속성에 접근하는 법은 점 표기법과 괄호 표기법 두 가지가 있습니다.

+ +

점 표기법

+ +
get = object.property;
+object.property = set;
+
+ +

이 코드에서, property는 유효한 JavaScript {{glossary("identifier", "식별자")}}여야합니다. 따라서 object.$1은 유효하지만 object.1은 아닙니다.

+ +
document.createElement('pre');
+
+ +

여기서는 "createElement"라는 이름을 가진 메서드를 document에서 찾아 호출하고 있습니다.

+ +

소숫점 없는 숫자 리터럴의 메서드를 호출하고 싶으면, 메서드의 접근자 앞에 공백을 한 칸 추가해 점이 소숫점으로 인식되지 않도록 해야 합니다.

+ +
77 .toExponential();
+// or
+77
+.toExponential();
+// or
+(77).toExponential();
+// or
+77..toExponential();
+// or
+77.0.toExponential();
+// because 77. === 77.0, no ambiguity
+
+ +

괄호 표기법

+ +
get = object[property_name];
+object[property_name] = set;
+
+ +

괄호 표기법에서는 property_name으로 문자열이나 {{jsxref("Symbol")}}을 사용할 수 있습니다. 문자열은 유효한 식별자가 아니어도 괜찮습니다. "1foo", "!bar!", 심지어 " "(공백)도 가능합니다.

+ +
document['createElement']('pre');
+
+ +

이 코드는 점 표기법의 예시와 동일합니다.

+ +

괄호 앞에 공백이 올 수도 있습니다.

+ +
document ['createElement']('pre');
+
+ +

속성 이름

+ +

속성의 이름은 문자열이나 {{jsxref("Symbol")}}입니다. 숫자 등의 다른 자료형은 문자열로 변환됩니다.

+ +
var object = {};
+object['1'] = 'value';
+console.log(object[1]);
+
+ +

위 코드의 1'1'로 변환되므로, 출력 결과는 "value"입니다.

+ +
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
+object[foo] = 'value';
+console.log(object[bar]);
+
+ +

위의 코드 역시 foobar가 같은 문자열(SpiderMonkey JavaScript 엔진에서는 문자열 "['object Object']")로 변환되므로, 출력 결과는 동일하게 "value"입니다.

+ +

메서드 바인딩

+ +

메서드는 해당 메서드의 객체에 바인딩되지 않습니다. 특히 this는 메서드 내에 고정되지 않으므로 this가 항상 현재 메서드를 포함하는 객체를 참조하는건 아닙니다. 대신, this는 함수 호출 방식에 따라 "전달"됩니다. 메서드 바인딩을 참고하세요.

+ +

eval() 주의사항

+ +

JavaScript 초심자로써는 괄호 표기법을 사용할 수 있는 장소에 {{jsxref("eval", "eval()")}}을 남용하기 쉽습니다. 간혹 스크립트에서 다음과 같은 구문을 찾아볼 수 있습니다.

+ +
x = eval('document.forms.form_name.elements.' + strFormControl + '.value');
+
+ +

eval()은 느리고, 가능하다면 최대한 피해야 합니다. 또한, strFormControl은 유효한 식별자여야 하지만, 폼 컨트롤의 ID나 이름은 식별자가 아닐 수도 있습니다. 따라서 괄호 표기법을 대신 사용하는 것이 좋습니다.

+ +
x = document.forms["form_name"].elements[strFormControl].value;
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ESDraft', '#sec-property-accessors', 'Property Accessors')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-property-accessors', 'Property Accessors')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.1', 'Property Accessors')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.2.1', 'Property Accessors')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.property_accessors")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/remainder/index.html b/files/ko/web/javascript/reference/operators/remainder/index.html new file mode 100644 index 0000000000..beeb0033a3 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/remainder/index.html @@ -0,0 +1,73 @@ +--- +title: 나머지 연산자 (%) +slug: Web/JavaScript/Reference/Operators/Remainder +translation_of: Web/JavaScript/Reference/Operators/Remainder +--- +
{{jsSidebar("Operators")}}
+ +

나머지 연산자(%)는 피제수가 제수에 의해 나누어진 후, 그 나머지를 반환합니다. 항상 피제수의 부호를 따릅니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-remainder.html")}}
+ +
+ + + +

문법

+ +
Operator: var1 % var2
+
+ +

예시

+ +

(+)피제수의 나머지

+ +
 12 % 5  //  2
+ 1 % -2 //  1
+ 1 % 2  //  1
+ 2 % 3  //  2
+5.5 % 2 // 1.5
+
+ +

(-)피제수의 나머지

+ +
-12 % 5 // -2
+-1 % 2  // -1
+-4 % 2  // -0
+ +

NaN의 나머지

+ +
NaN % 2 // NaN
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Remainder operator')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.remainder")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/spread_syntax/index.html b/files/ko/web/javascript/reference/operators/spread_syntax/index.html new file mode 100644 index 0000000000..d2174a53bb --- /dev/null +++ b/files/ko/web/javascript/reference/operators/spread_syntax/index.html @@ -0,0 +1,255 @@ +--- +title: 전개 구문 +slug: Web/JavaScript/Reference/Operators/Spread_syntax +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Reference + - Spread + - 전개 연산자 +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +
{{jsSidebar("Operators")}}
+ +

전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
+ + + +

구문

+ +

함수 호출:

+ +
myFunction(...iterableObj);
+
+ +

배열 리터럴과 문자열:

+ +
[...iterableObj, '4', 'five', 6];
+ +

객체 리터럴(ECMAScript 2018에서 추가):

+ +
let objClone = { ...obj };
+ +

예제

+ +

함수 호출에서의 전개

+ +

apply() 대체

+ +

일반적으로 배열의 엘리먼트를 함수의 인수로 사용하고자 할 때 {{jsxref( "Function.prototype.apply()")}} 를 사용하였습니다.

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction.apply(null, args);
+ +

전개 구문을 사용해 위 코드는 다음과 같이 작성될 수 있습니다.

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction(...args);
+ +

인수 목록의 모든 인수는 전개 구문을 사용할 수 있으며, 여러번 사용될 수도 있습니다.

+ +
function myFunction(v, w, x, y, z) { }
+var args = [0, 1];
+myFunction(-1, ...args, 2, ...[3]);
+ +

new에 적용

+ +

{{jsxref("Operators/new", "new")}}를 사용해 생성자를 호출 할 때, 배열과 apply (apply[[Call]] 을 하지만 [[Construct]] 는 그렇지 않음) 를 직접 사용하는 것은 불가했습니다. 하지만, 전개 구문 덕분에 배열을 new 와 함께 쉽게 사용될 수 있습니다.

+ +
var dateFields = [1970, 0, 1];  // 1 Jan 1970
+var d = new Date(...dateFields);
+
+ +

전개 구문 없이 파라미터의 배열과 함께 new를 사용하려면, 부분적인 어플리케이션을 통해 간접적으로 해야 합니다.

+ +
function applyAndNew(constructor, args) {
+   function partial () {
+      return constructor.apply(this, args);
+   };
+   if (typeof constructor.prototype === "object") {
+      partial.prototype = Object.create(constructor.prototype);
+   }
+   return partial;
+}
+
+
+function myConstructor () {
+   console.log("arguments.length: " + arguments.length);
+   console.log(arguments);
+   this.prop1="val1";
+   this.prop2="val2";
+};
+
+var myArguments = ["hi", "how", "are", "you", "mr", null];
+var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
+
+console.log(new myConstructorWithArguments);
+// (internal log of myConstructor):           arguments.length: 6
+// (internal log of myConstructor):           ["hi", "how", "are", "you", "mr", null]
+// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
+ +

배열 리터럴에서의 전개

+ +

더 강력한 배열 리터럴

+ +

전개 구문 없이, 이미 존재하는 배열을 일부로 하는 새로운 배열을 생성하기에, 배열 리터럴 문법은 더 이상 충분하지 않으며 {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} 등의 조합을 사용하는 대신 명령형 코드를 사용해야 했습니다. 전개 구문으로 이는 훨씬 더 간결해졌습니다.

+ +
var parts = ['shoulders', 'knees'];
+var lyrics = ['head', ...parts, 'and', 'toes'];
+// ["head", "shoulders", "knees", "and", "toes"]
+
+ +

인수 목록을 위한 spread 처럼, ... 은 배열 리터럴의 어디에서든 사용될 수 있으며 여러번 사용될 수도 있습니다.

+ +

배열 복사

+ +
var arr = [1, 2, 3];
+var arr2 = [...arr]; // arr.slice() 와 유사
+arr2.push(4);
+
+// arr2 은 [1, 2, 3, 4] 이 됨
+// arr 은 영향을 받지 않고 남아 있음
+
+ +
+

참고: Spread 문법은 배열을 복사할 때 1 레벨 깊이에서 효과적으로 동작합니다. 그러므로, 다음 예제와 같이 다차원 배열을 복사하는것에는 적합하지 않을 수 있습니다. ({{jsxref("Object.assign()")}} 과 전개 구문이 동일합니다)

+
+ +
var a = [[1], [2], [3]];
+var b = [...a];
+b.shift().shift(); // 1
+// 이제 배열 a 도 영향을 받음: [[], [2], [3]]
+
+ +

배열을 연결하는 더 나은 방법

+ +

{{jsxref("Array.prototype.concat()")}} 은 배열을 존재하는 배열의 끝에 이어붙이는데 종종 사용됩니다. 전개 구문 없이, 이는 다음과 같이 작성됩니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// arr2 의 모든 항목을 arr1 에 붙임
+arr1 = arr1.concat(arr2);
+ +

전개 구문을 사용해 이는 다음과 같아집니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr1, ...arr2]; // arr1 은 이제 [0, 1, 2, 3, 4, 5]
+
+ +

{{jsxref("Array.prototype.unshift()")}}는 존재하는 배열의 시작 지점에 배열의 값들을 삽입하는데 종종 사용됩니다. 전개 구문 없이, 이는 다음과 같이 작성됩니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// arr2 의 모든 항목을 arr1 의 앞에 붙임
+Array.prototype.unshift.apply(arr1, arr2) // arr1 은 이제 [3, 4, 5, 0, 1, 2] 가 됨
+ +

전개 구문으로, 이는 다음과 같아집니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr2, ...arr1]; // arr1 은 이제 [3, 4, 5, 0, 1, 2] 가 됨
+
+ +
+

참고: unshift()와 달리, 위 예제는 새로운 arr1을 만들며 기존 배열을 변형하지 않습니다.

+
+ +

객체 리터럴에서의 전개

+ +

ECMAScript의 Rest/Spread 프로퍼티 제안 (stage 4) 은 객체 리터럴에 속성 전개를 추가합니다. 이는 제공된 객체가 소유한 열거형 프로퍼티를 새로운 객체로 복사합니다.

+ +

얕은 복제(prototype 제외) 또는 객체의 병합은 이제 {{jsxref("Object.assign()")}} 보다 더 짧은 문법을 사용해 가능합니다.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+
+var clonedObj = { ...obj1 };
+// Object { foo: "bar", x: 42 }
+
+var mergedObj = { ...obj1, ...obj2 };
+// Object { foo: "baz", x: 42, y: 13 }
+ +

{{jsxref("Object.assign()")}} 은 setters 를 트리거하지만 전개 구문은 그렇지 않음을 유의합니다.

+ +

{{jsxref("Object.assign()")}} 함수를 대체하거나 흉내낼 수 없음을 유의합니다.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+const merge = ( ...objects ) => ( { ...objects } );
+
+var mergedObj = merge ( obj1, obj2);
+// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
+
+var mergedObj = merge ( {}, obj1, obj2);
+// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
+ +

위 예제에서, 전개 구문은 예상대로 동작하지 않습니다. 나머지 매개변수로 인해, 인수 배열을 객체 리터럴로 전개합니다.

+ +

이터러블 전용

+ +

전개 구문 (spread 프로퍼티인 경우 제외) 은 iterable 객체에만 적용됩니다.

+ +
var obj = {'key1': 'value1'};
+var array = [...obj]; // TypeError: obj is not iterable
+
+ +

많은 값과 Spread

+ +

함수 호출에서 spread 문법을 사용할 때, 자바스크립트 엔진의 인수 길이 제한을 초과하지 않도록 주의합니다. 자세한 내용은 apply() 를 보세요.

+ +

나머지 구문 (매개변수)

+ +

나머지 구문은 전개 구문과 정확히 같아보이지만, 대신 배열이나 객체를 분해할 때 사용됩니다. 어떤 면에서, 나머지 구문은 전개 구문과 반대입니다. 전개는 배열을 그 엘리먼트로 '확장' 하는 반면, 나머지는 여러 엘리먼트를 수집하며 이를 하나의 엘리먼트로 '압축' 합니다. 나머지 매개변수 문서를 보세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}명세의 여러 섹션에서 정의 됨: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Object Initializer 에서 정의됨
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}변동 없음.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}변동 없음.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.spread")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/super/index.html b/files/ko/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..fbcb123c57 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/super/index.html @@ -0,0 +1,176 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operators/super +tags: + - Classes + - JavaScript + - Left-hand-side expressions + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/super +--- +
{{jsSidebar("Operators")}}
+ +

super 키워드는 부모 오브젝트의 함수를 호출할 때 사용됩니다.

+ +

super.propsuper[expr] 표현식은 클래스 와 객체리터럴의 어떠한 메서드 정의 방법에서도 유효합니다.

+ +

문법

+ +
super([arguments]); // 부모 생성자 호출
+super.functionOnParent([arguments]);
+
+ +

설명

+ +

생성자에서는 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출되어야 합니다. 또한 super 키워드는 부모 객체의 함수를 호출하는데 사용될 수 있습니다.

+ +

예제

+ +

클래스에서 super 사용하기

+ +

이 예제는 옆의 링크에서 발췌하였습니다. classes sample (live demo).

+ +
class Polygon {
+  constructor(height, width) {
+    this.name = 'Polygon';
+    this.height = height;
+    this.width = width;
+  }
+  sayName() {
+    console.log('Hi, I am a ', this.name + '.');
+  }
+}
+
+class Square extends Polygon {
+  constructor(length) {
+    this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.
+
+    // 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다.
+    // Polygon의 길이와 높이를 넘겨줍니다.
+    super(length, length);
+
+    // 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
+    // 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

정적 메서드에서 Super 호출

+ +

static 메서드에서도 super를 호출할 수 있습니다.

+ +
class Human {
+  constructor() {}
+  static ping() {
+    return 'ping';
+  }
+}
+
+class Computer extends Human {
+  constructor() {}
+  static pingpong() {
+    return super.ping() + ' pong';
+  }
+}
+Computer.pingpong(); // 'ping pong'
+
+ +

super의 속성 삭제

+ +

delete 연산자를 사용할 수 없으며 super.prop 또는 super[expr] 표현식을 사용하여 부모 클래스의 속성을 삭제할 경우 {{jsxref("ReferenceError")}} 오류가 발생합니다.

+ +
class Base {
+  constructor() {}
+  foo() {}
+}
+class Derived {
+  constructor() {}
+  delete() {
+    delete super.foo;
+  }
+}
+
+new Derived().delete(); // 참조오류: 'super'완 관련된 삭제가 유효하지 않습니다. 
+ +

Super.prop은 non-writable 속성을 덮어 쓸 수 없습니다

+ +

예를 들어 {{jsxref("Object.defineProperty")}}로 속성을 정의할 때, super의 속성 값을 덮어 쓸 수 없습니다.

+ +
class X {
+  constructor() {
+    Object.defineProperty(this, "prop", {
+      configurable: true,
+      writable: false,
+      value: 1
+    });
+  }
+  f() {
+    super.prop = 2;
+  }
+}
+
+var x = new X();
+x.f();
+console.log(x.prop); // 1
+
+ +

객체 리터럴에서 super.prop 사용하기

+ +

Super는 object initializer / literal 표기법에서 사용할 수 있습니다. 아래의 예제에서, 두개의 객체는 메서드를 정의합니다. 두번째 객체에서, super는  첫번째 객체의 메서드를 호출합니다. 이 예제는 {{jsxref("Object.setPrototypeOf()")}}를 이용하여  obj2 prototype에 obj1을 세팅하여, super가 obj1의 method1을 찾을 수 있도록 합니다.

+ +
var obj1 = {
+  method1() {
+    console.log("method 1");
+  }
+}
+
+var obj2 = {
+  method2() {
+   super.method1();
+  }
+}
+
+Object.setPrototypeOf(obj2, obj1);
+obj2.method2(); // logs "method 1"
+
+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-super-keyword', 'super')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.super")}}

+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/operators/this/index.html b/files/ko/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..8a2807a5d8 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/this/index.html @@ -0,0 +1,398 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +tags: + - JavaScript + - Operator + - Primary Expressions + - Reference +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar("Operators")}}
+ +

JavaScript에서 함수의 this 키워드는 다른 언어와 조금 다르게 동작합니다. 또한 엄격 모드와 비엄격 모드에서도 일부 차이가 있습니다.

+ +

대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정됩니다. 실행중에는 할당으로 설정할 수 없고 함수를 호출할 때 마다 다를 수 있습니다. ES5는 {{jsxref('Operators/this', "함수를 어떻게 호출했는지 상관하지 않고 this 값을 설정할 수 있는")}} {{jsxref("Function.prototype.bind()", "bind")}} 메서드를 도입했고, ES2015는 스스로의 this 바인딩을 제공하지 않는 화살표 함수를 추가했습니다(이는 렉시컬 컨텍스트안의 this값을 유지합니다).

+ +
{{EmbedInteractiveExample("pages/js/expressions-this.html")}}
+ + + +

구문

+ +
this
+ +

+ +

실행 컨텍스트(global, function 또는 eval)의 프로퍼티는 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값이든 될 수 있습니다.

+ +

전역 문맥

+ +

전역 실행 문맥global execution context에서 this는 엄격 모드 여부에 관계 없이 전역 객체를 참조합니다.

+ +
// 웹 브라우저에서는 window 객체가 전역 객체
+console.log(this === window); // true
+
+a = 37;
+console.log(window.a); // 37
+
+this.b = "MDN";
+console.log(window.b)  // "MDN"
+console.log(b)         // "MDN"
+ +
+

노트: global {{jsxref("globalThis")}} 프로퍼티를 사용하여 코드가 실행중인 현재 컨텍스트와 관계없이 항상 전역 객체를 얻을 수 있습니다.

+
+ +

함수 문맥

+ +

함수 내부에서 this의 값은 함수를 호출한 방법에 의해 좌우됩니다.

+ +

단순 호출

+ +

다음 예제는 엄격 모드가 아니며 this의 값이 호출에 의해 설정되지 않으므로, 기본값으로 브라우저에서는 {{domxref("Window", "window")}}인 전역 객체를 참조합니다.

+ +
function f1() {
+  return this;
+}
+
+// 브라우저
+f1() === window; // true
+
+// Node.js
+f1() === global; // true
+ +

반면에 엄격 모드에서 this 값은 실행 문맥에 진입하며 설정되는 값을 유지하므로 다음 예시에서 보여지는 것 처럼 thisundefined로 남아있습니다.

+ +
function f2(){
+  "use strict"; // 엄격 모드 참고
+  return this;
+}
+
+f2() === undefined; // true
+
+ +
+

두번째 예제에서 f2를 객체의 메서드나 속성(예: window.f2())으로써가 아닌 직접 호출했기 때문에  this는 {{jsxref("undefined")}}여야 합니다. 그러나 엄격 모드를 처음 지원하기 시작한 초기 브라우저에서는 구현하지 않았고, window 객체를 잘못 반환했습니다.

+
+ +

this의 값을 한 문맥에서 다른 문맥으로 넘기려면 다음 예시와 같이 {{jsxref("Function.prototype.call()", "call()")}}이나 {{jsxref("Function.prototype.apply", "apply()")}}를 사용하세요.

+ +

예시 1

+ +
// call 또는 apply의 첫 번째 인자로 객체가 전달될 수 있으며 this가 그 객체에 묶임
+var obj = {a: 'Custom'};
+
+// 변수를 선언하고 변수에 프로퍼티로 전역 window를 할당
+var a = 'Global';
+
+function whatsThis() {
+  return this.a;  // 함수 호출 방식에 따라 값이 달라짐
+}
+
+whatsThis();          // this는 'Global'. 함수 내에서 설정되지 않았으므로 global/window 객체로 초기값을 설정한다.
+whatsThis.call(obj);  // this는 'Custom'. 함수 내에서 obj로 설정한다.
+whatsThis.apply(obj); // this는 'Custom'. 함수 내에서 obj로 설정한다.
+
+ +

예시 2

+ +
function add(c, d) {
+  return this.a + this.b + c + d;
+}
+
+var o = {a: 1, b: 3};
+
+// 첫 번째 인자는 'this'로 사용할 객체이고,
+// 이어지는 인자들은 함수 호출에서 인수로 전달된다.
+add.call(o, 5, 7); // 16
+
+// 첫 번째 인자는 'this'로 사용할 객체이고,
+// 두 번째 인자는 함수 호출에서 인수로 사용될 멤버들이 위치한 배열이다.
+add.apply(o, [10, 20]); // 34
+
+ +

비엄격 모드에서 this로 전달된 값이 객체가 아닌 경우, callapply는 이를 객체로 변환하기 위한 시도를 합니다. nullundefined 값은 전역 객체가 됩니다. 7이나 'foo'와 같은 원시값은 관련된 생성자를 사용해 객체로 변환되며, 따라서 원시 숫자 7new Number(7)에 의해 객체로 변환되고 문자열 'foo'new String('foo')에 의해 객체로 변환됩니다.

+ +
function bar() {
+  console.log(Object.prototype.toString.call(this));
+}
+
+bar.call(7);     // [object Number]
+bar.call('foo'); // [object String]
+bar.call(undefined); // [object global]
+
+ +

bind 메서드

+ +

ECMAScript 5는 {{jsxref("Function.prototype.bind")}}를 도입했습니다. f.bind(someObject)를 호출하면 f와 같은 본문(코드)과 범위를 가졌지만 this는 원본 함수를 가진 새로운 함수를 생성합니다. 새 함수의 this는 호출 방식과 상관없이 영구적으로bind()의 첫 번째 매개변수로 고정됩니다.

+ +
function f() {
+  return this.a;
+}
+
+var g = f.bind({a: 'azerty'});
+console.log(g()); // azerty
+
+var h = g.bind({a: 'yoo'}); // bind는 한 번만 동작함!
+console.log(h()); // azerty
+
+var o = {a: 37, f: f, g: g, h: h};
+console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty
+ +

화살표 함수

+ +

화살표 함수에서 this는 자신을 감싼 정적 범위lexical context입니다. 전역 코드에서는 전역 객체를 가리킵니다.

+ +
var globalObject = this;
+var foo = (() => this);
+console.log(foo() === globalObject); // true
+ +
+

참고: 화살표 함수를 call(), bind(), apply()를 사용해 호출할 때 this의 값을 정해주더라도 무시합니다. 사용할 매개변수를 정해주는 건 문제 없지만, 첫 번째 매개변수(thisArg)는 null을 지정해야 합니다.

+
+ +
// 객체로서 메서드 호출
+var obj = {func: foo};
+console.log(obj.func() === globalObject); // true
+
+// call을 사용한 this 설정 시도
+console.log(foo.call(obj) === globalObject); // true
+
+// bind를 사용한 this 설정 시도
+foo = foo.bind(obj);
+console.log(foo() === globalObject); // true
+ +

어떤 방법을 사용하든 foothis는 생성 시점의 것으로 설정됩니다(위 예시에서는 global 객체). 다른 함수 내에서 생성된 화살표 함수에도 동일하게 적용됩니다. this는 싸여진 렉시컬 컨텍스트의 것으로 유지됩니다.

+ +
// this를 반환하는 메소드 bar를 갖는 obj를 생성합니다.
+// 반환된 함수는 화살표 함수로 생성되었으므로,
+// this는 감싸진 함수의 this로 영구적으로 묶입니다.
+// bar의 값은 호출에서 설정될 수 있으며, 이는 반환된 함수의 값을 설정하는 것입니다.
+var obj = {
+  bar: function() {
+    var x = (() => this);
+    return x;
+  }
+};
+
+// obj의 메소드로써 bar를 호출하고, this를 obj로 설정
+// 반환된 함수로의 참조를 fn에 할당
+var fn = obj.bar();
+
+// this 설정 없이 fn을 호출하면,
+// 기본값으로 global 객체 또는 엄격 모드에서는 undefined
+console.log(fn() === obj); // true
+
+// 호출 없이 obj의 메소드를 참조한다면 주의하세요.
+var fn2 = obj.bar;
+// 화살표 함수의 this를 bar 메소드 내부에서 호출하면
+// fn2의 this를 따르므로 window를 반환할것입니다.
+console.log(fn2()() == window); // true
+ +

위 예시에서, obj.bar에 할당된 함수(익명 함수 A라고 지칭)는 화살표 함수로 생성된 다른 함수(익명 함수 B라고 지칭)를 반환합니다. 결과로써 함수 B가 호출될 때 B의 this는 영구적으로 obj.bar(함수 A)의 this로 설정됩니다. 반환됨 함수(함수 B)가 호출될 때, this는 항상 초기에 설정된 값일 것입니다. 위 코드 예시에서, 함수 B의 this는 함수 A의 thisobj로 설정되므로, 일반적으로 thisundefined나 global 객체로 설정하는 방식으로 호출할 때도(또는 이전 예시에서처럼 global 실행 컨텍스트에서 다른 방법을 사용할 때에도) obj의 설정은 유지됩니다.

+ +

객체의 메서드로서

+ +

함수를 어떤 객체의 메서드로 호출하면 this의 값은 그 객체를 사용합니다.

+ +

다음 예제에서 o.f()를 실행할 때 o 객체가 함수 내부의 this와 연결됩니다.

+ +
var o = {
+  prop: 37,
+  f: function() {
+    return this.prop;
+  }
+};
+
+console.log(o.f()); // 37
+
+ +

이 행동이 함수가 정의된 방법이나 위치에 전혀 영향을 받지 않는 것에 유의해라. 이전 예제에서, o 의 정의 중 f 함수를 구성원으로 내부에 정의 하였다.  그러나, 간단하게 함수를 먼저 정의하고 나중에 o.f를 추가할 수 있다. 이렇게 하면 동일한 동작 결과 이다 :

+ +
var o = {prop: 37};
+
+function independent() {
+  return this.prop;
+}
+
+o.f = independent;
+
+console.log(o.f()); // logs 37
+
+ +

이는 함수가 o의 멤버 f로 부터 호출 된 것만이 중요하다는 것을 보여준다.

+ +

마찬가지로, 이 this 바인딩은 가장 즉각으로 멤버 대상에 영향을 받는다. 다음 예제에서, 함수를 실행할 때, 객체 o.b의 메소드 g 로서 호출한다. 이것이 실행되는 동안, 함수 내부의 thiso.b를 나타낸다. 객체는 그 자신이 o의 멤버 중 하나라는 사실은 중요하지 않다. 가장 즉각적인 참조가  중요한 것이다.

+ +
o.b = {g: independent, prop: 42};
+console.log(o.b.g()); // logs 42
+
+ +

객체의 프로토타입 체인에서의 this

+ +

같은 개념으로 객체의 프로토타입 체인 어딘가에 정의한 메서드도 마찬가지입니다. 메서드가 어떤 객체의 프로토타입 체인 위에 존재하면, this의 값은 그 객체가 메서드를 가진 것 마냥 설정됩니다.

+ +
var o = {
+  f:function() { return this.a + this.b; }
+};
+var p = Object.create(o);
+p.a = 1;
+p.b = 4;
+
+console.log(p.f()); // 5
+
+ +

이 예제에서, f 속성을 가지고 있지 않은 변수 p가 할당된 객체는, 프로토타입으로 부터 상속받는다. 그러나 그것은 결국 o에서 f 이름을 가진 멤버를 찾는 되는 문제가 되지 않는다 ; p.f를 찾아 참조하기 시작하므로, 함수 내부의 this p 처럼 나타나는 객체 값을 취한다. 즉, fp의 메소드로서 호출된 이후로, thisp를 나타낸다. 이것은 JavaScript의 프로토타입 상속의 흥미로운 기능이다.

+ +

접근자와 설정자의 this

+ +

다시 한 번 같은 개념으로, 함수를 접근자와 설정자에서 호출하더라도 동일합니다. 접근자나 설정자로 사용하는 함수의 this는 접근하거나 설정하는 속성을 가진 객체로 묶입니다.

+ +
function sum() {
+  return this.a + this.b + this.c;
+}
+
+var o = {
+  a: 1,
+  b: 2,
+  c: 3,
+  get average() {
+    return (this.a + this.b + this.c) / 3;
+  }
+};
+
+Object.defineProperty(o, 'sum', {
+    get: sum, enumerable: true, configurable: true});
+
+console.log(o.average, o.sum); // 2, 6
+
+ +

생성자로서

+ +

함수를 {{jsxref("Operators/new", "new")}} 키워드와 함께 생성자로 사용하면 this는 새로 생긴 객체에 묶입니다.

+ +
+

While the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

+
+ +
/*
+ * Constructors work like this:
+ *
+ * function MyConstructor(){
+ *   // Actual function body code goes here.
+ *   // Create properties on |this| as
+ *   // desired by assigning to them.  E.g.,
+ *   this.fum = "nom";
+ *   // et cetera...
+ *
+ *   // If the function has a return statement that
+ *   // returns an object, that object will be the
+ *   // result of the |new| expression.  Otherwise,
+ *   // the result of the expression is the object
+ *   // currently bound to |this|
+ *   // (i.e., the common case most usually seen).
+ * }
+ */
+
+function C() {
+  this.a = 37;
+}
+
+var o = new C();
+console.log(o.a); // 37
+
+
+function C2() {
+  this.a = 37;
+  return {a: 38};
+}
+
+o = new C2();
+console.log(o.a); // 38
+
+ +

DOM 이벤트 처리기로서

+ +

함수를 이벤트 처리기로 사용하면 this는 이벤트를 발사한 요소로 설정됩니다. 일부 브라우저는 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 외의 다른 방법으로 추가한 처리기에 대해선 이 규칙을 따르지 않습니다.

+ +
// 처리기로 호출하면 관련 객체를 파랗게 만듦
+function bluify(e) {
+  // 언제나 true
+  console.log(this === e.currentTarget);
+  // currentTarget과 target이 같은 객체면 true
+  console.log(this === e.target);
+  this.style.backgroundColor = '#A5D9F3';
+}
+
+// 문서 내 모든 요소의 목록
+var elements = document.getElementsByTagName('*');
+
+// 어떤 요소를 클릭하면 파랗게 변하도록
+// bluify를 클릭 처리기로 등록
+for (var i = 0; i < elements.length; i++) {
+  elements[i].addEventListener('click', bluify, false);
+}
+ +

인라인 이벤트 핸들러에서

+ +

코드를 인라인 이벤트 처리기로 사용하면 this는 처리기를 배치한 DOM 요소로 설정됩니다.

+ +
<button onclick="alert(this.tagName.toLowerCase());">
+  this 표시
+</button>
+ +

위의 경고창은 button을 보여줍니다. 다만 바깥쪽 코드만 this를 이런 방식으로 설정합니다.

+ +
<button onclick="alert((function() { return this; })());">
+  내부 this 표시
+</button>
+ +

위의 경우, 내부 함수의 this는 정해지지 않았으므로 전역/window 객체를 반환합니다. 즉 비엄격 모드에서 this를 설정하지 않은 경우의 기본값입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.this")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/typeof/index.html b/files/ko/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..acdd2eedbb --- /dev/null +++ b/files/ko/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,227 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operators/typeof +tags: + - JavaScript + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +
{{jsSidebar("Operators")}}
+ +

typeof 연산자는 피연산자의 평가 전 자료형을 나타내는 문자열을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
+ + + +

구문

+ +

typeof 연산자는 피연산자 앞에 위치합니다.

+ +
typeof operand
+typeof(operand)
+ +

매개변수

+ +
+
operand
+
자료형을 가져올 객체 또는 {{glossary("Primitive", "원시값")}}을 나타내는 표현식.
+
+ +

설명

+ +

typeof가 반환할 수 있는 값을 아래 표에서 볼 수 있습니다. 자료형과 원시값에 대한 자세한 정보는 JavaScript 자료형과 자료구조 페이지를 참고하세요.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeResult
{{glossary("Undefined")}}"undefined"
{{glossary("Null")}}"object" ({{anch("null", "아래")}} 참고)
{{glossary("Boolean")}}"boolean"
{{glossary("Number")}}"number"
{{glossary("BigInt")}}"bigint"
{{glossary("String")}}"string"
{{glossary("Symbol")}} (ECMAScript 2015에서 추가)"symbol"
호스트 객체 (JS 환경에서 제공)구현체마다 다름
{{glossary("Function")}} 객체 (ECMA-262 표현으로는 [[Call]]을 구현하는 객체)"function"
다른 모든 객체"object"
+ +
+

Note: ECMAScript 2019 and older permitted implementations to have typeof return any implementation-defined string value for non-callable non-standard exotic objects.

+ +

The only known browser to have actually taken advantage of this is old Internet Explorer (see below).

+
+ +

예제

+ +
// Numbers
+typeof 37 === 'number';
+typeof 3.14 === 'number';
+typeof Math.LN2 === 'number';
+typeof Infinity === 'number';
+typeof NaN === 'number'; // Despite being "Not-A-Number"
+typeof Number(1) === 'number'; // but never use this form!
+
+typeof 42n === 'bigint';
+
+
+// Strings
+typeof "" === 'string';
+typeof "bla" === 'string';
+typeof (typeof 1) === 'string'; // typeof always returns a string
+typeof String("abc") === 'string'; // but never use this form!
+
+
+// Booleans
+typeof true === 'boolean';
+typeof false === 'boolean';
+typeof Boolean(true) === 'boolean'; // but never use this form!
+
+
+// Symbols
+typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+
+// Undefined
+typeof undefined === 'undefined';
+typeof declaredButUndefinedVariable === 'undefined';
+typeof undeclaredVariable === 'undefined';
+
+
+// Objects
+typeof {a:1} === 'object';
+
+// use Array.isArray or Object.prototype.toString.call
+// to differentiate regular objects from arrays
+typeof [1, 2, 4] === 'object';
+
+typeof new Date() === 'object';
+
+
+// The following is confusing. Don't use!
+typeof new Boolean(true) === 'object';
+typeof new Number(1) === 'object';
+typeof new String("abc") === 'object';
+
+
+// Functions
+typeof function(){} === 'function';
+typeof class C {} === 'function';
+typeof Math.sin === 'function';
+
+ +

추가 정보

+ +

null

+ +
// This stands since the beginning of JavaScript
+typeof null === 'object';
+
+ +

자바스크립트를 처음 구현할 때, 자바스크립트 값은 타입 태그와 값으로 표시되었습니다. 객체의 타입 태그는 0이었습니다. null은 Null pointer(대부분의 플랫폼에서 0x00)로 표시되었습니다. 그 결과 null은 타입 태그로 0을 가지며, 따라서 typeof는 object를 반환합니다. (참고 문서)

+ +

ECMAScript에 수정이 제안(opt-in을 통해)되었으나 거절되었습니다. 제안된 것은 다음과 같습니다. typeof null === 'null'.

+ +

Regular expressions

+ +

Callable regular expressions were a non-standard addition in some browsers.

+ +
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
+typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.typeof")}}

+ +

IE 참고사항

+ +

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

+ +
typeof alert === 'object'
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/void/index.html b/files/ko/web/javascript/reference/operators/void/index.html new file mode 100644 index 0000000000..79fe2c1837 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/void/index.html @@ -0,0 +1,122 @@ +--- +title: void +slug: Web/JavaScript/Reference/Operators/void +tags: + - JavaScript + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/void +--- +
{{jsSidebar("Operators")}}
+ +

void 연산자는 주어진 표현식을 평가하고 {{jsxref("undefined")}}를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-voidoperator.html")}}
+ + + +

구문

+ +
void expression
+ +

설명

+ +

void는 값을 생성하는 표현식을 평가해서 {{jsxref("undefined")}}를 반환합니다.

+ +

오직 undefined 원시값을 얻기 위해 void 0 또는 void(0)처럼 사용하는 경우도 볼 수 있습니다. 이런 경우 전역 {{jsxref("undefined")}}를 대신 사용해도 됩니다.

+ +

void 연산자의 우선순위도 유념해야 합니다. 그룹 연산자(괄호)를 사용하면 void 연산자를 사용한 식의 평가 과정을 더 명확하게 보일 수 있습니다.

+ +
void 2 == '2'; // undefined == '2', false
+void (2 == '2'); // void true, undefined
+
+ +

IIFE

+ +

즉시 실행 함수 표현식({{Glossary("IIFE")}})을 사용할 때 void를 사용하면 function 키워드를 선언문이 아니라 표현식처럼 간주하도록 강제할 수 있습니다.

+ +
void function iife() {
+    var bar = function () {};
+    var baz = function () {};
+    var foo = function () {
+        bar();
+        baz();
+     };
+    var biz = function () {};
+
+    foo();
+    biz();
+}();
+
+ +

JavaScript URI

+ +

javascript:로 시작하는 URI를 지원하는 브라우저에서는, URI에 있는 코드의 평가 결과가 {{jsxref("undefined")}}가 아니라면 페이지의 콘텐츠를 반환 값으로 대체합니다. void 연산자를 사용하면 undefined를 반환할 수 있습니다. 다음 예제를 확인하세요.

+ +
<a href="javascript:void(0);">
+  클릭해도 아무 일도 없음
+</a>
+<a href="javascript:void(document.body.style.backgroundColor='green');">
+  클릭하면 배경색이 녹색으로
+</a>
+
+ +
+

참고: javascript: 의사 프로토콜보다 이벤트 처리기와 같은 대체재 사용을 권장합니다.

+
+ +

새지 않는 화살표 함수

+ +

Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change.

+ +
button.onclick = () => void doSomething();
+ +

This ensures the return value of doSomething changing from undefined to true will not change the behavior of this code.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-void-operator', 'The void Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-void-operator', 'The void Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.4.2', 'The void Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.4.2', 'The void Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.4.2', 'The void Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.void")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/yield/index.html b/files/ko/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..ef884816d2 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,182 @@ +--- +title: yield +slug: Web/JavaScript/Reference/Operators/yield +tags: + - ECMAScript 2015 + - Generators + - Iterator + - JavaScript + - Operator + - 반복자 + - 생성기 +translation_of: Web/JavaScript/Reference/Operators/yield +--- +
{{jsSidebar("Operators")}}
+ +

yield 키워드는 제너레이터 함수 ({{jsxref("Statements/function*", "function*")}} 또는  레거시 generator 함수)를 중지하거나 재개하는데 사용됩니다.

+ +

문법

+ +
[rv] = yield [expression];
+ +
+
expression
+
제너레이터 함수에서 제너레이터 프로토콜을 통해 반환할 값을 정의합니다.  값이 생략되면, undefined를 반환합니다.
+
rv
+
+

제너레이터 실행을 재개 하기 위해서, optional value을 제너레이터의 next() 메서드로 전달하여 반환합니다.

+
+
+ +

설명

+ +

yield 키워드는 제너레이터 함수의 실행을 중지시키거나 그리고  yield 키워드 뒤에오는 표현식[expression]의 값은 제너레이터의 caller로 반환된다. 제너레이터 버전의 return 키워드로 생각 할 수 있다.

+ +

yield 키워드는 실질적으로  value 와 done 이라는 두 개의 속성을 가진 IteratorResult 객체를 반환한다. value 속성은 yield 표현(expression)의 실행 결과를 나타내고, done 속성은 제너레이터 함수가 완전히 종료되었는지 여부를 불린(Boolean) 형태로 보여줍니다. 

+ +

yield 표현식에서 중지되면 ,제너레이터의 next()가 메서드가 호출될 때까지 제너레이터의 코드 실행이 중지된다. 제너레이터의 next()메서드를 호출할 때마다 제너레이터는 실행을 재개하며 그리고 다음의 같은 경우에 진행될 때 실행된다:

+ + + +

만약에 optional value가 제너레이터의 next() 메서드로 전달되면, optional value는  제너레이터의 현재 yield의 연산으로 반환되는 값이 된다.

+ +

generator 코드 경로, yield연산자, {{jsxref("Generator.prototype.next()")}}에 이르기까지 새로운 시작 값을 지정할 수 있는 능력과 제네레이터는 커다란 힘과 제어를 제공한다.

+ +

예시

+ +

다음 코드는 제너레이터 함수의 선언의 예시이다.

+ +
function* foo(){
+  var index = 0;
+  while (index <= 2) // when index reaches 3,
+                     // yield's done will be true
+                     // and its value will be undefined;
+    yield index++;
+}
+ +

제너레이터 함수가 정의되면 , 아래 코드와 보여지는 것처럼 iterator로 만들어 사용할 수 있다.

+ +
var iterator = foo();
+console.log(iterator.next()); // { value: 0, done: false }
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#', 'Yield')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox-specific notes

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/yield_star_/index.html b/files/ko/web/javascript/reference/operators/yield_star_/index.html new file mode 100644 index 0000000000..3bbb10146d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/yield_star_/index.html @@ -0,0 +1,164 @@ +--- +title: yield* +slug: Web/JavaScript/Reference/Operators/yield* +tags: + - ECMAScript 2015 + - Generators + - Iterable + - Iterator + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/yield* +--- +
{{jsSidebar("Operators")}}
+ +

yield* 표현식은 다른 {{jsxref("Statements/function*", "generator")}} 또는 이터러블(iterable) 객체에 yield를 위임할 때 사용됩니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-yieldasterisk.html")}}
+ + + +

구문

+ +
yield* [[expression]];
+ +
+
expression
+
이터러블(iterable) 객체를 반환하는 표현식.
+
+ +

설명

+ +

yield* 표현은 피연산자를 반복하고 반환되는 값을 yield합니다.

+ +

yield* 표현 자체의 값은 반복자(iterator)가 종료될 때 반환되는 값입니다. (i.e., done이 true일 때)

+ +

예제

+ +

다른 생성기(generator)에 위임하기

+ +

다음 코드는, next() 호출을 통해 g1()으로부터 yield 되는 값을 g2()에서 yield 되는 것처럼 만듭니다.

+ +
function* g1() {
+  yield 2;
+  yield 3;
+  yield 4;
+}
+
+function* g2() {
+  yield 1;
+  yield* g1();
+  yield 5;
+}
+
+var iterator = g2();
+
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: 3, done: false }
+console.log(iterator.next()); // { value: 4, done: false }
+console.log(iterator.next()); // { value: 5, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+
+ +

다른 이터러블(iterable) 객체

+ +

생성기 객체 말고도, yield*는 다른 반복 가능한 객체도 yield 할 수 있습니다. e.g. 배열, 문자열 또는 arguments 객체

+ +
function* g3() {
+  yield* [1, 2];
+  yield* "34";
+  yield* Array.from(arguments);
+}
+
+var iterator = g3(5, 6);
+
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: "3", done: false }
+console.log(iterator.next()); // { value: "4", done: false }
+console.log(iterator.next()); // { value: 5, done: false }
+console.log(iterator.next()); // { value: 6, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+
+ +

yield* 표현 자체의 값

+ +

yield* 는 구문이 아닌 표현입니다. 따라서 값으로 평가됩니다.

+ +
function* g4() {
+  yield* [1, 2, 3];
+  return "foo";
+}
+
+var result;
+
+function* g5() {
+  result = yield* g4();
+}
+
+var iterator = g5();
+
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: 3, done: false }
+console.log(iterator.next()); // { value: undefined, done: true },
+                              // g4() 는 여기서 { value: "foo", done: true }를 반환합니다
+
+console.log(result);          // "foo"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.yield_star")}}

+ +

Firefox에 한정된 내용

+ + + +

같이 보기

+ + diff --git "a/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" "b/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" new file mode 100644 index 0000000000..2e1140eed5 --- /dev/null +++ "b/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" @@ -0,0 +1,249 @@ +--- +title: 논리 연산자 +slug: Web/JavaScript/Reference/Operators/논리_연산자(Logical_Operators) +tags: + - JavaScript + - Logic + - Not + - Operator + - Reference + - and + - or + - 논리 +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

논리 연산자는 보통 {{jsxref("Boolean")}}(논리적) 값과 함께 쓰이며, 불리언 값을 반환합니다. 그런데, &&|| 연산자는 사실 피연산자 중 하나의 값을 반환합니다. 그러므로 불리언 외의 다른 값과 함께 사용하면 불리언 값이 아닌 것을 반환할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-logicaloperator.html")}}
+ + + +

설명

+ +

다음 표는 논리 연산자의 종류입니다. (expr은 불리언을 포함해서 아무 자료형이나 가능합니다)

+ + + + + + + + + + + + + + + + + + + + + + + + +
연산자구문설명
논리 AND (&&)expr1 && expr2expr1true로 변환할 수 있는 경우 expr2을 반환하고, 그렇지 않으면 expr1을 반환합니다.
논리 OR (||)expr1 || expr2 +

expr1true로 변환할 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다.

+
논리 NOT (!)!expr단일 피연산자를 true로 변환할 수 있으면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.
+ +

값을 true로 변환하면 값이 {{Glossary("truthy", "참")}}인 것입니다.
+ 값을 false로 변환할 수 있으면 값이 {{Glossary("falsy", "거짓")}}인 것입니다.

+ +

거짓으로 변환할 수 있는 표현의 예는 다음과 같습니다.

+ + + +

&& 연산자와 || 연산자를 불리언 값이 아닌 피연산자와 함께 사용될 수 있지만, 반환 값을 항상 불리언 원시값으로 변환할 수 있으므로 불리언 연산자로 생각할 수 있습니다. 반환 값을 직접 불리언으로 바꾸려면 {{jsxref("Boolean")}} 함수나 이중 부정 연산자를 사용하세요.

+ +

단락 평가

+ +

논리 표현식을 좌측부터 평가하므로, 아래 규칙에 따라 단락(short-circuit) 평가를 수행합니다.

+ + + +

"단락"이란, 위 규칙에서 expr을 평가하지 않는다는 뜻입니다. 따라서 평가 중 발생해야 할 부작용(예: expr이 함수 호출이면 절대 호출하지 않음)도 나타나지 않습니다. 단락 평가가 발생하는 원인은 첫 번째 피연산자를 평가한 순간 이미 연산자의 결과가 정해지기 때문입니다. 다음 예제를 살펴보세요.

+ +
function A(){ console.log('A 호출'); return false; }
+function B(){ console.log('B 호출'); return true; }
+
+console.log( A() && B() );
+// 함수 호출로 인해 콘솔에 "A 호출" 기록
+// 그 후 연산자의 결과값인 "false" 기록
+
+console.log( B() || A() );
+// 함수 호출로 인해 콘솔에 "B 호출" 기록
+// 그 후 연산자의 결과인 "true" 기록
+
+ +

연산자 우선순위

+ +

다음 두 식은 똑같아 보이지만, && 연산자는 || 이전에 실행되므로 서로 다릅니다. 연산자 우선순위를 참고하세요.

+ +
true || false && false      // returns true, because && is executed first
+(true || false) && false    // returns false, because operator precedence cannot apply
+ +

논리 AND (&&)

+ +

다음은 &&(논리 AND) 연산자의 예제입니다.

+ +
a1 = true  && true       // t && t returns true
+a2 = true  && false      // t && f returns false
+a3 = false && true       // f && t returns false
+a4 = false && (3 == 4)   // f && f returns false
+a5 = 'Cat' && 'Dog'      // t && t returns "Dog"
+a6 = false && 'Cat'      // f && t returns false
+a7 = 'Cat' && false      // t && f returns false
+a8 = ''    && false      // f && f returns ""
+a9 = false && ''         // f && f returns false
+ +

논리 OR (||)

+ +

다음은 ||(논리 OR) 연산자의 예제입니다.

+ +
o1 = true  || true       // t || t returns true
+o2 = false || true       // f || t returns true
+o3 = true  || false      // t || f returns true
+o4 = false || (3 == 4)   // f || f returns false
+o5 = 'Cat' || 'Dog'      // t || t returns "Cat"
+o6 = false || 'Cat'      // f || t returns "Cat"
+o7 = 'Cat' || false      // t || f returns "Cat"
+o8 = ''    || false      // f || f returns false
+o9 = false || ''         // f || f returns ""
+o10 = false || varObject // f || object returns varObject
+
+ +

논리 NOT (!)

+ +

다음은 !(논리 NOT) 연산자의 예제입니다.

+ +
n1 = !true               // !t returns false
+n2 = !false              // !f returns true
+n3 = !''                 // !f returns true
+n4 = !'Cat'              // !t returns false
+
+ +

이중 NOT (!!)

+ +

NOT 연산자 다수를 연속해서 사용하면 아무 값이나 불리언 원시값으로 강제 변환할 수 있습니다. 변환 결과는 피연산자 값의 "참스러움"이나 "거짓스러움"에 따릅니다. ({{Glossary("truthy", "참")}}과 {{Glossary("falsy", "거짓")}}을 참고하세요)

+ +

동일한 변환을 {{jsxref("Boolean")}} 함수로도 수행할 수 있습니다.

+ +
n1 = !!true                   // !!truthy returns true
+n2 = !!{}                     // !!truthy returns true: any object is truthy...
+n3 = !!(new Boolean(false))   // ...even Boolean objects with a false .valueOf()!
+n4 = !!false                  // !!falsy returns false
+n5 = !!""                     // !!falsy returns false
+n6 = !!Boolean(false)         // !!falsy returns false
+
+ +

불리언 변환 규칙

+ +

AND에서 OR로 변환

+ +

불리언 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 && bCondition2
+
+ +
!(!bCondition1 || !bCondition2)
+ +

OR에서 AND로 변환

+ +

불리언 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 || bCondition2
+
+ +
!(!bCondition1 && !bCondition2)
+ +

NOT 간 변환

+ +

불리언 계산에서, 다음 두 코드는 항상 같습니다.

+ +
!!bCondition
+
+ +
bCondition
+ +

중첩 괄호 제거

+ +

논리 표현식은 항상 왼쪽에서 오른쪽으로 평가되므로, 몇 가지 규칙을 따르면 복잡한 표현식에서 괄호를 제거할 수 있습니다.

+ +

중첩 AND 제거

+ +

불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 || (bCondition2 && bCondition3)
+
+ +
bCondition1 || bCondition2 && bCondition3
+ +

중첩 OR 제거

+ +

불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 && (bCondition2 || bCondition3)
+
+ +
!(!bCondition1 || !bCondition2 && !bCondition3)
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-11.11')}}{{Spec2('ES5.1')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
{{SpecName('ES6', '#sec-binary-logical-operators')}}{{Spec2('ES6')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
{{SpecName('ESDraft', '#sec-binary-logical-operators')}}{{Spec2('ESDraft')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.logical")}}

+ +

같이 보기

+ + diff --git "a/files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" "b/files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" new file mode 100644 index 0000000000..4bdd29b61c --- /dev/null +++ "b/files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" @@ -0,0 +1,200 @@ +--- +title: 배열 내포 +slug: Web/JavaScript/Reference/Operators/배열 +tags: + - JavaScript + - Non-standard + - Obsolete + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Array_comprehensions +--- +
{{jsSidebar("Operators")}}
+ +
표준이 아닙니다. 사용하지 않는 것을 권장합니다!
+Array comprehensions 문법은 비표준이며 Firefox 58부터는 제거됩니다. 향후 사용할 수 없게 되기 때문에 사용하지 않는것을 고려해보세요.
+{{jsxref("Array.prototype.map")}}, {{jsxref("Array.prototype.filter")}}, {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}}, and {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}.
+ +
{{Obsolete_Header(58)}}
+ +

array comprehension 문법은 기존의 배열을 기반으로 새로운 배열을 신속하게 어셈블 할 수 있는 JavaScript 표현식입니다. 그러나 표준 및 Firefox 구현에서 제거되었습니다. 사용하지 마세요!

+ +

Syntax

+ +
[for (x of iterable) x]
+[for (x of iterable) if (condition) x]
+[for (x of iterable) for (y of iterable) x + y]
+
+ +

Description

+ +

배열의 이해로 넘어가서, 다음 두가지의 요소들이 사용가능하다.

+ + + +

for-of 반복문은 항상 첫번째 요소이다. 여러개의 for-of 반복문이나 if 제어문을 사용할 수 있다.

+ +

배열 선언은 ECMAScript 2016에서 이전부터 표준으로 정립되어왔으며, 이는 다른 형태의 데이터(contents)를 이용해서 새로운 배열을 구성할 수 있게 해 준다.

+ +

아래의 선언은 숫자로 이루어진 배열 내 각각의 숫자들을 이용해서 double형의 새로운 배열을 만들어준다.

+ +
var numbers = [1, 2, 3, 4];
+var doubled = [for (i of numbers) i * 2];
+console.log(doubled); // logs 2,4,6,8
+
+ +

이것은 {{jsxref("Array.prototype.map", "map()")}} 연산자와 같은 기능을 한다.

+ +
var doubled = numbers.map(i => i * 2);
+
+ +

배열들은 또한 다양한 표현을 통해 몇몇개의 배열 원소들은 선택할 수 도 있다. 아래의 예제는 바로 홀수만 선택하는 예제이다.

+ +
var numbers = [1, 2, 3, 21, 22, 30];
+var evens = [for (i of numbers) if (i % 2 === 0) i];
+console.log(evens); // logs 2,22,30
+
+ +

{{jsxref("Array.prototype.filter", "filter()")}} 또한 같은 목적으로 얼마든지 사용가능하다.

+ +
var evens = numbers.filter(i => i % 2 === 0);
+
+ +

{{jsxref("Array.prototype.map", "map()")}} 그리고 {{jsxref("Array.prototype.filter", "filter()")}} 스타일과 같은 연산자들은 단한 배열 선언과 결합할 수 있다. 아래는 짝수만 필터링하고, 그 원소들을 2배씩하는 배열들을 만드는 예제이다.

+ +
var numbers = [1, 2, 3, 21, 22, 30];
+var doubledEvens = [for (i of numbers) if (i % 2 === 0) i * 2];
+console.log(doubledEvens); // logs 4,44,60
+
+ +

배열에서의 [ ] (꺽쇠괄호) 는 범위의 목적으로 암시적인 괄호를 의미한다. {{jsxref("Statements/let","let")}}를 사용하면서 정의된다면, 예제의 i와 같은 변수들이 사용된다. 이는 배열 밖에서 사용할 수 없음을 나타낸다.

+ +

배열의 원소에 넣어지는 것은 굳이 배열일 필요는 없다 iterators and generators 물론 가능하다.

+ +

심지어 문자열도 배열의 원소로 넣을 수 있다. 필터와 지도 액션과 같은 데에 이용할 수 있다.

+ +
var str = 'abcdef';
+var consonantsOnlyStr = [for (c of str) if (!(/[aeiouAEIOU]/).test(c)) c].join(''); // 'bcdf'
+var interpolatedZeros = [for (c of str) c + '0' ].join(''); // 'a0b0c0d0e0f0'
+
+ +

또한 입력 폼이 유지되지 않으므로, 문자열을 뒤집기 위해 {{jsxref("Array.prototype.join", "join()")}} 를 사용해야 한다.

+ +

Examples

+ +

단순 배열

+ +
[for (i of [1, 2, 3]) i * i ];
+// [1, 4, 9]
+
+var abc = ['A', 'B', 'C'];
+[for (letters of abc) letters.toLowerCase()];
+// ["a", "b", "c"]
+ +

if문에서의 배열

+ +
var years = [1954, 1974, 1990, 2006, 2010, 2014];
+[for (year of years) if (year > 2000) year];
+// [ 2006, 2010, 2014 ]
+[for (year of years) if (year > 2000) if (year < 2010) year];
+// [ 2006], the same as below:
+[for (year of years) if (year > 2000 && year < 2010) year];
+// [ 2006]
+
+ +

map과 filter를 비교한 배열

+ +

배열문법을 가장 쉽게 이해하는 방법은, 배열에서 {{jsxref("Array.map", "map")}} 그리고 {{jsxref("Array.filter", "filter")}}메소드를 비교하는 것이다.

+ +
var numbers = [1, 2, 3];
+
+numbers.map(function (i) { return i * i });
+numbers.map(i => i * i);
+[for (i of numbers) i * i];
+// all are [1, 4, 9]
+
+numbers.filter(function (i) { return i < 3 });
+numbers.filter(i => i < 3);
+[for (i of numbers) if (i < 3) i];
+// all are [1, 2]
+
+ +

2개의 배열

+ +

2개의 배열과 2개의 for-of 반복문을 살펴본다.

+ +
var numbers = [1, 2, 3];
+var letters = ['a', 'b', 'c'];
+
+var cross = [for (i of numbers) for (j of letters) i + j];
+// ["1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c"]
+
+var grid = [for (i of numbers) [for (j of letters) i + j]];
+// [
+//  ["1a", "1b", "1c"],
+//  ["2a", "2b", "2c"],
+//  ["3a", "3b", "3c"]
+// ]
+
+[for (i of numbers) if (i > 1) for (j of letters) if(j > 'a') i + j]
+// ["2b", "2c", "3b", "3c"], the same as below:
+
+[for (i of numbers) for (j of letters) if (i > 1) if(j > 'a') i + j]
+// ["2b", "2c", "3b", "3c"]
+
+[for (i of numbers) if (i > 1) [for (j of letters) if(j > 'a') i + j]]
+// [["2b", "2c"], ["3b", "3c"]], not the same as below:
+
+[for (i of numbers) [for (j of letters) if (i > 1) if(j > 'a') i + j]]
+// [[], ["2b", "2c"], ["3b", "3c"]]
+
+ +

명세

+ +

ECMAScript 2015 초안에 있었지만 개정 27(2014년 8월)에서 삭제되었습니다. specification semantics에 대해서는 ES2015의 이전 버전을 참조하세요.

+ +

Browser compatibility

+ +

{{Compat("javascript.operators.array_comprehensions")}}

+ +

오래된 JS1.7/JS1.8 comprehensions과의 차이점들

+ +
Gecko에서 JS1.7 / JS1.8 comprehensions가 46 버전부터 제거되었습니다. ({{bug(1220564)}}).
+ +

이전에 사용된 문법입니다. (더 이상 사용되지 않음!):

+ +
[X for (Y in Z)]
+[X for each (Y in Z)]
+[X for (Y of Z)]
+
+ +

차이점:

+ + + +

버그 업데이트에 대한 제안은 Bug 1220564, comment 42를 참조하세요.

+ +

더보기

+ + diff --git "a/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" "b/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" new file mode 100644 index 0000000000..7a82346d09 --- /dev/null +++ "b/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" @@ -0,0 +1,462 @@ +--- +title: 연산자 우선순위 +slug: Web/JavaScript/Reference/Operators/연산자_우선순위 +tags: + - JavaScript + - Operator + - 연산자 + - 우선순위 +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

연산자 우선순위는 연산자를 실행하는 순서를 결정합니다. 우선순위가 높은 연산자가 먼저 실행됩니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

우선순위와 결합성

+ +

아래와 같이 표현할 수 있는 표현식을 생각해 봅시다. 연산자1과 연산자2의 자리에는 아무 연산자를 넣을 수 있습니다.

+ +
a 연산자1 b 연산자2 c
+ +

두 연산자의 우선순위(아래 표 참조)가 다를 경우, 우선순위가 높은 연산자가 먼저 실행되고 결합성은 영향을 미치지 않습니다. 아래 예제에서는 덧셈이 곱셈보다 먼저 쓰였음에도 곱셈의 우선순위가 높기 때문에 먼저 실행됩니다.

+ +
console.log(3 + 10 * 2);   // 23을 출력
+console.log(3 + (10 * 2)); // 23을 출력, 괄호는 불필요함
+console.log((3 + 10) * 2); // 26을 출력, 괄호로 인해 실행 순서가 바뀜
+
+ +

좌결합성(왼쪽에서 오른쪽으로)은 표현식이 (a 연산자1 b) 연산자2 c와 같이, 우결합성(오른쪽에서 왼쪽으로)은 a 연산자1 (b 연산자2 c)와 같이 계산된다는 의미입니다. 대입 연산자는 우결합성이므로 다음과 같은 코드를 작성할 수 있습니다.

+ +
a = b = 5; // a = (b = 5);와 같음
+
+ +

이때 대입 연산자는 대입된 값을 반환하므로 ab의 값이 5가 됨을 예상할 수 있습니다. 우선 b의 값이 5로 설정되고, 그 다음에는 a의 값이 우변인 b = 5의 반환값 5로 설정됩니다.

+ +

다른 예시로, 좌결합성인 다른 산술 연산자와 달리 거듭제곱 연산자 (**)만은 우결합성입니다. 흥미로운 점으로 표현식의 평가는 결합성과 무관하게 항상 왼쪽에서 오른쪽으로 진행됩니다.

+ + + + + + + + + + + + + + + + +
코드출력
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 나눗셈 연산자 (/)에 주목
+console.log(echo("첫째", 6) / echo("둘째", 2));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+3
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 거듭제곱 연산자 (**)에 주목
+console.log(echo("첫째", 2) ** echo("둘째", 3));
+
+
+첫째 항 평가함
+둘째 항 평가함
+8
+
+ +

여러 연산자의 우선순위가 같을 때는 결합성을 고려합니다. 위에서와 같이 연산자가 하나이거나 연산자끼리 우선순위가 다를 경우에는 결합성이 결과에 영향을 미치지 않습니다. 아래의 예제에서 같은 종류의 연산자를 여러 번 사용했을 때 결합성이 결과에 영향을 미치는 것을 확인할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + +
코드출력
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 나눗셈 연산자 (/)에 주목
+console.log(echo("첫째", 6) / echo("둘째", 2) / echo("셋째", 3));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+1
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 거듭제곱 연산자 (**)에 주목
+console.log(echo("첫째", 2) ** echo("둘째", 3) ** echo("셋째", 2));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+512
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 첫 번째 거듭제곱 연산자 주변의 괄호에 주목
+console.log((echo("첫째", 2) ** echo("둘째", 3)) ** echo("셋째", 2));
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+64
+
+ +

위의 예제에서 나눗셈은 좌결합성이므로 6 / 3 / 2(6 / 3) / 2와 같습니다. 한편 거듭제곱은 우결합성이므로 2 ** 3 ** 22 ** (3 ** 2)와 같습니다. 그러므로 (2 ** 3) ** 2는 괄호로 인해 실행 순서가 바뀌기 때문에 위 표와 같이 64로 평가됩니다.

+ +

우선순위는 결합성보다 항상 우선하므로, 거듭제곱과 나눗셈을 같이 사용하면 나눗셈보다 거듭제곱이 먼저 계산됩니다. 예를 들어 2 ** 3 / 3 ** 2는 (2 ** 3) / (3 ** 2)와 같으므로 0.8888888888888888로 계산됩니다.

+ +

예제

+ +
3 > 2 && 2 > 1
+// true를 반환
+
+3 > 2 > 1
+// 3 > 2는 true인데, 부등호 연산자에서 true는 1로 변환되므로
+// true > 1은 1 > 1이 되고, 이는 거짓이다.
+// 괄호를 추가하면 (3 > 2) > 1과 같다.
+ +

+ +

다음 표는 우선순위 내림차순(21부터 1까지)으로 정렬되어 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
우선순위연산자 유형결합성연산자
21{{jsxref("Operators/Grouping", "그룹", "", 1)}}없음( … )
20{{jsxref("Operators/Property_Accessors", "멤버 접근", "#점_표기법", 1)}}좌결합성… . …
{{jsxref("Operators/Property_Accessors", "계산된 멤버 접근","#괄호_표기법", "1")}}좌결합성… [ … ]
{{jsxref("Operators/new","new")}} (매개변수 리스트 존재)없음new … ( … )
+

함수 호출

+
좌결합성… ( )
Optional chaining좌결합성?.
19{{jsxref("Operators/new","new")}} (매개변수 리스트 생략)우결합성new …
18{{jsxref("Operators/Arithmetic_Operators","후위 증가","#Increment", 1)}}없음… ++
{{jsxref("Operators/Arithmetic_Operators","후위 감소","#Decrement", 1)}}… --
17논리 NOT우결합성! …
비트 NOT~ …
단항 양부호+ …
단항 부정- …
전위 증가++ …
전위 감소-- …
{{jsxref("Operators/typeof", "typeof")}}typeof …
{{jsxref("Operators/void", "void")}}void …
{{jsxref("Operators/delete", "delete")}}delete …
{{jsxref("Operators/await", "await")}}await …
16거듭제곱우결합성… ** …
15곱셈좌결합성… * …
나눗셈… / …
나머지… % …
14덧셈좌결합성… + …
뺄셈… - …
13비트 왼쪽 시프트좌결합성… << …
비트 오른쪽 시프트… >> …
비트 부호 없는 오른쪽 시프트… >>> …
12미만좌결합성… < …
이하… <= …
초과… > …
이상… >= …
{{jsxref("Operators/in", "in")}}… in …
{{jsxref("Operators/instanceof", "instanceof")}}… instanceof …
11동등좌결합성… == …
부등… != …
일치… === …
불일치… !== …
10비트 AND좌결합성… & …
9비트 XOR좌결합성… ^ …
8비트 OR좌결합성… | …
7널 병합 연산자좌결합성… ?? …
6논리 AND좌결합성… && …
5논리 OR좌결합성… || …
4조건우결합성… ? … : …
3할당우결합성… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}우결합성yield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1쉼표 / 시퀀스좌결합성… , …
-- cgit v1.2.3-54-g00ecf