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/statements/async_function/index.html | 243 ++++++++++++++++ .../reference/statements/block/index.html | 132 +++++++++ .../reference/statements/break/index.html | 119 ++++++++ .../reference/statements/class/index.html | 119 ++++++++ .../reference/statements/const/index.html | 136 +++++++++ .../reference/statements/continue/index.html | 164 +++++++++++ .../reference/statements/debugger/index.html | 79 ++++++ .../reference/statements/default/index.html | 121 ++++++++ .../reference/statements/do...while/index.html | 78 ++++++ .../reference/statements/empty/index.html | 102 +++++++ .../reference/statements/export/index.html | 199 ++++++++++++++ .../reference/statements/for-await...of/index.html | 144 ++++++++++ .../reference/statements/for...in/index.html | 176 ++++++++++++ .../reference/statements/for...of/index.html | 228 +++++++++++++++ .../javascript/reference/statements/for/index.html | 160 +++++++++++ .../reference/statements/for_each...in/index.html | 85 ++++++ .../reference/statements/function/index.html | 177 ++++++++++++ .../reference/statements/function_star_/index.html | 159 +++++++++++ .../reference/statements/if...else/index.html | 177 ++++++++++++ .../reference/statements/import/index.html | 156 +++++++++++ .../web/javascript/reference/statements/index.html | 143 ++++++++++ .../reference/statements/label/index.html | 241 ++++++++++++++++ .../javascript/reference/statements/let/index.html | 246 +++++++++++++++++ .../reference/statements/return/index.html | 159 +++++++++++ .../reference/statements/switch/index.html | 306 +++++++++++++++++++++ .../reference/statements/throw/index.html | 198 +++++++++++++ .../reference/statements/try...catch/index.html | 273 ++++++++++++++++++ .../javascript/reference/statements/var/index.html | 195 +++++++++++++ .../reference/statements/while/index.html | 142 ++++++++++ .../reference/statements/with/index.html | 127 +++++++++ 30 files changed, 4984 insertions(+) create mode 100644 files/ko/web/javascript/reference/statements/async_function/index.html create mode 100644 files/ko/web/javascript/reference/statements/block/index.html create mode 100644 files/ko/web/javascript/reference/statements/break/index.html create mode 100644 files/ko/web/javascript/reference/statements/class/index.html create mode 100644 files/ko/web/javascript/reference/statements/const/index.html create mode 100644 files/ko/web/javascript/reference/statements/continue/index.html create mode 100644 files/ko/web/javascript/reference/statements/debugger/index.html create mode 100644 files/ko/web/javascript/reference/statements/default/index.html create mode 100644 files/ko/web/javascript/reference/statements/do...while/index.html create mode 100644 files/ko/web/javascript/reference/statements/empty/index.html create mode 100644 files/ko/web/javascript/reference/statements/export/index.html create mode 100644 files/ko/web/javascript/reference/statements/for-await...of/index.html create mode 100644 files/ko/web/javascript/reference/statements/for...in/index.html create mode 100644 files/ko/web/javascript/reference/statements/for...of/index.html create mode 100644 files/ko/web/javascript/reference/statements/for/index.html create mode 100644 files/ko/web/javascript/reference/statements/for_each...in/index.html create mode 100644 files/ko/web/javascript/reference/statements/function/index.html create mode 100644 files/ko/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/ko/web/javascript/reference/statements/if...else/index.html create mode 100644 files/ko/web/javascript/reference/statements/import/index.html create mode 100644 files/ko/web/javascript/reference/statements/index.html create mode 100644 files/ko/web/javascript/reference/statements/label/index.html create mode 100644 files/ko/web/javascript/reference/statements/let/index.html create mode 100644 files/ko/web/javascript/reference/statements/return/index.html create mode 100644 files/ko/web/javascript/reference/statements/switch/index.html create mode 100644 files/ko/web/javascript/reference/statements/throw/index.html create mode 100644 files/ko/web/javascript/reference/statements/try...catch/index.html create mode 100644 files/ko/web/javascript/reference/statements/var/index.html create mode 100644 files/ko/web/javascript/reference/statements/while/index.html create mode 100644 files/ko/web/javascript/reference/statements/with/index.html (limited to 'files/ko/web/javascript/reference/statements') diff --git a/files/ko/web/javascript/reference/statements/async_function/index.html b/files/ko/web/javascript/reference/statements/async_function/index.html new file mode 100644 index 0000000000..5a986c8af4 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/async_function/index.html @@ -0,0 +1,243 @@ +--- +title: async function +slug: Web/JavaScript/Reference/Statements/async_function +tags: + - Example + - JavaScript + - Promise + - async + - await +translation_of: Web/JavaScript/Reference/Statements/async_function +--- +
{{jsSidebar("Statements")}}
+ +

async function 선언은 {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 {{jsxref("Promise")}}를 사용하여 결과를 반환합니다. 그러나 비동기 함수를 사용하는 코드의 구문과 구조는, 표준 동기 함수를 사용하는것과 많이 비슷합니다.

+ +
+

또한 {{jsxref("Operators/async_function", "async function expression", "", 1)}}을 사용해서 async function을 선언할 수 있습니다.

+
+ +
{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}
+ + + +

Syntax

+ +
async function name([param[, param[, ... param]]]) {
+    statements
+}
+
+ +

매개변수

+ +
+
name
+
함수의 이름.
+
+ +
+
param
+
함수에게 전달되기 위한 인자의 이름.
+
+ +
+
statements
+
함수본문을 구성하는 내용.
+
+

반환 값

+ +

Promise : async 함수에 의해 반환 된 값으로 해결되거나 async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값.

+
+
+ +

Description

+ +

async 함수에는 {{jsxref ( "Operators / await", "await")}}식이 포함될 수 있습니다. 이 식은 async 함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 다음 async 함수의 실행을 다시 시작하고 완료후 값을 반환합니다.

+ +
+

await 키워드는 async 함수에서만 유효하다는 것을 기억하십시오. async 함수의 본문 외부에서 사용하면 SyntaxError가 발생합니다.

+
+ +
+

async/await함수의 목적은 사용하는 여러 promise의 동작을 동기스럽게 사용할 수 있게 하고, 어떠한 동작을 여러 promise의 그룹에서 간단하게 동작하게 하는 것이다.
+ promise가 구조화된 callback과 유사한 것 처럼 async/await또한 제네레이터(generator)와 프로미스(promise)를 묶는것과 유사하다.

+
+ +

async 함수는 항상 promise를 반환합니다. 만약 async 함수의 반환값이 명시적으로 promise가 아니라면 암묵적으로 promise로 감싸집니다.

+ +

예를 들어

+ +
async function foo() {
+    return 1
+}
+ +

위 코드는 아래와 같습니다.

+ +
function foo() {
+    return Promise.resolve(1)
+}
+ +

async 함수의 본문은 0개 이상의 await 문으로 분할된 것으로 생각할 수 있습니다. 첫번째 await 문을 포함하는 최상위 코드는 동기적으로 실행됩니다. 따라서 await 문이 없는 async 함수는 동기적으로 실행됩니다. 하지만 await 문이 있다면 async 함수는 항상 비동기적으로 완료됩니다.

+ +

예를 들어

+ +
async function foo() {
+    await 1
+}
+ +

위 코드는 아래와 같습니다.

+ +
function foo() {
+    return Promise.resolve(1).then(() => undefined)
+}
+
+ +

Examples

+ +

Simple example

+ +
var resolveAfter2Seconds = function() {
+  console.log("starting slow promise");
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve(20);
+      console.log("slow promise is done");
+    }, 2000);
+  });
+};
+
+var resolveAfter1Second = function() {
+  console.log("starting fast promise");
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve(10);
+      console.log("fast promise is done");
+    }, 1000);
+  });
+};
+
+var sequentialStart = async function() {
+  console.log('==SEQUENTIAL START==');
+
+  // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
+  const slow = await resolveAfter2Seconds();
+  console.log(slow);
+
+  const fast = await resolveAfter1Second();
+  console.log(fast);
+}
+
+var concurrentStart = async function() {
+  console.log('==CONCURRENT START with await==');
+  const slow = resolveAfter2Seconds(); // starts timer immediately
+  const fast = resolveAfter1Second();
+
+  console.log(await slow);
+  console.log(await fast); // waits for slow to finish, even though fast is already done!
+}
+
+var stillConcurrent = function() {
+  console.log('==CONCURRENT START with Promise.all==');
+  Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
+    console.log(messages[0]); // slow
+    console.log(messages[1]); // fast
+  });
+}
+
+var parallel = function() {
+  console.log('==PARALLEL with Promise.then==');
+  resolveAfter2Seconds().then((message)=>console.log(message));
+  resolveAfter1Second().then((message)=>console.log(message));
+}
+
+sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
+// wait above to finish
+setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
+// wait again
+setTimeout(stillConcurrent, 7000); // same as concurrentStart
+// wait again
+setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"
+ +
+

await 와 Promise#then을 혼동하지 마세요

+ +

sequentialStart 에서, 첫 번째 await는 2초의 대기 시간을 갖고,  다시 두 번째 await에서 1초의 대기 시간을 갖습니다. 두 번째 타이머는 첫 번째 타이머가 완료될 때 까지 생성되지 않습니다.

+ +

concurrentStart 에서, 두 타이머 모두 생성 된 다음 await 합니다. 타이머가 동시에 실행되고 있지만, await 호출은 여전히 연속적 실행중이므로, 두 번째 await 는 첫 번째 호출이 끝날 때 까지 대기합니다. 이렇게하면 3초가 아니라, 가장 느린 타이머에 필요한 2초가 필요합니다. stillConcurrent 에서도 Promise.all 을 사용하여 같은 일이 발생합니다.

+ +

두 개 이상의 프러미스를 동시에 wait 하고 싶다면, Promise#then을 사용하여 예제와 같이 parallel 를 수행할 수 있습니다.

+
+ +

async함수를 사용한 promise chain 재작성

+ +

{{jsxref("Promise")}} 를 반환하는 API는 promise chain을 만들며 여러 파트의 함수로 나뉜다.
+ 아래 코드를 보자.

+ +
function getProcessedData(url) {
+  return downloadData(url) // returns a promise
+    .catch(e => {
+      return downloadFallbackData(url) // returns a promise
+    })
+    .then(v => {
+      return processDataInWorker(v); // returns a promise
+    });
+}
+
+ +

위의 코드는 하나의 async함수로 아래와 같이 쓰여질 수도 있다.

+ +
async function getProcessedData(url) {
+  let v;
+  try {
+    v = await downloadData(url);
+  } catch (e) {
+    v = await downloadFallbackData(url);
+  }
+  return processDataInWorker(v);
+}
+
+ +

위 예제에서는 return 구문에 await 구문이 없다는 것에 주목하자. 이는 async function의 반환값이 암묵적으로 {{jsxref("Promise.resolve")}}로 감싸지기 때문이다.

+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("javascript.statements.async_function")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/block/index.html b/files/ko/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..aab5d0dc3f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/block/index.html @@ -0,0 +1,132 @@ +--- +title: block +slug: Web/JavaScript/Reference/Statements/block +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/block +--- +
{{jsSidebar("Statements")}}
+ +

블록문(또는 다른 언어에서는 복합문)은 0개 이상의 구문을 묶을 때 사용합니다. 블록은 한 쌍의 중괄호로 구성하며 선택적으로 {{jsxref("Statements/label", "이름", "", 0)}}을 붙일 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-block.html")}}
+ + + +

구문

+ +

블록문

+ +
{
+  StatementList
+}
+ +

유명 블록문

+ +
LabelIdentifier: {
+  StatementList
+}
+
+ +
+
StatementList
+
블록문 내의 문.
+
LabelIdentifier
+
시각적인 구분, 또는 {{jsxref("Statements/break", "break")}}문의 대상으로 쓸 {{jsxref("Statements/label", "label")}}.
+
+ +

설명

+ +

다른 언어에서 블록문은 복합문이라고 부르기도 합니다. 블록문을 쓰면 JavaScript가 하나의 문을 기대하는 곳에서 다수의 문을 실행할 수 있습니다. JavaScript에서 이렇게 문을 묶는건 흔히 쓰이는 기법입니다. 반대 개념으로는 {{jsxref("Statements/empty", "공백문", "", 0)}}이 있으며, 이는 하나의 문을 기대하는 곳에 아무것도 제공하지 않는 것입니다.

+ +

블록 범위 규칙

+ +

var 사용 시

+ +

{{jsxref("Statements/var", "var")}}로 선언한 변수는 블록 범위를 가지지 않습니다. 블록 내에서 선언한 변수의 범위는 함수나 스크립트가 되어, 값 할당의 영향이 블록 바깥까지 미칩니다. 다른 말로는 블록문이 범위를 만들지 않습니다. "독립" 블록문도 유효한 구문이긴 하지만, C와 Java의 블록에 기대하는걸 JavaScript에서도 기대하면 안됩니다. 예를 들어보겠습니다.

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // 2 기록
+ +

콘솔 출력 결과는 2입니다. 블록 밖의 var x와 블록 안의 var x는 같은 범위에 속하기 때문입니다. C나 Java에서 같은 코드를 작성한다면 1을 출력할 것입니다.

+ +

letconst 사용 시

+ +

반면 {{jsxref("Statements/let", "let")}}과 {{jsxref("Statements/const", "const")}}로 선언한 식별자는 블록 범위를 가집니다.

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // 1 기록
+
+ +

x = 2는 선언한 블록으로 범위가 제한됩니다.

+ +

const도 마찬가지입니다.

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // 1 기록, SyntaxError 없음
+ +

블록 내의 const c = 2SyntaxError: Identifier 'c' has already been declared를 던지지 않는 점에 주목하세요. 블록 범위 안이라 별개의 식별자이기 때문입니다.

+ +

ES2015의 엄격 모드부터, 블록 내의 함수는 해당 블록으로 범위가 제한됩니다. ES2015 이전의 엄격 모드에서는 블록 레벨 함수를 사용할 수 없었습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-block', 'Block statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.1', 'Block statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.1', 'Block statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.1', 'Block statement')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.block")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/break/index.html b/files/ko/web/javascript/reference/statements/break/index.html new file mode 100644 index 0000000000..fdbb79e719 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/break/index.html @@ -0,0 +1,119 @@ +--- +title: break +slug: Web/JavaScript/Reference/Statements/break +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/break +--- +
{{jsSidebar("Statements")}}
+ +

break은 현재 반복문, {{jsxref("Statements/switch", "switch")}} 문, 또는 {{jsxref("Statements/label", "label")}} 문을 종료하고, 그 다음 문으로 프로그램 제어를 넘깁니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-break.html")}}
+ + + +

구문

+ +
break [label];
+ +
+
label {{optional_inline}}
+
문의 라벨에 연결한 {{glossary("identifier", "식별자")}}. 반복문이나 {{jsxref("Statements/switch", "switch")}}에서 사용하는게 아니면 필수로 제공해야 합니다.
+
+ +

설명

+ +

break 문은 프로그램이 label 달린 문에서 빠져나오게 하는 선택사항 label을 포함합니다. break 문은 참조되는 label 내에 중첩되어야 합니다. label 달린 문은 어떤 {{jsxref("Statements/block", "block")}} 문이든 될 수 있습니다. 꼭, loop 문을 달 필요가 없습니다.

+ +

예제

+ +

다음 함수는 i가 3일 때 {{jsxref("Statements/while", "while")}} loop를 종료하는 break 문이 있고, 그러고는 3 * x값을 반환합니다.

+ +
function testBreak(x) {
+  var i = 0;
+
+  while (i < 6) {
+    if (i == 3) {
+      break;
+    }
+    i += 1;
+  }
+
+  return i * x;
+}
+ +

다음 코드는 label 달린 블록이 있는 break 문을 사용합니다. break 문은 자신이 참조하는 label 내에 중첩되어야 합니다. inner_blockouter_block내에 중첩되어야 함을 주의하세요.

+ +
outer_block: {
+  inner_block: {
+    console.log('1');
+    break outer_block; // inner_block과 outer_block 둘다 빠져나옴
+    console.log(':-('); // 건너뜀
+  }
+  console.log('2'); // 건너뜀
+}
+
+ +

다음 코드는 또한 label 달린 블록이 있는 break 문을 사용하지만 그 break 문이 block_2를 참조하지만 block_1 내에 있기에 구문 오류(Syntax Error)가 발생합니다. break 문은 항상 자신이 참조하는 label 내에 중첩되어야 합니다.

+ +
block_1: {
+  console.log('1');
+  break block_2; // SyntaxError: label을 찾을 수 없음
+}
+
+block_2: {
+  console.log('2');
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Unlabeled version.
{{SpecName('ES3')}}{{Spec2('ES3')}}Labeled version added.
{{SpecName('ES5.1', '#sec-12.8', 'Break statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-break-statement', 'Break statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-break-statement', 'Break statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.break")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/class/index.html b/files/ko/web/javascript/reference/statements/class/index.html new file mode 100644 index 0000000000..bfb1c95027 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/class/index.html @@ -0,0 +1,119 @@ +--- +title: class +slug: Web/JavaScript/Reference/Statements/class +tags: + - Classes + - Declaration + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/class +--- +
{{jsSidebar("Statements")}}
+ +

class 선언은 프로토타입 기반 상속을 사용하여, 주어진 이름의 새로운 클래스를 만듭니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-class.html")}}
+ + + +
+

{{jsxref("Operators/class", "클래스 표현", "", 1)}}을 사용하여 클래스를 정의할 수도 있습니다. 표현식과 달리 선언문으로는 같은 클래스를 다시 선언하면 오류가 발생합니다.

+
+ +

구문

+ +
class name [extends] {
+  // class body
+}
+
+ +

설명

+ +

클래스 본문은 엄격 모드에서 실행됩니다. 생성자 속성은 선택 사항입니다..

+ +

클래스 선언은 {{jsxref("Statements/function", "함수 선언", "", 0)}}과 달리 {{Glossary("Hoisting", "호이스팅")}}의 대상이 아닙니다.

+ +

예제

+ +

간단한 클래스 선언

+ +

다음 예제는 우선 Polygon 클래스를 정의하고, Square라는 이름의 새로운 클래스가 Polygon을 상속합니다. 생성자 내부의 super()는 생성자 내에서만, 그리고 {{jsxref("Operators/this", "this")}} 키워드를 사용하기 전에만 쓸 수 있다는 점을 주의하세요.

+ +
class Polygon {
+  constructor(height, width) {
+    this.name = 'Polygon';
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(length) {
+    super(length, length);
+    this.name = 'Square';
+  }
+}
+ +
+

같은 클래스를 두 번 선언하려고 시도할 때

+ +

클래스 선언문으로 같은 클래스를 두 번 선언하면 오류가 발생합니다.

+ +
class Foo {};
+class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared
+
+ +

이전에 표현식으로 정의한 경우에도 오류가 발생합니다.

+ +
var Foo = class {};
+class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

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

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/statements/const/index.html b/files/ko/web/javascript/reference/statements/const/index.html new file mode 100644 index 0000000000..1cbd7ea7aa --- /dev/null +++ b/files/ko/web/javascript/reference/statements/const/index.html @@ -0,0 +1,136 @@ +--- +title: const +slug: Web/JavaScript/Reference/Statements/const +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement + - constants +translation_of: Web/JavaScript/Reference/Statements/const +--- +
{{jsSidebar("Statements")}}
+ +

const 선언은 블록 범위의 상수를 선언합니다. 상수의 값은 재할당할 수 없으며 다시 선언할 수도 없습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-const.html")}}
+ + + +

구문

+ +
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
+ +
+
nameN
+
상수의 이름. 아무 유효한 {{Glossary("identifier", "식별자")}}를 사용할 수 있습니다.
+
valueN
+
상수의 값. 아무 유효한 표현식이나 가능합니다.
+
+ +

설명

+ +

이 선언은 선언된 함수에 전역 또는 지역일 수 있는 상수를 만듭니다. 상수 초기자(initializer)가 필요합니다. 즉 선언되는 같은 문에 그 값을 지정해야 합니다(이는 나중에 변경될 수 없는 점을 감안하면 말이 됩니다).

+ +

상수는 let 문을 사용하여 정의된 변수와 마찬가지로 블록 범위(block-scope)입니다. 상수의 값은 재할당을 통해 바뀔 수 없고 재선언될 수 없습니다.

+ +

let에 적용한 "일시적 사각 지대"에 관한 모든 고려는, const에도 적용합니다.

+ +

상수는 같은 범위의 상수 또는 변수와 그 이름을 공유할 수 없습니다.

+ +

예제

+ +

다음 예제는 상수가 어떻게 동작하는지 보입니다. 브라우저 콘솔에서 따라해보세요.

+ +
// 주의: 상수 선언에는 대소문자 모두 사용할 수 있지만,
+// 일반적인 관습은 모두 대문자를 사용하는 것입니다.
+
+// MY_FAV를 상수로 정의하고 그 값을 7로 함
+const MY_FAV = 7;
+
+// 에러가 발생함
+MY_FAV = 20;
+
+// 7 출력
+console.log("my favorite number is: " + MY_FAV);
+
+// 상수를 재선언하려는 시도는 오류 발생 - Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
+const MY_FAV = 20;
+
+// MY_FAV라는 이름은 위에서 상수로 예약되어 있어서 역시 실패함.
+var MY_FAV = 20;
+
+// 역시 오류가 발생함
+let MY_FAV = 20;
+
+// 블록 범위의 특성을 아는게 중요
+if (MY_FAV === 7) {
+    // 블록 범위로 지정된 MY_FAV 라는 변수를 만드므로 괜찮습니다
+    // (let으로 const 변수가 아닌 블록 범위를 선언하는 것과 똑같이 동작합니다)
+    let MY_FAV = 20;
+
+    // MY_FAV는 이제 20입니다
+    console.log('my favorite number is ' + MY_FAV);
+
+    // 이 선언은 전역으로 호이스트되고 에러가 발생합니다.
+    var MY_FAV = 20;
+}
+
+// MY_FAV는 여전히 7
+console.log('my favorite number is ' + MY_FAV);
+
+// const 선언시에 초기값을 생략해서 오류 발생
+const FOO;
+
+// const는 오브젝트에도 잘 동작합니다
+const MY_OBJECT = {'key': 'value'};
+
+// 오브젝트를 덮어쓰면 오류가 발생합니다
+MY_OBJECT = {'OTHER_KEY': 'value'};
+
+// 하지만 오브젝트의 키는 보호되지 않습니다.
+// 그러므로 아래 문장은 문제없이 실행됩니다
+MY_OBJECT.key = 'otherValue'; // 오브젝트를 변경할 수 없게 하려면 Object.freeze() 를 사용해야 합니다
+
+// 배열에도 똑같이 적용됩니다
+const MY_ARRAY = [];
+// 배열에 아이템을 삽입하는 건 가능합니다
+MY_ARRAY.push('A'); // ["A"]
+// 하지만 변수에 새로운 배열을 배정하면 에러가 발생합니다
+MY_ARRAY = ['B']
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.const")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/continue/index.html b/files/ko/web/javascript/reference/statements/continue/index.html new file mode 100644 index 0000000000..f0d67deea2 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/continue/index.html @@ -0,0 +1,164 @@ +--- +title: continue +slug: Web/JavaScript/Reference/Statements/continue +translation_of: Web/JavaScript/Reference/Statements/continue +--- +
{{jsSidebar("Statements")}}
+ +

continue 문은 현재 또는 레이블이 지정된 루프의 현재 반복에서 명령문의 실행을 종료하고 반복문의 처음으로 돌아가여 루프문의 다음 코드를 실행합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-continue.html")}}
+ + + +

구문

+ +
continue [label];
+ +
+
label
+
+

명령문의 레이블과 연관된 식별자.

+
+
+ +

설명

+ +

{{jsxref ( "Statements / break", "break")}} 문과 달리 continue는 루프의 실행을 완전히 종료하지 않고 for, while문에서 다음과 같이 동작합니다.

+ + + + + +

continue 문에는 현재 루프 대신 레이블이 지정된 루프 문의 다음 반복으로 건너 뛰도록하는 선택적 레이블이 포함될 수 있습니다. 이 경우, continue 문은 이 레이블 된 명령문 내에 중첩되어야합니다.

+ +

예제

+ +

Using continue with while

+ +

다음 예제에서는 i의 값이 3일 때 실행되는 continue문을 포함하는 {{jsxref("Statements/while", "while")}}을 보여줍니다. 따라서 n은 1, 3, 7 및 12 값을 갖습니다.

+ +
var i = 0;
+var n = 0;
+
+while (i < 5) {
+  i++;
+
+  if (i === 3) {
+    continue;
+  }
+
+  n += i;
+}
+
+ +

label과 함께 continue 사용하기

+ +

다음 예제에서 checkiandj라는 문에는 checkj라는 문이 있습니다. continue가 발생하면 프로그램은 checkj 문의 맨 위에서 계속됩니다. continue가 발생할 때마다 checkj는 조건이 false를 반환 할 때까지 반복합니다. false가 리턴되면 나머지 checkiandj 문이 완료됩니다.

+ +

continuecheckiandj 레이블이 있으면이 프로그램은 checkiandj 문 맨 위에서 계속됩니다.

+ +

See also {{jsxref("Statements/label", "label")}}.

+ +
var i = 0;
+var j = 8;
+
+checkiandj: while (i < 4) {
+  console.log('i: ' + i);
+  i += 1;
+
+  checkj: while (j > 4) {
+    console.log('j: ' + j);
+    j -= 1;
+
+    if ((j % 2) == 0)
+      continue checkj;
+    console.log(j + ' is odd.');
+  }
+  console.log('i = ' + i);
+  console.log('j = ' + j);
+}
+
+ +

출력:

+ +
i: 0
+
+// start checkj
+j: 8
+7 is odd.
+j: 7
+j: 6
+5 is odd.
+j: 5
+// end checkj
+
+i = 1
+j = 4
+
+i: 1
+i = 2
+j = 4
+
+i: 2
+i = 3
+j = 4
+
+i: 3
+i = 4
+j = 4
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Unlabeled version.
{{SpecName('ES3')}}{{Spec2('ES3')}}Labeled version added.
{{SpecName('ES5.1', '#sec-12.7', 'Continue statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-continue-statement', 'Continue statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.continue")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/debugger/index.html b/files/ko/web/javascript/reference/statements/debugger/index.html new file mode 100644 index 0000000000..4f081282b9 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/debugger/index.html @@ -0,0 +1,79 @@ +--- +title: debugger +slug: Web/JavaScript/Reference/Statements/debugger +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/debugger +--- +
{{jsSidebar("Statements")}}
+ +

debugger은 중단점 설정 등 현재 사용할 수 있는 디버그 기능을 호출합니다. 사용할 수있는 디버깅 기능이 없으면 아무런 동작도 하지 않습니다.

+ +

구문

+ +
debugger;
+ +

예제

+ +

다음 예제에서는 함수가 호출 시 디버거를 활성화하도록 debugger를 삽입한 모습입니다.

+ +
function potentiallyBuggyCode() {
+    debugger;
+    // 버그가 있을 것으로 생각하는 코드를 분석하거나, 한 단계씩 진행해보거나...
+}
+ +

디버거가 활성화되면 디버거 문의 위치에서 실행이 일시중지됩니다. 스크립트 소스의 중단점과 비슷합니다.

+ +

Paused at a debugger statement.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-debugger-statement', 'Debugger statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-debugger-statement', 'Debugger statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.15', 'Debugger statement')}}{{Spec2('ES5.1')}}Initial definition
{{SpecName('ES3', '#sec-7.5.3', 'Debugger statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-7.4.3', 'Debugger statement')}}{{Spec2('ES1')}}Only mentioned as reserved word.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.debugger")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/default/index.html b/files/ko/web/javascript/reference/statements/default/index.html new file mode 100644 index 0000000000..d8d107e774 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/default/index.html @@ -0,0 +1,121 @@ +--- +title: default +slug: Web/JavaScript/Reference/Statements/default +tags: + - JavaScript + - Keyword + - Reference +translation_of: Web/JavaScript/Reference/Statements/switch +--- +
{{jsSidebar("Statements")}}
+ +

default 키워드는 {{jsxref("Statements/switch", "switch")}} 구문과 {{jsxref("Statements/export", "export")}} 구문에서 사용할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-default.html")}}
+ + + +

구문

+ +

{{jsxref("Statements/switch", "switch")}} 구문 내에서는 다음과 같이 사용합니다.

+ +
switch (expression) {
+  case value1:
+    //Statements executed when the result of expression matches value1
+    [break;]
+  default:
+    //Statements executed when none of the values match the value of the expression
+    [break;]
+}
+ +

{{jsxref("Statements/export", "export")}} 구문 내에서는 다음과 같이 사용합니다.

+ +
export default nameN 
+ +

설명

+ +

세부사항을 보려면,

+ + + +

예제

+ +

switch에서 default 사용

+ +

아래 예제에서 expr 이 "오렌지" 또는 "사과"일 때, 프로그램은 값을 "오렌지" 또는 "사과"와 일치시키고 해당 명령문을 실행합니다. 기본(default) 키워드는 다른 경우에 도움이 되며 연관된 명령문을 실행합니다.

+ +
switch (expr) {
+  case '오렌지':
+    console.log('오렌지는 1000원입니다.');
+    break;
+  case '사과':
+    console.log('사과는 500원입니다.');
+    break;
+  default:
+    console.log('죄송합니다. ' + expr + '의 재고가 다 떨어졌습니다.');
+}
+ +

export에서 default 사용

+ +

단일 값을 내보내거나 모듈의 기본 값이 필요한 경우, 기본 내보내기를 사용할 수 있습니다.

+ +
// module "my-module.js"
+let cube = function cube(x) {
+  return x * x * x;
+};
+export default cube;
+ +

다른 스크립트에서 가져오는 건 간단합니다.

+ +
// module "my-module.js"
+import cube from 'my-module';  //default export gave us the liberty to say import cube, instead of import cube from 'my-module'
+console.log(cube(3)); // 27
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}}
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}}
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.default")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/do...while/index.html b/files/ko/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..f6d2e00c57 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,78 @@ +--- +title: do...while +slug: Web/JavaScript/Reference/Statements/do...while +tags: + - 구문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +
{{jsSidebar("Statements")}}
+ +

do...while 문은 테스트 조건이 거짓으로 평가될 때까지 지정된 구문을 실행하는 루프를 만듭니다.
+ 단, 구문이 실행된 뒤에 테스트 조건이 평가됨으로 구문은 무조건 한 번은 실행됩니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
+ + + +

문법

+ +
do구문
+while (조건식);
+
+ +
+
구문
+
테스트 조건이 참일 때마다 한 번이상 실행되는 구문입니다. 만약 루프 내에서 여러 구문을 반복 실행 시키고 싶으시다면, 다음 명령을 사용합니다.
+
{{jsxref("Statements/block", "block", "", 1)}} 구문을 활용하여 ({ ... }) 이런 식으로 그룹화합니다.
+
+ +
+
조건식
+
루프가 실행될 때마다 평가되는 식입니다. 만약 조건식이 참으로 평가되었다면, 구문 이 다시 실행됩니다. 만약 조건식이 거짓으로 평가되었다면, 자바스크립트는 do...while. 구문 밑에 있는 구문들을 실행시킵니다.
+
+ +

예제

+ +

do...while

+ +

예제에서 do...while 문은 적어도 한번 반복되고 i 변수가 5 보다 작을 때까지 실행됩니다.

+ +
var result = '';
+var i = 0;
+do {
+   i += 1;
+   result += i + ' ';
+}
+while (i > 0 && i < 5);
+// Despite i == 0 this will still loop as it starts off without the test
+
+console.log(result);
+ +

자세한 내용

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.do_while")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/empty/index.html b/files/ko/web/javascript/reference/statements/empty/index.html new file mode 100644 index 0000000000..c986c6232a --- /dev/null +++ b/files/ko/web/javascript/reference/statements/empty/index.html @@ -0,0 +1,102 @@ +--- +title: empty +slug: Web/JavaScript/Reference/Statements/Empty +translation_of: Web/JavaScript/Reference/Statements/Empty +--- +
{{jsSidebar("Statements")}}
+ +

empty 문은 JavaScript 아무것도 동작하지 않습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-empty.html")}}
+ + + +

구문

+ +
;
+
+ +

설명

+ +

empty statement은 JavaScript구문에 하나가 필요할 때 어떤 문도 실행되지 않을 것이라는 것을 나타내는 세미 콜론(;)입니다. 여러개의 문장을 원하지만 JavaScript는 block statement을 사용하여 하나만 허용하며 여러개의 문장을 하나로 결합합니다.

+ +

예제

+ +

빈 문은 루프 문과 함께 사용되기도합니다. 빈 루프 본문이있는 다음 예제를 참조하십시오.

+ +
var arr = [1, 2, 3];
+
+// Assign all array values to 0
+for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
+
+console.log(arr)
+// [0, 0, 0]
+
+ +

참고: 정상적인 세미 콜론을 구분하는 것이 그리 쉽지 않기 때문에, empty statement를 사용할 때는 의도적으로 주석을 달아주는것이 좋습니다. 다음 예 에서는 의도한대로 코드가 동작하지 않을것입니다. 아마도 killTheUniverse()를 if문 안에서 실행하고자 했던것 같습니다.

+ +
if (condition);       // Caution, this "if" does nothing!
+   killTheUniverse()  // So this always gets executed!!!
+
+ +

다른 예 : 중괄호 ({})가없는 if...else 문에서 three가 true이면 아무 일도 일어나지 않고 four를 건너 뛰고 else case의 launchRocket() 함수도 실행되지 않습니다.

+ +
if (one)
+  doOne();
+else if (two)
+  doTwo();
+else if (three)
+  ; // nothing here
+else if (four)
+  doFour();
+else
+  launchRocket();
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.empty")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/export/index.html b/files/ko/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..1c15d4e7f9 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/export/index.html @@ -0,0 +1,199 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +tags: + - ECMAScript 2015 + - JavaScript + - Modules + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/export +--- +
{{jsSidebar("Statements")}}
+ +

export 문은 JavaScript 모듈에서 함수, 객체, 원시 값을 내보낼 때 사용합니다. 내보낸 값은 다른 프로그램에서 {{jsxref("Statements/import", "import")}} 문으로 가져가 사용할 수 있습니다.

+ +

내보내는 모듈은 "use strict"의 존재 유무와 상관없이 무조건 엄격 모드입니다. export 문은 HTML 안에 작성한 스크립트에서는 사용할 수 없습니다.

+ +

구문

+ +
// 하나씩 내보내기
+export let name1, name2, …, nameN; // var, const도 동일
+export let name1 = …, name2 = …, …, nameN; // var, const도 동일
+export function functionName(){...}
+export class ClassName {...}
+
+// 목록으로 내보내기
+export { name1, name2, …, nameN };
+
+// 내보내면서 이름 바꾸기
+export { variable1 as name1, variable2 as name2, …, nameN };
+
+// 비구조화로 내보내기
+export const { name1, name2: bar } = o;
+
+// 기본 내보내기
+export default expression;
+export default function (…) { … } // also class, function*
+export default function name1(…) { … } // also class, function*
+export { name1 as default, … };
+
+// 모듈 조합
+export * from …; // does not set the default export
+export * as name1 from …;
+export { name1, name2, …, nameN } from …;
+export { import1 as name1, import2 as name2, …, nameN } from …;
+export { default } from …;
+ +
+
nameN
+
내보낼 식별자 이름. {{jsxref("Statements/import", "import")}}를 사용해 다른 스크립트에서 가져갈 수 있습니다.
+
+ +

설명

+ +

내보내기에는 두 종류, 유명(named)과 기본(default) 내보내기가 있습니다. 모듈 하나에서, 유명 내보내기는 여러 개 존재할 수 있지만 기본 내보내기는 하나만 가능합니다. 각 종류는 위의 구문 중 하나와 대응합니다.

+ + + +

유명 내보내기는 여러 값을 내보낼 때 유용합니다. 가져갈 때는 내보낸 이름과 동일한 이름을 사용해야 합니다.

+ +

반면 기본 내보내기는 어떤 이름으로도 가져올 수 있습니다.

+ +
// test.js
+let k; export default k = 12;
+ +
// 임의의 다른 파일
+import m from './test'; // k가 기본 내보내기이므로, 가져오는 이름으로 k 대신 m을 사용해도 문제 없음
+console.log(m);         // 12 기록
+ +

식별자 충돌을 피하기 위해 유명 내보내기 중 이름을 바꿔줄 수도 있습니다.

+ +
export { myFunction as function1,
+         myVariable as variable };
+ +

다시 내보내기 / 조합

+ +

부모 모듈이 자식 모듈을 가져와서 다시 내보낼 수도 있습니다. 즉, 여러 개의 모듈을 모아놓을 하나의 모듈을 만들 수 있습니다.

+ +
export foo from 'bar.js';
+
+ +

위 구문은 아래와 동일합니다.

+ +
import foo from 'bar.js';
+export foo;
+
+ +

예제

+ +

유명 내보내기 사용

+ +

어떤 모듈에서 다음과 같은 코드를 가진다고 해보겠습니다.

+ +
// module "my-module.js"
+function cube(x) {
+  return x * x * x;
+}
+const foo = Math.PI + Math.SQRT2;
+var graph = {
+    options: {
+        color:'white',
+        thickness:'2px'
+    },
+    draw: function() {
+        console.log('From graph draw function');
+    }
+}
+export { cube, foo, graph };
+ +

다른 스크립트에서는 아래와 같이 사용할 수 있습니다.

+ +
// You should use this script in html with the type module.
+// For example:
+//   <script type="module" src="./demo.js"></script>
+//
+// Open the page in a http server, otherwise there will be a CORS policy error.
+//
+// script demo.js
+
+import { cube, foo, graph } from 'my-module';
+graph.options = {
+    color:'blue',
+    thickness:'3px'
+};
+graph.draw();
+console.log(cube(3)); // 27
+console.log(foo);    // 4.555806215962888
+ +

기본 내보내기 사용

+ +

단일 값을 내보낼 때나 모듈의 폴백fallback 값이 필요할 땐 기본 내보내기를 사용할 수 있습니다.

+ +
// module "my-module.js"
+export default function cube(x) {
+  return x * x * x;
+}
+ +

그런 다음, 다른 스크립트에서 가져오는건 간단합니다:

+ +
import cube from './my-module.js';
+console.log(cube(3)); // 27
+ +

export default를 사용할 때 var, let, const는 사용하지 못합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}Initial definition.
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.export")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/for-await...of/index.html b/files/ko/web/javascript/reference/statements/for-await...of/index.html new file mode 100644 index 0000000000..c52d226e27 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for-await...of/index.html @@ -0,0 +1,144 @@ +--- +title: for await...of +slug: Web/JavaScript/Reference/Statements/for-await...of +tags: + - 구문 + - 반복문 + - 비동기 + - 식 + - 열거 + - 열거자 +translation_of: Web/JavaScript/Reference/Statements/for-await...of +--- +
{{jsSidebar("Statements")}}
+ +

for await...of 구문은 보통 비동기에 대응하는 열거자를 나열할 때 쓰이지만, {{jsxref("String")}}, {{jsxref("Array")}}, Array 같은 객체 (e.g., {{jsxref("Functions/arguments", "arguments")}} or NodeList), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}} 같은 동기적으로 열거 가능한 객체 또한 가능하며, 사용자가 직접 정의한 동기 또는 비동기 객체도 나열할 수 있도록 해준다. 일반적인 for ...of 문과 마찬가지로 열거자 심볼이 정의한 속성을 실행하게 되어 열거한 값을 변수로 받아 처리한다.

+ + + +

구문

+ +
for await (variable of iterable) {
+  statement
+}
+
+ +
+
variable
+
열거할 때마다 variable. 문을 통해 변수로 받을 수 있다. variable 문 안에서는 const, let 및 var. 문으로 선언된 변수 및 상수를 선언할 수 있다.
+
iterable
+
열거 가능한 속성이 들어가 있는 객체 및 식을 포함한다.
+
+ +

비동기 열거 속성을 통한 열거 식

+ +

비동기 열거 프로토콜을 담은 객체를 아래와 같이 열거할 수 있다.

+ +
const asyncIterable = {
+  [Symbol.asyncIterator]() {
+    return {
+      i: 0,
+      next() {
+        if (this.i < 3) {
+          return Promise.resolve({ value: this.i++, done: false });
+        }
+
+        return Promise.resolve({ done: true });
+      }
+    };
+  }
+};
+
+(async function() {
+   for await (let num of asyncIterable) {
+     console.log(num);
+   }
+})();
+
+// 0
+// 1
+// 2
+
+ +

비동기 생성자를 통한 열거 식

+ +

비동기 생성자는 애초부터 비동기 열거 프로토콜을 탑재한 채로 정의한다.이를 for await...of 식으로 아래와 같이 사용할 수 있다.

+ +
async function* asyncGenerator() {
+  let i = 0;
+  while (i < 3) {
+    yield i++;
+  }
+}
+
+(async function() {
+  for await (let num of asyncGenerator()) {
+    console.log(num);
+  }
+})();
+// 0
+// 1
+// 2
+ +

좀 더 상세한 비동기 생성자를 통한 for await...of 식의 사용법을 위해 기본 API를 통해 값을 비동기적으로 열거하는 방법을 알아본다.

+ +

아래 예제를 통해 먼저 API를 사용하여 스트림 데이터를 통해 비동기 열거자를 만든 뒤, 스트림에서 응답이 끝나면 최종 응답 데이터 크기를 가져온다.

+ +
async function* streamAsyncIterator(stream) {
+  const reader = stream.getReader();
+  try {
+    while (true) {
+      const { done, value } = await reader.read();
+      if (done) {
+        return;
+      }
+      yield value;
+    }
+  } finally {
+    reader.releaseLock();
+  }
+}
+// 주소로부터 데이터를 받아온 뒤, 응답 크기를 구하는 비동기 생성자 함수.
+async function getResponseSize(url) {
+  const response = await fetch(url);
+  // 여기에 응답 크기를 바이트 단위로 적재한다.
+  let responseSize = 0;
+  // for-await-of 문을 통해 응답이 들어올 때마다 열거 프로토콜을 통해 반복문이 작동한다.
+  for await (const chunk of streamAsyncIterator(response.body)) {
+    // 총 응답 크기를 지속적으로 누적한다.
+    responseSize += chunk.length;
+  }
+
+  console.log(`응답 크기: ${responseSize} 바이트`);
+  // 예상 출력: "응답 크기: 1071472 바이트"
+  return responseSize;
+}
+getResponseSize('https://jsonplaceholder.typicode.com/photos');
+ +

규격

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'ECMAScript Language: The for-in, for-of, and for-await-of Statements')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.for_await_of")}}

+ +

같이보기

+ + diff --git a/files/ko/web/javascript/reference/statements/for...in/index.html b/files/ko/web/javascript/reference/statements/for...in/index.html new file mode 100644 index 0000000000..983e50c91f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for...in/index.html @@ -0,0 +1,176 @@ +--- +title: for...in +slug: Web/JavaScript/Reference/Statements/for...in +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...in +--- +
{{jsSidebar("Statements")}}
+ +

for...in문은 상속된 열거 가능한 속성들을 포함하여 객체에서 문자열로 키가 지정된 모든 열거 가능한 속성에 대해 반복합니다. (Symbol로 키가 지정된 속성은 무시합니다.)

+ +

{{EmbedInteractiveExample("pages/js/statement-forin.html")}}

+ +

문법

+ +
for (variable in object) { ... }
+ +

파라미터

+ +
+
variable
+
매번 반복마다 다른 속성이름(Value name)이 변수(variable)로 지정됩니다.
+
object
+
반복작업을 수행할 객체로 열거형 속성을 가지고 있는 객체.
+
+ +

설명

+ +

for...in문은 열거 가능한 non-Symbol 속성에 대해서만 반복합니다.
+ ArrayObject 등 내장 constructor를 통해 만들어진 객체는  {{jsxref("String")}}의 {{jsxref("String.indexOf", "indexOf()")}}, {{jsxref("Object")}}의 {{jsxref("Object.toString", "toString()")}}와 같이 Object.prototype, String.prototype 로부터 열거가 가능하지 않은 속성들을 상속해왔습니다. for...in문은 객체 자체의 모든 열거 가능한 속성들과 프로토타입 체인으로부터 상속받은 속성들에 대해 반복할 것입니다. (더 가까운 프로토타입의 속성들이 프로토타입 체인 객체로부터 더 멀리 떨어진 프로토 타입의 속성보다 더 우선합니다.)

+ +

속성의 삭제, 추가, 수정 

+ +

for..in 문은 임의의 순서로 객체의 속성들에 대해 반복합니다. (적어도 cross-browser 설정에서는 왜 표면적으로 보이는 반복의 순서를 따를 수 없는지에 대해서  {{jsxref("Operators/delete", "delete")}} 를 참고하십시오.)

+ +

만약 한 반복으로 속성이 수정된 후에 방문하는 경우, 반복문에서의 그 값은 나중의 값으로 정해집니다. 방문하기 전에 삭제된 속성에 대해서는 이후에 방문하지 않습니다. 반복이 발생하는 객체에 추가된 속성은 방문하거나 반복에서 생략할 수 있습니다.

+ +

일반적으로 현재 방문 중인 속성 외에는 반복하는 동안 객체의 속성을 추가, 수정, 제거하지 않는 것이 가장 좋습니다. 추가된 속성을 방문할 것인지, 수정된 속성(현재의 속성 제외)을 수정 이전 혹은 이후에 방문할 것인지, 삭제된 속성을 삭제 이전에 방문할 것인지에 대해서는 보장할 수 없습니다.

+ +

배열의 반복과 for...in

+ +
+

Note: for...in 인덱스의 순서가 중요한 {{jsxref("Array")}}에서 반복을 위해 사용할 수 없습니다.

+
+ +

배열 인덱스는 정수로 된 열거 가능한 속성이며, 일반적인 객체의 속성들과 같습니다. for...in은 특정 순서에 따라 인덱스를 반환하는 것을 보장할 수 없습니다. for...in반복문은 정수가 아닌 이름을 가진 속성, 상속된 모든 열거 가능한 속성들을 반환합니다.

+ +

반복되는 순서는 구현에 따라 다르기 때문에, 배열의 반복이 일관된 순서로 요소를 방문하지 못할 수도 있습니다. 그러므로 방문의 순서가 중요한 배열의 반복시에는 숫자 인덱스를 사용할 수 있는 for 반복문을 사용하는 것이 좋습니다.(또는 {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Statements/for...of", "for...of")}}를 권장합니다.)

+ +

자체 속성만 반복

+ +

만약 당신이 객체의 프로토타입이 아닌 객체 자체에 연결된 속성만 고려한다면 {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}}나 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}를 사용하십시오.({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable()")}} 또한 가능합니다.)  또는 외부적인 코드 간섭이 없다면 체크 메서드로 내장 프로토타입을 확장할 수 있습니다.

+ +

왜 for...in을 사용합니까?

+ +

for...in이 객체의 반복을 위해 만들어졌지만, 배열의 반복을 위해서는 추천되지 않고,  Array.prototype.forEach()for...of가 이미 존재합니다. 그러면 for...in은 어떻게 사용하는 것이 좋을까요?

+ +

이것은 쉽게 객체의 속성을 확인(콘솔이나 다른 방법으로 출력)할 수 있기 때문에 실질적으로 디버깅을 위해 사용될 수 있습니다. 배열이 데이터의 저장에 있어서는 더 실용적이지만, 키-값 쌍이 선호되는 데이터의 경우(속성이 "key"의 역할을 함) 특정 값을 가진 키가 있는지 확인하려는 경우에 for...in을 사용할 수 있습니다.

+ +

예제

+ +

for...in의 사용

+ +

아래의 예는 열거 가능한 non-Symbol속성들을 반복해서 속성의 이름과 그 값을 기록합니다.

+ +
var obj = {a: 1, b: 2, c: 3};
+
+for (const prop in obj) {
+  console.log(`obj.${prop} = ${obj[prop]}`);
+}
+
+// Output:
+// "obj.a = 1"
+// "obj.b = 2"
+// "obj.c = 3"
+ +

자체 속성 반복

+ +

아래는 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} 를 사용하는 예를 보여주고 있습니다. 상속된 속성은 표시되지 않습니다.

+ +
var triangle = {a:1, b:2, c:3};
+
+function ColoredTriangle() {
+  this.color = "red";
+}
+
+ColoredTriangle.prototype = triangle;
+
+function show_own_props(obj, objName) {
+  var result = "";
+
+  for (var prop in obj) {
+    if( obj.hasOwnProperty( prop ) ) {
+      result += objName + "." + prop + " = " + obj[prop] + "\n";
+    }
+  }
+
+  return result;
+}
+
+o = new ColoredTriangle();
+alert(show_own_props(o, "o")); /* alerts: o.color = red */
+
+ +

상세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Initial definition.
+ +

브라우저 호환성

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("javascript.statements.for_in")}}

+ +

Compatibility: Initializer expressions in strict mode

+ +

Prior to SpiderMonkey 40 {{geckoRelease(40)}}, it was possible to use an initializer expression (i=0) in a for...in loop:

+ +
var obj = {a: 1, b: 2, c: 3};
+for (var i = 0 in obj) {
+  console.log(obj[i]);
+}
+// 1
+// 2
+// 3
+ +

This nonstandard behavior is now ignored in version 40 and later, and will present a {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") error in strict mode ({{bug(748550)}} and {{bug(1164741)}}).

+ +

Other engines such as v8 (Chrome), Chakra (IE/Edge), and JSC (WebKit/Safari) are investigating whether to remove the nonstandard behavior as well.

+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/statements/for...of/index.html b/files/ko/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..d082763616 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,228 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +
{{jsSidebar("Statements")}}
+ +

for...of 명령문반복가능한 객체 ({{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-forof.html")}}
+ + + +

구문

+ +
for (variable of iterable) {
+  statement
+}
+
+ +
+
variable
+
각 반복에 서로 다른 속성값이 variable에 할당됩니다.
+
iterable
+
반복되는 열거가능(enumerable)한 속성이 있는 객체.
+
+ +

예제

+ +

{{jsxref("Array")}}에 대해 반복:

+ +
let iterable = [10, 20, 30];
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 10
+// 20
+// 30
+
+ +

let 대신 const도 사용할 수 있습니다, 블록 내부 변수를 수정하지 않는 경우.

+ +
let iterable = [10, 20, 30];
+
+for (const value of iterable) {
+  console.log(value);
+}
+// 10
+// 20
+// 30
+
+ +

{{jsxref("String")}}에 대해 반복:

+ +
let iterable = "boo";
+
+for (let value of iterable) {
+  console.log(value);
+}
+// "b"
+// "o"
+// "o"
+
+ +

{{jsxref("TypedArray")}}에 대해 반복:

+ +
let iterable = new Uint8Array([0x00, 0xff]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 0
+// 255
+
+ +

{{jsxref("Map")}}에 대해 반복:

+ +
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
+
+for (let entry of iterable) {
+  console.log(entry);
+}
+// [a, 1]
+// [b, 2]
+// [c, 3]
+
+for (let [key, value] of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

{{jsxref("Set")}}에 대해 반복:

+ +
let iterable = new Set([1, 1, 2, 2, 3, 3]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

DOM 컬렉션에 대해 반복

+ +

{{domxref("NodeList")}} 같은 DOM 컬렉션에 대해 반복: 다음 예는 article의 직계 자손인 paragraph에 read 클래스를 추가합니다:

+ +
// 주의: 이는 NodeList.prototype[Symbol.iterator]가
+// 구현된 플랫폼에서만 작동합니다
+let articleParagraphs = document.querySelectorAll("article > p");
+
+for (let paragraph of articleParagraphs) {
+  paragraph.classList.add("read");
+}
+
+ +

생성기에 대해 반복

+ +

생성기에 대해서도 반복할 수 있습니다:

+ +
function* fibonacci() { // 생성기 함수
+  let [prev, curr] = [1, 1];
+  while (true) {
+    [prev, curr] = [curr, prev + curr];
+    yield curr;
+  }
+}
+
+for (let n of fibonacci()) {
+  console.log(n);
+  // 1000에서 수열을 자름
+  if (n >= 1000) {
+    break;
+  }
+}
+
+ +

다른 반복가능 객체에 대해 반복

+ +

iterable 프로토콜을 명시해서 구현하는 객체에 대해서도 반복할 수 있습니다:

+ +
var iterable = {
+  [Symbol.iterator]() {
+    return {
+      i: 0,
+      next() {
+        if (this.i < 3) {
+          return { value: this.i++, done: false };
+        }
+        return { value: undefined, done: true };
+      }
+    };
+  }
+};
+
+for (var value of iterable) {
+  console.log(value);
+}
+// 0
+// 1
+// 2
+
+ +

for...offor...in의 차이

+ +

for...in 루프는 객체의 모든 열거가능한 속성에 대해 반복합니다.

+ +

for...of 구문은 컬렉션 전용입니다. 모든 객체보다는, [Symbol.iterator] 속성이 있는 모든 컬렉션 요소에 대해 이 방식으로 반복합니다.

+ +

다음 예는 for...of 루프와 for...in 루프의 차이를 보입니다.

+ +
Object.prototype.objCustom = function () {};
+Array.prototype.arrCustom = function () {};
+
+let iterable = [3, 5, 7];
+iterable.foo = "hello";
+
+for (let i in iterable) {
+  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
+}
+
+for (let i of iterable) {
+  console.log(i); // logs 3, 5, 7
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.for_of")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/for/index.html b/files/ko/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..cba49dbba6 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for/index.html @@ -0,0 +1,160 @@ +--- +title: for +slug: Web/JavaScript/Reference/Statements/for +tags: + - JavaScript + - Loop + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for +--- +
{{jsSidebar("Statements")}}
+ +

for 문은 괄호로 감싸고 세미콜론으로 구분한 세 개의 선택식과, 반복을 수행할 문(주로 {{jsxref("Statements/block", "블럭문", "", 0)}})으로 이루어져 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
+ + + +

구문

+ +
for ([initialization]; [condition]; [final-expression])
+   statement
+
+ +
+
initialization
+
식(할당식 포함) 또는 변수 선언. 주로 카운터 변수를 초기화할 때 사용합니다. var 또는 let 키워드를 사용해 새로운 변수를 선언할 수도 있습니다. var 키워드로 선언한 변수는 반복문에 제한되지 않습니다. 즉 for 문과 같은 범위scope에 위치합니다. let 키워드로 선언한 변수는 반복문의 지역 변수가 됩니다.
+
+ 식의 결과는 버려집니다.
+
condition
+
매 반복마다 평가할 식. 평가 결과가 참이라면 statement를 실행합니다. 이 식을 넣지 않았을 때 계산 결과는 언제나 참이 됩니다. 계산 결과가 거짓이라면 for 문의 바로 다음 식으로 건너 뜁니다.
+
final-expression
+
매 반복 후 평가할 식. 다음번 condition 평가 이전에 발생합니다. 주로 카운터 변수를 증감하거나 바꿀 때 사용합니다.
+
statement
+
조건의 평가 결과가 참일 때 실행하는 문. 여러 문을 반복 실행하려면 {{jsxref("Statements/block", "블럭문", "", 0)}}({ ... })으로 묶어야 합니다. 아무것도 실행하지 않으려면 {{jsxref("Statements/empty", "공백문", "", 0)}} (;)을 사용하세요.
+
+ +

예제

+ +

for 사용하기

+ +

다음 for 문은 변수 i를 선언하고 0으로 초기화하여 시작합니다. i가 9보다 작은지를 확인하고 맞으면 명령문을 수행한 후 i의 값을 1 높입니다.

+ +
for (var i = 0; i < 9; i++) {
+   console.log(i);
+   // 기타 등등
+}
+
+ +

선택적 식 사용

+ +

for 반복문의 3개 식은 모두 선택 사항입니다.

+ +

예를 들어, 변수를 초기화하려고 initialization 블럭을 사용할 필요는 없습니다.

+ +
var i = 0;
+for (; i < 9; i++) {
+    console.log(i);
+    // 기타 등등
+}
+
+ +

initialization 블럭처럼 condition 블럭도 선택 사항입니다. 다만 이 경우, 반복문 본문에 무한 반복을 탈출할 수 있는 장치를 추가해야 합니다.

+ +
for (var i = 0;; i++) {
+   console.log(i);
+   if (i > 3) break;
+   // 기타 등등
+}
+ +

세 가지 모두 생략할 수도 있습니다. 위와 같이 {{jsxref("Statements/break", "break")}} 문을 사용해 반복을 탈출할 수 있도록 추가하고, 변수를 수정해 탈출 조건이 언젠가 참이 되도록 해야 합니다.

+ +
var i = 0;
+
+for (;;) {
+  if (i > 3) break;
+  console.log(i);
+  i++;
+}
+
+ +

문 없이 for 사용하기

+ +

다음 for 반복 사이클은 노드의 위치 오프셋을 final-expression에서 계산해 문이나 블럭문이 필요하지 않으므로 세미콜론을 사용합니다.

+ +
function showOffsetPos(sId) {
+  var nLeft = 0, nTop = 0;
+
+  for (
+    var oItNode = document.getElementById(sId); /* initialization */
+    oItNode; /* condition */
+    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
+  ); /* semicolon */
+
+  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
+}
+
+/* Example call: */
+
+showOffsetPos('content');
+
+// Output:
+// "Offset position of "content" element:
+// left: 0px;
+// top: 153px;"
+ +
참고: 여기서 쓰인 세미콜론은, JavaScript가 필수로 요구하는 몇 안되는 세미콜론입니다. 물론 세미콜론 없이는 반복 사이클 선언의 바로 다음 줄을 반복 본문으로 인식합니다.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12.6.2', 'for statement')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES3', '#sec-12.6.3', 'for statement')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12.6.3', 'for statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-for-statement', 'for statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.for")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/statements/for_each...in/index.html b/files/ko/web/javascript/reference/statements/for_each...in/index.html new file mode 100644 index 0000000000..9fa9901aae --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for_each...in/index.html @@ -0,0 +1,85 @@ +--- +title: for each...in +slug: Web/JavaScript/Reference/Statements/for_each...in +tags: + - Deprecated + - E4X + - JavaScript + - Obsolete + - Statement +translation_of: Archive/Web/JavaScript/for_each...in +--- +
{{jsSidebar("Statements")}}
+ +
+

The for each...in statement is deprecated as the part of ECMA-357 (E4X) standard. E4X support has been removed. Consider using for...of instead.
+
+ Firefox now warns about the usage of for each...in and it no longer works starting with Firefox 57.
+ Please see Warning: JavaScript 1.6's for-each-in loops are deprecated for migration help.

+
+ +

for each...in 문은 객체의 모든 속성 값에 대해 지정된 변수를 반복합니다. 각각의 고유한 특성에 대해 지정된 명령문이 실행됩니다.

+ +

Syntax

+ +
for each (variable in object) {
+  statement
+}
+ +
+
variable
+
var 키워드로 선택적으로 선언된 속성 값을 반복하는 변수입니다. 이 변수는 루프가 아니라 함수의 local이 됩니다.
+
+ +
+
object
+
반복될 객체입니다.
+
+ +
+
statement
+
각 속성에 대해 실행할 명령문입니다. 루프 내에서 여러 명령문을 실행하려면 블록 명령문 ({...})을 사용하여 해당 명령문을 그룹화하십시오.
+
+ +

Description

+ +

일부 기본 제공 속성은 반복되지 않습니다. 여기에는 객체 기본 제공 메서드 전부가 포함됩니다.

+ +

ex) String의 indexOf 메소드.

+ +

그러나 사용자가 정의한 모든 속성은 반복됩니다.

+ +

Examples

+ +

Using for each...in

+ +

Warning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.

+ +

The following snippet iterates over an object's properties, calculating their sum:

+ +
var sum = 0;
+var obj = {prop1: 5, prop2: 13, prop3: 8};
+
+for each (var item in obj) {
+  sum += item;
+}
+
+console.log(sum); // logs "26", which is 5+13+8
+ +

Specifications

+ +

Not part of a current ECMA-262 specification. Implemented in JavaScript 1.6 and deprecated.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.for_each_in")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/function/index.html b/files/ko/web/javascript/reference/statements/function/index.html new file mode 100644 index 0000000000..fe1eee366a --- /dev/null +++ b/files/ko/web/javascript/reference/statements/function/index.html @@ -0,0 +1,177 @@ +--- +title: 함수 선언 +slug: Web/JavaScript/Reference/Statements/function +tags: + - Function + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/function +--- +
{{jsSidebar("Statements")}}
+ +

함수 선언(function declaration)은 지정된 매개변수(parameter)를 갖는 함수를 정의합니다.

+ +

{{jsxref("Function")}} 생성자나 {{jsxref("Operators/function", "함수 표현식(function expression)")}}을 사용해서 정의할 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-function.html")}}
+ + + +

구문

+ +
function name([param[, param,[..., param]]]) { [statements] }
+
+ +
+
name
+
함수 이름.
+
+ +
+
param
+
함수로 전달되는 인수(argument)의 이름. 인수의 최대 개수는 엔진마다 다름.
+
+ +
+
statements
+
함수의 몸통(body)을 구성하는 문(statement).
+
+ +

설명

+ +

함수 선언으로 생성된 함수는 Function 객체로, Function 객체의 모든 속성(property), 메서드 및 행위 특성(behavior)을 갖습니다. 함수에 관한 더 자세한 정보는 {{jsxref("Function")}} 참조하시기 바랍니다.

+ +

함수는 또한 표현식({{jsxref("Operators/function", "함수 표현식")}} 참조)을 사용하여 생성될 수 있습니다.

+ +

기본적으로 함수는 undefined를 반환합니다. 다른 값을 반환하기 위해서는, 함수는 반환값을 지정하는 {{jsxref("Statements/return", "return")}} 문이 있어야 합니다.

+ +

조건부로 생성되는 함수

+ +

함수는 조건부로 선언될 수 있습니다. 즉, function 문은 if 문 안에 들어갈 수 있습니다. 하지만, 구현에 따라 결과에 일관성이 없으므로 이 패턴은 실제 코드에서는 사용해선 안됩니다. 조건부로 함수를 생성하고자 한다면, 함수 표현식(function expression)을 대신 사용하세요.

+ +
var hoisted = "foo" in this;
+console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
+if (false) {
+  function foo(){ return 1; }
+}
+
+// In Chrome:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Firefox:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Edge:
+// 'foo' name is not hoisted. typeof foo is undefined
+//
+// In Safari:
+// 'foo' name is hoisted. typeof foo is function
+
+ +

결과는 참으로 평가되는 조건과 정확하게 일치합니다.

+ +
var hoisted = "foo" in this;
+console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
+if (true) {
+  function foo(){ return 1; }
+}
+
+// In Chrome:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Firefox:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Edge:
+// 'foo' name is not hoisted. typeof foo is undefined
+//
+// In Safari:
+// 'foo' name is hoisted. typeof foo is function
+
+ +

함수 선언 끌어올리기

+ +

자바스크립트에서 함수 선언은 그 선언을 둘러싼 함수의 최상부나 전역 범위(global scope)로 끌어올려집니다.

+ +
hoisted(); // logs "foo"
+
+function hoisted() {
+  console.log("foo");
+}
+
+ +

{{jsxref("Operators/function", "함수 표현식")}}은 끌어올려지지 않으므로 주의하세요:

+ +
notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log("bar");
+};
+
+ +

예제

+ +

function 사용하기

+ +

다음 코드는 제품 a, bc의 단위 판매량이 주어졌을 때, 총 판매량을 반환하는 함수를 선언합니다.

+ +
function calc_sales(units_a, units_b, units_c) {
+   return units_a*79 + units_b * 129 + units_c * 699;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{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')}} 
{{SpecName('ES1', '#sec-13', 'Function definition')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨.
+ +

브라우저 호환성

+ + + +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/function_star_/index.html b/files/ko/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..9178c28602 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,159 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +tags: + - ECMAScript6 + - Generator + - Iterator + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/function* +--- +
{{jsSidebar("Statements")}}
+ +

function* 선언 (끝에 별표가 있는 function keyword) 은 generator function 을 정의하는데, 이 함수는 {{jsxref("Global_Objects/Generator","Generator")}} 객체를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}
+ + + +

generator function 은 {{jsxref("Global_Objects/GeneratorFunction", "GeneratorFunction")}} 생성자와 {{jsxref("Operators/function*", "function* expression")}} 을 사용해서 정의할 수 있습니다.

+ +

문법

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
함수명.
+
+ +
+
param
+
함수에 전달되는 인수의 이름. 함수는 인수를 255개까지 가질 수 있다.
+
+ +
+
statements
+
함수의 본체를 구성하는 구문들.
+
+ +

설명

+ +

Generator는 빠져나갔다가 나중에 다시 돌아올 수 있는 함수입니다. 이때 컨텍스트(변수 값)는 출입 과정에서 저장된 상태로 남아 있습니다.

+ +

Generator 함수는 호출되어도 즉시 실행되지 않고, 대신 함수를 위한 Iterator 객체가 반환됩니다. Iterator의 next() 메서드를 호출하면 Generator 함수가 실행되어 {{jsxref("Operators/yield", "yield")}} 문을 만날 때까지 진행하고, 해당 표현식이 명시하는 Iterator로부터의 반환값을 반환합니다. {{jsxref("Operators/yield*", "yield*")}} 표현식을 마주칠 경우, 다른 Generator 함수가 위임(delegate)되어 진행됩니다.

+ +

이후 next() 메서드가 호출되면 진행이 멈췄던 위치에서부터 재실행합니다. next() 가 반환하는 객체는 yield문이 반환할 값(yielded value)을 나타내는 value 속성과, Generator 함수 안의 모든 yield 문의 실행 여부를 표시하는 boolean 타입의 done 속성을 갖습니다. next() 를 인자값과 함께 호출할 경우, 진행을 멈췄던 위치의 yield 문을  next() 메서드에서 받은 인자값으로 치환하고 그 위치에서 다시 실행하게 됩니다.

+ +

예시

+ +

간단한 예제

+ +
function* idMaker(){
+  var index = 0;
+  while(index < 3)
+    yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+console.log(gen.next().value); // undefined
+// ...
+
+ +

yield* 를 사용한 예제

+ +
function* anotherGenerator(i) {
+  yield i + 1;
+  yield i + 2;
+  yield i + 3;
+}
+
+function* generator(i){
+  yield i;
+  yield* anotherGenerator(i);
+  yield i + 10;
+}
+
+var gen = generator(10);
+
+console.log(gen.next().value); // 10
+console.log(gen.next().value); // 11
+console.log(gen.next().value); // 12
+console.log(gen.next().value); // 13
+console.log(gen.next().value); // 20
+
+ +

Generator 에 인자값을 넘기는 예제

+ +
function* logGenerator() {
+  console.log(yield);
+  console.log(yield);
+  console.log(yield);
+}
+
+var gen = logGenerator();
+
+// the first call of next executes from the start of the function
+// until the first yield statement
+gen.next();
+gen.next('pretzel'); // pretzel
+gen.next('california'); // california
+gen.next('mayonnaise'); // mayonnaise
+
+ +

Generator 는 생성자로서 사용될 수 없다

+ +
function* f() {}
+var obj = new f; // throws "TypeError: f is not a constructor"
+ +

Specifications

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

Browser compatibility

+ +

{{Compat("javascript.statements.generator_function")}}

+ +

관련 항목

+ + diff --git a/files/ko/web/javascript/reference/statements/if...else/index.html b/files/ko/web/javascript/reference/statements/if...else/index.html new file mode 100644 index 0000000000..cde42b2a80 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/if...else/index.html @@ -0,0 +1,177 @@ +--- +title: if...else +slug: Web/JavaScript/Reference/Statements/if...else +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/if...else +--- +
{{jsSidebar("Statements")}}
+ +

if은 지정한 조건이 {{glossary("truthy", "참")}}인 경우 명령문(statement)을 실행합니다. 조건이 {{glossary("falsy", "거짓")}}인 경우 또 다른 명령문이 실행 될 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-ifelse.html")}}
+ + + +

구문

+ +
if (condition)
+   statement1
+[else
+   statement2]
+
+ +
+
condition
+
참 또는 거짓으로 평가되는 표현식입니다.
+
+ +
+
statement1
+
조건이 참으로 평가될 경우 실행되는 문입니다.
+ 중첩된 if구문을 포함하여 어떤 구문이든 쓸 수 있습니다. 다중구문을 사용할 경우  ({ ... })블럭 구문 으로 그룹화 하고 실행하지 않으려면  구문을 사용합니다.
+
+ +
+
statement2
+
이 구문은 조건이 거짓일경우 다른 조항이 있을 때 실행되는 구문입니다. 블록 문과 if문의 중첩을 호함한 모든문이 될 수 있습니다.
+
+ +

설명

+ +

다중의 if...else 문은 else if 절을 만들기 위해 중첩될 수 있다.
+ 자바스크립트에서는 elseif (하나의 단어) 키워드가 존재하지 않는다.

+ +
if (조건1)
+   명령문1
+else if (조건2)
+   명령문2
+else if (조건3)
+   명령문3
+...
+else
+   명령문N
+
+ +

아래 작업한 것을 보면,  if문을 중첩 사용하면 들여쓰기된 것이 제대로 보여집니다.

+ +
if (조건1)
+   명령문1
+else
+   if (조건2)
+      명령문2
+   else
+      if (조건3)
+...
+
+ +

하나의 절에서 여러개의 명령문들을 실행하려면,   그 명령문들을 그룹화하는 블록 명령문 ({ ... }) 블럭구문을 사용한다.
+ 일반적으로, 블럭구문을 항상 사용하는 것은 좋은 연습입니다. 특히 중첩된 if 문과 관련되어
+ 있는 코드안에서 사용하면 더욱 좋습니다.

+ +
if (조건) {
+   명령문들1
+} else {
+   명령문들2
+}
+
+ +

원시 불리언 값인 true (참) 과 false (거짓) 을 불리언 객체의 truthiness (참으로 보이는 것) 과 falsiness (거짓으로 보이는 것)으로 혼동하면 안된다. false, undefined, null, 0, NaN, 또는 빈 스트링 ("") 이 아닌 모든 값, 그리고 false 값인 불리언 객체를 포함하는 모든 객체는 조건으로 사용될 때 truthy 로 간주된다. 예:

+ +
var b = new Boolean(false);
+if (b) // 이 조건은 참으로 보이는 것 (truthy) 이다.
+
+ +

예시

+ +

if...else 사용하기

+ +
if (cipher_char === from_char) {
+   result = result + to_char;
+   x++;
+} else {
+   result = result + clear_char;
+}
+
+ +

else if 사용하기

+ +

자바스크립트에는 elseif 구문이 없다. 그러나, else if  를 사용할 수 있다.

+ +
if (x > 5) {
+
+} else if (x > 50) {
+
+} else {
+
+}
+ +

조건식의 값을 지정하기

+ +

조건식을 단순하게 지정하는 것은 좋지 않습니다.
+ 왜냐하면,  코드를 흘깃 보면 값을 지정한것을 평등한것으로  혼동할 수 있기 때문입니다. 예를들어, 다음코드를 사용하지 마세요:

+ +
if (x = y) {
+   /* do the right thing */
+}
+
+ +

당신이 조건식에 값의 지정을 해야할 경우, 일반적인 관행은 그 할당된 것 주위에 추가 괄호를 넣어야 합니다. 예를들면:

+ +
if ((x = y)) {
+   /* do the right thing */
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-if-statement', 'if statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-if-statement', 'if statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.5', 'if statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.5', 'if statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.5', 'if statement')}}{{Spec2('ES1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.if_else")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/import/index.html b/files/ko/web/javascript/reference/statements/import/index.html new file mode 100644 index 0000000000..ce3a1536cb --- /dev/null +++ b/files/ko/web/javascript/reference/statements/import/index.html @@ -0,0 +1,156 @@ +--- +title: import +slug: Web/JavaScript/Reference/Statements/import +tags: + - ECMAScript6 + - Modules + - import +translation_of: Web/JavaScript/Reference/Statements/import +--- +
{{jsSidebar("Statements")}}
+ +

정적 import 문은 다른 모듈에서 내보낸 바인딩을 가져올 때 사용합니다.

+ +

가져오는 모듈은 "use strict"의 존재 유무와 상관없이 무조건 엄격 모드입니다. HTML 안에 작성한 스크립트에서는 import를 사용할 수 없습니다.

+ +

함수형 구문을 가진 동적 import()도 있으며, type="module"을 필요로 하지 않습니다.

+ +

{{htmlelement("script")}} 태그의 nomodule 속성을 사용해 하위호환성을 유지할 수 있습니다.

+ +

동적 가져오기는 모듈을 조건적으로 가져오고 싶거나, 필요할 때에만 가져올 때 유용합니다. 반면 초기 의존성을 불러올 때엔 정적 가져오기가 더 좋고, 정적 코드 분석 도구와 {{glossary("Tree shaking", "트리 셰이킹")}}을 적용하기 쉽습니다.

+ +

구문

+ +
import defaultExport from "module-name";
+import * as name from "module-name";
+import { export1 } from "module-name";
+import { export1 as alias1 } from "module-name";
+import { export1 , export2 } from "module-name";
+import { foo , bar } from "module-name/path/to/specific/un-exported/file";
+import { export1 , export2 as alias2 , [...] } from "module-name";
+import defaultExport, { export1 [ , [...] ] } from "module-name";
+import defaultExport, * as name from "module-name";
+import "module-name";
+var promise = import("module-name");
+ +
+
defaultExport
+
모듈에서 가져온 기본 내보내기를 가리킬 이름.
+
module-name
+
가져올 대상 모듈. 보통, 모듈을 담은 .js 파일로의 절대 또는 상대 경로입니다. 번들러에 따라 확장자를 허용하거나, 필요로 할 수도 있으므로 작업 환경을 확인하세요. 따옴표와 쌍따옴표 문자열만 사용 가능합니다.
+
name
+
가져온 대상에 접근할 때 일종의 이름공간으로 사용할, 모듈 객체의 이름.
+
exportN
+
내보낸 대상 중 가져올 것의 이름.
+
aliasN
+
가져온 유명 내보내기를 가리킬 이름.
+
+ +

설명

+ +

name 파라미터는 export 되는 멤버를 받을 오브젝트의 이름입니다. member 파라미터는 각각의 멤버를 지정하지만, name 파라미터는 모두를 가져옵니다. 모듈에서 name 은 멤버 대신 하나의 default 파라미터를 통해 export 하는 경우에도 동작할 수 있습니다. 다음의 명확한 예제 문법을 살펴봅시다.

+ +

모듈 전체를 가져옵니다. export 한 모든 것들을 현재 범위(스크립트 파일 하나로 구분되는 모듈 범위) 내에 myModule 로 바인딩되어 들어갑니다.

+ +
import * as myModule from "my-module.js";
+
+ +

모듈에서 하나의 멤버만 가져옵니다. 현재 범위 내에 myMember 이 들어갑니다.

+ +
import {myMember} from "my-module.js";
+ +

모듈에서 여러 멤버들을 가져옵니다. 현재 범위 내에 foobar 이 들어갑니다.

+ +
import {foo, bar} from "my-module.js";
+ +

멤버를 가져올 때 좀 더 편리한 별명을 지정해줍니다. 현재 범위 내에 shortName 이 들어갑니다.

+ +
import {reallyReallyLongModuleMemberName as shortName} from "my-module.js";
+ +

모듈에서 여러 멤버들을 편리한 별명을 지정하며 가져옵니다.

+ +
import {reallyReallyLongModuleMemberName as shortName, anotherLongModuleName as short} from "my-module.js";
+ +

어떠한 바인딩 없이 모듈 전체의 사이드 이펙트만 가져옵니다.

+ +
import "my-module.js";
+ +

기본값 가져오기

+ +

default export 를 통해 내보낸 것을 기본값으로 가져올 수 있습니다. (object, function, class 등). export 와 상반된 import 명령어를 통해 기본값을 가져오는 것이 가능합니다.

+ +

기본값으로 바로 가져오는 가장 간단한 버전:

+ +
import myModule from "my-module.js";
+ +

위와 함께 기본 구문도 같이 사용할 수 있습니다 (namespace 가져오기 또는 이름 지정하여 가져오기). 이러한 경우, 기본값 가져오는 부분을 먼저 선언해야 할 것입니다. 예를 들어:

+ +
import myDefault, * as myModule from "my-module.js";
+// myModule used as a namespace
+ +

또는

+ +
import myDefault, {foo, bar} from "my-module.js";
+// specific, named imports
+
+ +

예제

+ +

AJAX JSON 리퀘스트 처리를 돕는 보조 파일을 가져옵니다.

+ +
// --file.js--
+function getJSON(url, callback) {
+  let xhr = new XMLHttpRequest();
+  xhr.onload = function () {
+    callback(this.responseText)
+  };
+  xhr.open("GET", url, true);
+  xhr.send();
+}
+
+export function getUsefulContents(url, callback) {
+  getJSON(url, data => callback(JSON.parse(data)));
+}
+
+// --main.js--
+import { getUsefulContents } from "file.js";
+getUsefulContents("http://www.example.com", data => {
+  doSomethingUseful(data);
+});
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-imports', 'Imports')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-imports', 'Imports')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.import")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/index.html b/files/ko/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..cd83b9f1c0 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/index.html @@ -0,0 +1,143 @@ +--- +title: 문 및 선언 +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - Reference + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript 응용 프로그램은 적절한 구문을 갖는 문으로 구성됩니다. 한 문이 여러 줄에 걸칠 수 있습니다. 여러 문은 각 문이 세미콜론으로 구분된 경우 한 줄에 나올 수 있습니다. 이는 키워드 하나가 아니라, 키워드 그룹입니다.

+ +

항목별 문 및 선언

+ +

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

+ +

흐름 제어

+ +
+
{{jsxref("Statements/block", "Block")}}
+
블록문은 0개 이상의 문을 묶을 때 쓰입니다. 블록은 중괄호 한 쌍으로 구분됩니다.
+
{{jsxref("Statements/break", "break")}}
+
현재 루프, switch 또는 label 문을 종료하고 프로그램 제어를 종료된 문의 다음 문으로 넘겨줍니다.
+
{{jsxref("Statements/continue", "continue")}}
+
현재 또는 레이블 달린 루프의 현재 반복 중인 문의 실행을 종료하고 루프의 실행은 다음 반복으로 이어집니다.
+
{{jsxref("Statements/Empty", "empty")}}
+
empty 문은 내용이 없는 빈 문을 제공하기 위해 사용됩니다, 비록 JavaScript 구문이 문을 기대할 것이지만.
+
{{jsxref("Statements/if...else", "if...else")}}
+
지정된 조건이 true면 문을 실행. 조건이 false인 경우, 다른 문이 실행될 수 있습니다.
+
{{jsxref("Statements/switch", "switch")}}
+
식의 값이 case 절과 일치하는지 식을 평가하고 case 절과 관련된 문을 실행합니다.
+
{{jsxref("Statements/throw", "throw")}}
+
사용자 정의 예외가 발생합니다.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
시도(try)할 문 블록을 표시하고 예외가 발생되어야 하는 응답을 지정합니다.
+
+ +

선언

+ +
+
{{jsxref("Statements/var", "var")}}
+
변수를 선언합니다, 변수를 값으로 초기화할 수 있습니다.
+
{{jsxref("Statements/let", "let")}}
+
블록 범위 지역 변수를 선언합니다, 변수를 값으로 초기화할 수 있습니다.
+
{{jsxref("Statements/const", "const")}}
+
읽기 전용 유명(named) 상수를 선언합니다.
+
+ +

함수 및 클래스

+ +
+
{{jsxref("Statements/function", "function")}}
+
지정된 매개변수를 갖는 함수를 선언합니다.
+
{{jsxref("Statements/function*", "function*")}}
+
반복기를 더 쉽게 작성할 수 있게 하는 생성기 함수.
+
{{jsxref("Statements/return", "return")}}
+
함수에 의해 반환되는 값을 지정합니다.
+
{{jsxref("Statements/class", "class")}}
+
클래스를 선언합니다.
+
+ +

반복

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
테스트 조건이 거짓으로 평가될 때까지 지정된 문을 실행하는 루프를 만듭니다. 조건은 문을 실행한 후 평가됩니다, 그 결과 지정된 문은 적어도 한 번 실행됩니다.
+
{{jsxref("Statements/for", "for")}}
+
괄호로 묶이고 세미콜론으로 구분된 선택사항 식 셋으로 구성된 루프를 만듭니다, 루프에서 실행되는 문이 뒤따릅니다.
+
{{jsxref("Statements/for_each...in", "for each...in")}} {{deprecated_inline}} {{non-standard_inline}}
+
객체의 모든 속성값에 대해 지정된 변수를 반복합니다. 각 개별 속성에 대해, 지정된 문이 실행됩니다.
+
{{jsxref("Statements/for...in", "for...in")}}
+
임의의 순서로 객체의 열거 속성을 반복합니다. 각 개별 속성에 대해, 문은 실행될 수 있습니다.
+
{{jsxref("Statements/for...of", "for...of")}}
+
반복 가능한 객체 ({{jsxref("Global_Objects/Array","배열","","true")}}, 배열 같은 객체, 반복기 및 생성기 포함) 를 반복합니다, 각 개별 속성값에 대해 실행되는 문을 가진 사용자 정의 반복 후크를 호출하는.
+
{{jsxref("Statements/while", "while")}}
+
테스트 조건이 true로 평가되는 한 지정된 문을 실행하는 루프를 만듭니다. 조건은 문을 실행하기 전에 평가됩니다.
+
+ +

기타

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
이용 가능한 디버깅 기능을 호출합니다. 이용 가능한 기능이 없는 경우, 이 문은 아무 효과가 없습니다.
+
{{jsxref("Statements/export", "export")}}
+
외부 모듈, 다른 스크립트에 가져올(import) 수 있도록 함수를 내보내(export)는데 사용됩니다.
+
{{jsxref("Statements/import", "import")}}
+
외부 모듈, 다른 스크립트에서 내보낸 함수를 가져오는데 사용됩니다.
+
{{jsxref("Statements/label", "label")}}
+
break 또는 continue 문을 사용하여 참조할 수 있는 식별자 있는 문을 제공합니다.
+
+ +
+
{{jsxref("Statements/with", "with")}} {{deprecated_inline}}
+
문의 스코프 체인을 확장합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}초기 정의
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}신규: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

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

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/label/index.html b/files/ko/web/javascript/reference/statements/label/index.html new file mode 100644 index 0000000000..49d6054031 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/label/index.html @@ -0,0 +1,241 @@ +--- +title: label +slug: Web/JavaScript/Reference/Statements/label +translation_of: Web/JavaScript/Reference/Statements/label +--- +
{{jsSidebar("Statements")}}
+ +

레이블 구문은 {{jsxref("Statements/break", "break")}}나 {{jsxref("Statements/continue", "continue")}} 구문과 함께 사용할 수 있다. 원하는 식별자로 구문 앞에 레이블을 추가할 수 있다.

+ +
+

레이블을 붙인 반복문이나 블록가 자주 사용되는 것은 아니다. 반복문으로 점프하는 대신에 함수를 호출할 수도 있다.

+
+ +

문법

+ +
label :
+   statement
+
+ +
+
label
+
자바스크립트에서 사용할 수 있는 식별자면 모두 가능하다.
+
statement
+
구문. break는 모든 레이블 구문에서 사용될 수 있으며, continue는 반복 레이블 구문에서만 사용할 수 있다.
+
+ +

설명

+ +

반복문에 레이블을 붙이고, break나 continue 구문을 사용해 반복문의 어느 위치에서 작업을 멈추고 어느 위치에서 다시 수행할지를 알려줄 수 있다.

+ +

자바스크립트에는 goto 구문이 없다는 것에 주의. break나 continue에서만 레이블을 사용할 수 있다.

+ +

strict mode  코드에서 "let"을 레이블 이름으로 사용할 수 없다. {{jsxref("SyntaxError")}}를 발생시킨다. (let은 허용되지 않는 식별자이다.)

+ +

예제

+ +

for문에서 레이블 continue 사용하기

+ +
var i, j;
+
+loop1:
+for (i = 0; i < 3; i++) {      //첫번째 for문은 "loop1" 레이블을 붙였다.
+   loop2:
+   for (j = 0; j < 3; j++) {   //두번째 for문은 "loop2" 레이블을 붙였다.
+      if (i === 1 && j === 1) {
+         continue loop1;
+      }
+      console.log('i = ' + i + ', j = ' + j);
+   }
+}
+
+// 출력 결과:
+//   "i = 0, j = 0"
+//   "i = 0, j = 1"
+//   "i = 0, j = 2"
+//   "i = 1, j = 0"
+//   "i = 2, j = 0"
+//   "i = 2, j = 1"
+//   "i = 2, j = 2"
+// 다음 두 경우를 어떻게 스킵하는지 주목 : "i = 1, j = 1", "i = 1, j = 2"
+
+ +

레이블 continue문 사용하기

+ +

items, tests 배열을 보면 이 예제는 tests를 통과하는 items의 수를 세고 있다.

+ +
var itemsPassed = 0;
+var i, j;
+
+top:
+for (i = 0; i < items.length; i++) {
+  for (j = 0; j < tests.length; j++) {
+    if (!tests[j].pass(items[i])) {
+      continue top;
+    }
+  }
+
+  itemsPassed++;
+}
+ +

for문에 레이블 break문 사용하기

+ +
var i, j;
+
+loop1:
+for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
+   loop2:
+   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
+      if (i === 1 && j === 1) {
+         break loop1;
+      }
+      console.log('i = ' + i + ', j = ' + j);
+   }
+}
+
+// Output is:
+//   "i = 0, j = 0"
+//   "i = 0, j = 1"
+//   "i = 0, j = 2"
+//   "i = 1, j = 0"
+// Notice the difference with the previous continue example
+ +

레이블 break문 사용하기

+ +

items, tests 배열을 보면, 다음 예제는 items가 tests를 모두 통과하는지 판단한다.

+ +
var allPass = true;
+var i, j;
+
+top:
+for (i = 0; items.length; i++)
+  for (j = 0; j < tests.length; i++)
+    if (!tests[j].pass(items[i])) {
+      allPass = false;
+      break top;
+    }
+ +

레이블 붙인 블록에 break 사용하기

+ +

간단한 블록에도 레이블을 사용할 수 있지만, 반복문 아닌 레이블에는 break문만 사용할 수 있다.

+ +
foo: {
+  console.log('face');
+  break foo;
+  console.log('this will not be executed');
+}
+console.log('swap');
+
+// 로그는 이렇게 출력된다:
+
+// "face"
+// "swap 
+ +

레이블 붙인 함수 선언문

+ +

ECMAScript 2015에서, 레이블 붙인 함수 선언문은 web compatibility annex of the specification의 non-strict 모드에서 표준화되어 있다.

+ +
L: function F() {}
+ +

strict mode  에서는 {{jsxref("SyntaxError")}}를 발생시킨다.

+ +
'use strict';
+L: function F() {}
+// SyntaxError: functions cannot be labelled
+ +

Generator functions는 strict code도 non-strict code에서도 레이블 붙일 수 없다.

+ +
L: function* F() {}
+// SyntaxError: generator functions cannot be labelled
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.12', 'Labelled statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-labelled-statements', 'Labelled statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-labelled-statements', 'Labelled statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

더 알아보기

+ + diff --git a/files/ko/web/javascript/reference/statements/let/index.html b/files/ko/web/javascript/reference/statements/let/index.html new file mode 100644 index 0000000000..3d02a34fba --- /dev/null +++ b/files/ko/web/javascript/reference/statements/let/index.html @@ -0,0 +1,246 @@ +--- +title: let +slug: Web/JavaScript/Reference/Statements/let +translation_of: Web/JavaScript/Reference/Statements/let +--- +
{{jsSidebar("Statements")}}
+ +

let 구문은 블록 유효 범위를 갖는 지역 변수를 선언하며, 선언과 동시에 임의의 값으로 초기화할 수도 있다.

+ +
{{EmbedInteractiveExample("pages/js/statement-let.html")}}
+ + + +

Syntax

+ +
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];
+ +

Parameters

+ +
+
var1, var2, …, varN
+
변수명. 유효한 식별자이면 가능하다.
+
value1, value2, …, valueN
+
변수의 초기값. 유효한 표현식이면 가능하다.
+
+ +

Description

+ +

let은 변수가 선언된 블록, 구문 또는 표현식 내에서만 유효한 변수를 선언한다. 이는 var 키워드가 블록 범위를 무시하고 전역 변수나 함수 지역 변수로 선언되는 것과 다른 점이다.

+ +

"let"을 사용해야 하는 이유에 대해서는 이어지는 링크를 참조하시오.

+ +

유효 범위 규칙

+ +

let 으로 선언된 변수는 변수가 선언된 블록 내에서만 유효하며, 당연하지만 하위 블록에서도 유효하다. 이러한 점에서는 letvar는 유사하지만, var는 함수 블록 이외의 블록은 무시하고 선언된다는 점이 다르다.

+ +
function varTest() {
+  var x = 1;
+  if (true) {
+    var x = 2;  // 상위 블록과 같은 변수!
+    console.log(x);  // 2
+  }
+  console.log(x);  // 2
+}
+
+function letTest() {
+  let x = 1;
+  if (true) {
+    let x = 2;  // 상위 블록과 다른 변수
+    console.log(x);  // 2
+  }
+  console.log(x);  // 1
+}
+
+ +

프로그램이나 함수의 최상위에서는 letvar은 서로 다르게 행동한다. let은 전역 객체의 속성 값을 생성하지 않는다.

+ +
var x = 'global';
+let y = 'global';
+console.log(this.x); // "global" 전역 객체의 속성 x를 생성
+console.log(this.y); // undefined 전역 객체의 속성 y를 생성하지 않음
+
+ +

비공개 변수 모사

+ +

생성자와 함께 사용하여 클로저를 사용하지 않고 비공개 변수를 만들고 접근할 수 있다.

+ +
var Thing;
+
+{
+  let privateScope = new WeakMap();
+  let counter = 0;
+
+  Thing = function() {
+    this.someProperty = 'foo';
+
+    privateScope.set(this, {
+      hidden: ++counter,
+    });
+  };
+
+  Thing.prototype.showPublic = function() {
+    return this.someProperty;
+  };
+
+  Thing.prototype.showPrivate = function() {
+    return privateScope.get(this).hidden;
+  };
+}
+
+console.log(typeof privateScope);
+// "undefined"
+
+var thing = new Thing();
+
+console.log(thing);
+// Thing {someProperty: "foo"}
+
+thing.showPublic();
+// "foo"
+
+thing.showPrivate();
+// 1
+
+ +

임시적인 사각 지역과 오류

+ +

같은 변수를 같은 함수나 블록 범위 내에서 재선언하면 {{jsxref("SyntaxError")}}가 발생한다.

+ +
if (x) {
+  let foo;
+  let foo; // SyntaxError thrown.
+}
+ +

ECMAScript 2015에서는let선언 끌어올리기의 적용을 받지 않습니다.  이는 let 선언이 현재 실행되는 구간의 최상위로 옮겨지지 않는다는 것을 의미합니다. 따라서 변수가 초기화(선언)되기 전에 참조할 경우 ReferenceError가 발생합니다.(var로 선언된 변수는 undefined 값을 가지는 것과는 대조적입니다.) "임시적인 사각 지역"은 블록 시작 부분부터 변수 선언이 실행되기 전까지 입니다.

+ +

(let들의 정의가 평가되기까지 초기화가 되지 않는다는 의미이지. 호이스팅이 되지않아 정의가 되지 않는다는 의미와는 다르다고 생각함_헷갈리면 안된다.)

+ +
function do_something() {
+  console.log(bar); // undefined
+  console.log(foo); // ReferenceError
+  var bar = 1;
+  let foo = 2;
+}
+ +

switch 구문을 사용할 때는 실제 블록이 하나 뿐이므로 중복 선언 오류가 발생하기 쉽습니다.

+ +
let x = 1;
+switch(x) {
+  case 0:
+    let foo;
+    break;
+
+  case 1:
+    let foo; // 재선언에 의한 SyntaxError.
+    break;
+}
+ +

하지만 case 조건을 새로운 블록으로 감싸면 위의 코드와는 다르게 재선언 오류가 발생하지 않습니다.

+ +
let x = 1;
+
+switch(x) {
+  case 0: {
+    let foo;
+    break;
+  }
+  case 1: {
+    let foo;
+    break;
+  }
+}
+ +

임시적인 사각 지역과 typeof

+ +

선언되지 않은 변수와 undefined 값을 지닌 변수와는 다르게, 임시적인 사각 지역에 있는 변수에 변수형 확인을 위해 typeof을 사용하면 ReferenceError가 발생합니다:

+ +
// 'undefined' 출력
+console.log(typeof undeclaredVariable);
+// 'ReferenceError' 발생
+console.log(typeof i);
+let i = 10;
+ +

정적 유효 범위와 결합된 임시적인 사각 지역 예시

+ +

정적 유효 범위로 인해, 표현 (foo + 55) 내부의 "foo"는 33을 값으로 가지는 상위 블록의 foo가 아니라 if 블록의 foo로 해석됩니다. 해당 행에서 if 블록의 "foo"는 이미 정적 유효 범위에 생성되었지만, 선언의 초기화가 완료(선언 구문의 종료)되지 않았습니다. 따라서 여전히 임시적인 사각 지역에 해당됩니다.

+ +
function test(){
+   var foo = 33;
+   if (true) {
+      let foo = (foo + 55); // ReferenceError
+   }
+}
+test();
+ +

이 현상은 다음과 같은 상황에서 혼란을 유발할 수 있습니다. 지시 구문  let n of n.a은 이미 for loop 블록에 속해 있으며, 구문자 "n.a"는 속성 'a'를 지시 구문 자기자신의 앞부분에 위치한 객체 'n'에서 참조하려 합니다. 해당 객체 'n'은 위와 마찬가지로 선언이 종료되지 않았기에 임시적인 사각 지역에 해당합니다.

+ +
function go(n) {
+  // 정의되어 있는 n!
+  console.log(n); // Object {a: [1,2,3]}
+
+  for (let n of n.a) { // ReferenceError
+    console.log(n);
+  }
+}
+
+go({a: [1, 2, 3]});
+
+ +

그 외 상황들

+ +

블록을 사용할 때, let은 변수의 유효 범위를 블록으로 제한합니다. 함수 내 또는 전역을 유효 범위로 가지는 var와의 차이점을 숙지하세요.

+ +
var a = 1;
+var b = 2;
+
+if (a === 1) {
+  var a = 11; // 전역 변수
+  let b = 22; // if 블록 변수
+
+  console.log(a);  // 11
+  console.log(b);  // 22
+}
+
+console.log(a); // 11
+console.log(b); // 2
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ES2015')}}Initial definition. Does not specify let expressions or let blocks.
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.let")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/return/index.html b/files/ko/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..e865cb9a65 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/return/index.html @@ -0,0 +1,159 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

return 명령문은 함수 실행을 종료하고, 주어진 값을 함수 호출 지점으로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-return.html")}}
+ + + +

구문

+ +
return [[expression]]; 
+ +
+
expression
+
반환할 값으로 사용할 표현식. 생략할 경우 {{jsxref("undefined")}}를 대신 반환합니다.
+
+ +

설명

+ +

함수 본문에서 return 명령문에 도달하면 함수의 실행은 그 지점에서 중단됩니다. 값을 제공한 경우 함수를 호출한 곳에 그 값을 반환합니다. 예를 들어, 다음 함수는 숫자 매개변수 x의 제곱을 반환합니다.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo는 9
+ +

값을 명시하지 않으면 대신 undefined를 반환합니다.

+ +

다음 return 명령문 모두 함수 실행을 끊습니다.

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

자동 세미콜론 삽입

+ +

return 명령문은 자동 세미콜론 삽입(ASI)의 영향을 받습니다. return 키워드와 표현식 사이에는 줄바꿈 문자가 올 수 없습니다.

+ +
return
+a + b;
+
+ +

위 코드는 ASI로 인해 아래처럼 처리됩니다.

+ +
return;
+a + b;
+
+ +

콘솔이 "unreachable code after return statement" 경고를 출력할 것입니다.

+ +
Gecko 40 {{geckoRelease(40)}}부터, return 이후에 위치하여 도달할 수 없는 코드를 발견하면 콘솔에 경고를 출력합니다.
+ +

문제를 해결하려면 괄호를 사용해 ASI를 방지해야 합니다.

+ +
return (
+  a + b
+);
+
+ +

예제

+ +

함수 중단

+ +

함수는 return을 호출하는 지점에서 즉시 실행을 멈춥니다.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // 무한 반복
+    console.log(count + "A"); // 5까지
+      if (count === 5) {
+        return;
+      }
+      console.log(count + "B");  // 4까지
+    }
+  console.log(count + "C");  // 절대 나타나지 않음
+}
+
+counter();
+
+// 출력:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

함수 반환하기

+ +

클로저에 대해서도 더 알아보세요.

+ +
function magic(x) {
+  return function calc(x) { return x * 42 };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.return")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/switch/index.html b/files/ko/web/javascript/reference/statements/switch/index.html new file mode 100644 index 0000000000..b4eb68e5a7 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/switch/index.html @@ -0,0 +1,306 @@ +--- +title: switch +slug: Web/JavaScript/Reference/Statements/switch +translation_of: Web/JavaScript/Reference/Statements/switch +--- +
{{jsSidebar("Statements")}}
+ +

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

+ +
{{EmbedInteractiveExample("pages/js/statement-switch.html")}}
+ + + +

문법

+ +
switch (expression) {
+  case value1:
+    //Statements executed when the
+    //result of expression matches value1
+    [break;]
+  case value2:
+    //Statements executed when the
+    //result of expression matches value2
+    [break;]
+  ...
+  case valueN:
+    //Statements executed when the
+    //result of expression matches valueN
+    [break;]
+  [default:
+    //Statements executed when none of
+    //the values match the value of the expression
+    [break;]]
+}
+ +
+
expression
+

+ 각각의 case 절에 맞추어볼 결과에 대한 expression
+
case valueN {{optional_inline}}
+
어떤 case 절은  expression와 맞추어보는데 사용된다. 만약 expression 이 특정 valueN과 일치 된다면, switch statement 문이 끝나거나 break가 오떄까지 case 절 내부가 실행된다.
+
default {{optional_inline}}
+
default 절; 만약 있다면,  어떤 case의 절도 expression 값과 일치되지 않는다면, default 절이 실행된다.
+
+ +

설명

+ +

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.)

+ +

If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

+ +

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

+ +

예제

+ +

Using switch

+ +

In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

+ +
switch (expr) {
+  case 'Oranges':
+    console.log('Oranges are $0.59 a pound.');
+    break;
+  case 'Apples':
+    console.log('Apples are $0.32 a pound.');
+    break;
+  case 'Bananas':
+    console.log('Bananas are $0.48 a pound.');
+    break;
+  case 'Cherries':
+    console.log('Cherries are $3.00 a pound.');
+    break;
+  case 'Mangoes':
+  case 'Papayas':
+    console.log('Mangoes and papayas are $2.79 a pound.');
+    break;
+  default:
+    console.log('Sorry, we are out of ' + expr + '.');
+}
+
+console.log("Is there anything else you'd like?");
+
+ +

break를 쓰지않으면 어떻게 되는가?

+ +

If you forget a break then the script will run from the case where the criterion is met and will run the case after that regardless if criterion was met. See example here:

+ +
var foo = 0;
+switch (foo) {
+  case -1:
+    console.log('negative 1');
+    break;
+  case 0: // foo is 0 so criteria met here so this block will run
+    console.log(0);
+    // NOTE: the forgotten break would have been here
+  case 1: // no break statement in 'case 0:' so this case will run as well
+    console.log(1);
+    break; // it encounters this break so will not continue into 'case 2:'
+  case 2:
+    console.log(2);
+    break;
+  default:
+    console.log('default');
+}
+ +

Can I put a default between cases?

+ +

Yes, you can! JavaScript will drop you back to the default if it can't find a match:

+ +
var foo = 5;
+switch (foo) {
+  case 2:
+    console.log(2);
+    break; // it encounters this break so will not continue into 'default:'
+  default:
+    console.log('default')
+    // fall-through
+  case 1:
+    console.log('1');
+}
+
+ +

It also works when you put default before all other cases.

+ +

Methods for multi-criteria case

+ +

Source for this technique is here:

+ +

Switch statement multiple cases in JavaScript (Stack Overflow)

+ +

Multi-case - single operation

+ +

This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section titled "What happens if I forgot a break?"

+ +

This is an example of a single operation sequential switch statement, where four different values perform exactly the same.

+ +
var Animal = 'Giraffe';
+switch (Animal) {
+  case 'Cow':
+  case 'Giraffe':
+  case 'Dog':
+  case 'Pig':
+    console.log('This animal will go on Noah\'s Ark.');
+    break;
+  case 'Dinosaur':
+  default:
+    console.log('This animal will not.');
+}
+ +

Multi-case - chained operations

+ +

This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.

+ +
var foo = 1;
+var output = 'Output: ';
+switch (foo) {
+  case 0:
+    output += 'So ';
+  case 1:
+    output += 'What ';
+    output += 'Is ';
+  case 2:
+    output += 'Your ';
+  case 3:
+    output += 'Name';
+  case 4:
+    output += '?';
+    console.log(output);
+    break;
+  case 5:
+    output += '!';
+    console.log(output);
+    break;
+  default:
+    console.log('Please pick a number from 0 to 5!');
+}
+ +

이 예제의 결과:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueLog text
foo is NaN or not 1, 2, 3, 4, 5 or 0Please pick a number from 0 to 5!
0Output: So What Is Your Name?
1Output: What Is Your Name?
2Output: Your Name?
3Output: Name?
4Output: ?
5Output: !
+ +

Block-scope variables within switch statements

+ +

With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables.

+ +

Take a look at this example:

+ +
const action = 'say_hello';
+switch (action) {
+  case 'say_hello':
+    let message = 'hello';
+    console.log(message);
+    break;
+  case 'say_hi':
+    let message = 'hi';
+    console.log(message);
+    break;
+  default:
+    console.log('Empty action received.');
+    break;
+}
+ +

This example will output the error Uncaught SyntaxError: Identifier 'message' has already been declared which you were not probably expecting.

+ +

This is because the first let message = 'hello'; conflicts with second let statement let message = 'hi'; even they're within their own separate case statements case 'say_hello': and case 'say_hi':; ultimately this is due to both let statements being interpreted as duplicate declarations of the same variable name within the same block scope.

+ +

We can easily fix this by wrapping our case statements with brackets:

+ +
const action = 'say_hello';
+switch (action) {
+  case 'say_hello': { // added brackets
+    let message = 'hello';
+    console.log(message);
+    break;
+  } // added brackets
+  case 'say_hi': { // added brackets
+    let message = 'hi';
+    console.log(message);
+    break;
+  } // added brackets
+  default: { // added brackets
+    console.log('Empty action received.');
+    break;
+  } // added brackets
+}
+ +

This code will now output hello in the console as it should, without any errors at all.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.11', 'switch statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.switch")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/throw/index.html b/files/ko/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..ff5ccb2333 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,198 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

throw 문은 사용자 정의 예외를 던질 수 있습니다. 현재 함수의 실행이 중지되고 (throw 이후의 명령문은 실행되지 않습니다.), 컨트롤은 콜 스택의 첫 번째 catch 블록으로 전달됩니다. 호출자 함수 사이에 catch 블록이 없으면 프로그램이 종료됩니다. 

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + + +

Syntax

+ +
throw expression; 
+ +
+
expression
+
예외를 던지는 구문
+
+ +

Description

+ +

예외를 발생하기 위해 throw 문을 사용하세요. 
+ 예외를 던지면 expression은 예외 값을 지정합니다.
+ 다음 각각은 예외를 던집니다:

+ +
throw 'Error2'; // generates an exception with a string value
+throw 42;       // generates an exception with the value 42
+throw true;     // generates an exception with the value true
+ +

또한 throw 문은 자동 세미콜론 삽입 (ASI)에 의해 영향을 받으며 throw 키워드와 표현식 사이에 줄 종결자는 허용되지 않으므로 주의해야합니다.

+ +

예제

+ +

객체 throw 하기

+ +

예외를 던질 때 객체를 지정할 수 있습니다. 그러면 catch 블록에서 객체의 속성을 참조 할 수 있습니다.
+ 다음 예제에서는 UserException 유형의 객체를 만들고 throw 구문에서 이 객체를 사용합니다.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

객체를 throw 하는 다른 예제

+ +

다음 예제는 입력 문자열에서 미국 우편 번호를 테스트합니다.
+ 우편 번호가 잘못된 형식을 사용하는 경우 throw 문은 ZipCodeFormatException 유형의 개체를 만들어 예외를 던집니다.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow an exception

+ +

throw를 사용하여 예외를 잡은 후에 예외를 다시 던질 수 있습니다.
+ 다음 예제에서는 숫자 값으로 예외를 잡고 값이 50 이상이면 예외를 다시 throw합니다.
+ 반환 된 예외는 둘러싸는 함수 또는 최상위 수준으로 전파되어 사용자가 볼 수 있도록합니다

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

추가적으로 볼 것

+ + diff --git a/files/ko/web/javascript/reference/statements/try...catch/index.html b/files/ko/web/javascript/reference/statements/try...catch/index.html new file mode 100644 index 0000000000..c7cdf05b1f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/try...catch/index.html @@ -0,0 +1,273 @@ +--- +title: try...catch +slug: Web/JavaScript/Reference/Statements/try...catch +translation_of: Web/JavaScript/Reference/Statements/try...catch +--- +
+

{{jsSidebar("Statements")}}

+ +

try...catch 문은 실행할 코드블럭을 표시하고 예외(exception)가 발생(throw)할 경우의 응답을 지정합니다.

+ +

{{EmbedInteractiveExample("pages/js/statement-trycatch.html")}}

+
+ +

문법

+ +
try {
+  try_statements
+}
+[catch (exception_var) {
+  catch_statements
+}]
+[finally {
+  finally_statements
+}]
+ +
+
try_statements
+
실행될 선언들
+
+ +
+
catch_statements
+
try 블록에서 예외가 발생했을 때 실행될 선언들
+
+ +
+
exception_var
+
catch 블록과 관련된 예외 객체를 담기 위한 식별자
+
+ +
+
finally_statements
+
try 선언이 완료된 이후에 실행된 선언들. 이 선언들은 예외 발생 여부와 상관없이 실행된다.
+
+ +

설명

+ +

try 선언의 구성은 하나 혹은 그 이상의 선언을 포함한 try 블록 및 catch 항목이나 finally 항목 중 최소한 하나 혹은 둘 다 포함하여 이루어진다. 즉, try 선언에는 세 가지 형식이 존재한다.

+ +
    +
  1. try...catch
  2. +
  3. try...finally
  4. +
  5. try...catch...finally
  6. +
+ +

catch 블록은 try 블록 안에서 예외가 발생(throw)하는 경우 무엇을 할지 명시하는 코드를 포함합니다.  try 블록 (또는 try 블록 내에서 호출된 함수) 내의 명령문이 예외를 throw 하면 제어가 catch 블록으로 이동합니다. try 블록에 예외가 발생하지 않으면 catch 블록을 건너뜁니다.

+ +

finally 블록은 try 블록과 catch 블록(들)이 실행을 마친 후 항상 실행됩니다. 예외가 발생했는지에 관계없이 항상 실행됩니다.

+ +

하나 이상의 try 문을 중첩 할 수 있습니다. 내부의 try 문에 catch 블록이 없으면, 둘러싼 try 문의 catch 블록이 입력됩니다.

+ +

또한 try 문을 사용하여 예외처리를 합니다. 예외처리에 대해 더 알고 싶다면, JavaScript Guide 를 참고하세요.

+ +

무조건적 catch

+ +

try-block 내에서 예외가 발생하면 catch-block이 실행됩니다. 예를 들어, 다음 코드에서 예외가 발생하면 제어가 catch 블록으로 전송됩니다.

+ + + +
try {
+   throw "myException"; // generates an exception
+}
+catch (e) {
+   // statements to handle any exceptions
+   logMyErrors(e); // pass exception object to error handler
+}
+
+ +

조건적 catch

+ +

다음과 같이 try...catch블록을 if...else if...else 구조와 결합하여 '조건부 catch-blocks'을 만들 수 있습니다.

+ + + +
try {
+  myroutine(); // may throw three types of exceptions
+} catch (e) {
+  if (e instanceof TypeError) {
+    // statements to handle TypeError exceptions
+  } else if (e instanceof RangeError) {
+    // statements to handle RangeError exceptions
+  } else if (e instanceof EvalError) {
+    // statements to handle EvalError exceptions
+  } else {
+    // statements to handle any unspecified exceptions
+    logMyErrors(e); // pass exception object to error handler
+  }
+}
+
+ + + +

이에 대한 일반적인 사용 사례는 예상 오류의 작은 하위 집합 만 포착 (및 침묵) 한 다음 다른 경우에 오류를 다시 발생시키는 것입니다.

+ +
try {
+  myRoutine();
+} catch (e) {
+  if (e instanceof RangeError) {
+    // statements to handle this very common expected error
+  } else {
+    throw e;  // re-throw the error unchanged
+  }
+}
+ +

The exception identifier

+ +

try-block에서 예외가 발생하면 exception_var (즉, catch (e)내부의 e)가 예외 값을 보유합니다. 이 식별자를 사용하여 발생한 예외에 대한 정보를 얻을 수 있습니다. 이 식별자는 catch-block의 {{Glossary("Scope", "scope")}}에서만 사용할 수 있습니다.

+ + + +
function isValidJSON(text) {
+  try {
+    JSON.parse(text);
+    return true;
+  } catch {
+    return false;
+  }
+}
+ +

The finally-block

+ +

The finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. Note that the finally-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception.

+ + + +

The following example shows one use case for the finally-block. The code opens a file and then executes statements that use the file; the finally-block makes sure the file always closes after it is used even if an exception was thrown.

+ +
openMyFile();
+try {
+  // tie up a resource
+  writeMyFile(theData);
+}
+finally {
+  closeMyFile(); // always close the resource
+}
+ +

Examples

+ +

Nested try-blocks

+ +

First, let's see what happens with this:

+ +
try {
+  try {
+    throw new Error('oops');
+  }
+  finally {
+    console.log('finally');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Output:
+// "finally"
+// "outer" "oops"
+
+ +

Now, if we already caught the exception in the inner try-block by adding a catch-block

+ +
try {
+  try {
+    throw new Error('oops');
+  }
+  catch (ex) {
+    console.error('inner', ex.message);
+  }
+  finally {
+    console.log('finally');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Output:
+// "inner" "oops"
+// "finally"
+
+ +

And now, let's rethrow the error.

+ +
try {
+  try {
+    throw new Error('oops');
+  }
+  catch (ex) {
+    console.error('inner', ex.message);
+    throw ex;
+  }
+  finally {
+    console.log('finally');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Output:
+// "inner" "oops"
+// "finally"
+// "outer" "oops"
+
+ +

Any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block.

+ +

Returning from a finally-block

+ +

If the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch-blocks. This includes exceptions thrown inside of the catch-block:

+ +
(function() {
+  try {
+    try {
+      throw new Error('oops');
+    }
+    catch (ex) {
+      console.error('inner', ex.message);
+      throw ex;
+    }
+    finally {
+      console.log('finally');
+      return;
+    }
+  }
+  catch (ex) {
+    console.error('outer', ex.message);
+  }
+})();
+
+// Output:
+// "inner" "oops"
+// "finally"
+ +

The outer "oops" is not thrown because of the return in the finally-block. The same would apply to any value returned from the catch-block.

+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-try-statement', 'try statement')}}
+ +

Browser compatibility

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("javascript.statements.try_catch")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/var/index.html b/files/ko/web/javascript/reference/statements/var/index.html new file mode 100644 index 0000000000..4366c3ed73 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/var/index.html @@ -0,0 +1,195 @@ +--- +title: var +slug: Web/JavaScript/Reference/Statements/var +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/var +--- +
{{jsSidebar("Statements")}}
+ +

var문은 변수를 선언하고, 선택적으로 초기화할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-var.html")}}
+ + + +

구문

+ +
var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];
+ +
+
varnameN
+
변수 이름. 어떤 유효한 식별자도 될 수 있습니다.
+
+ +
+
valueN
+
변수의 초기값. 어떤 유효한 표현도 될 수 있습니다.
+
+ +

설명

+ +

어디에 선언이 되어있든 간에 변수들은 어떠한 코드가 실행되기 전에  처리가 됩니다. var로 선언된 변수의 범위는 현재 실행 문맥인데, 그 문맥은 둘러싼 함수, 혹은 함수의 외부에 전역으로 선언된 변수도 될 수 있습니다.

+ +

선언된 변수들의 값 할당은 할당이 실행될 때 전역변수(이것은 전역 오브젝트의 프로퍼티가 됩니다)처럼 생성이 됩니다. 선언된 변수들과 선언되지 않은 변수들의 차이점은 다음과 같습니다:

+ +

1. 선언된 변수들은 변수가 선언된 실행 콘텍스트(execution context) 안에서 만들어집니다. 선언되지 않은 변수들은 항상 전역변수 입니다.

+ +
function x() {
+  y = 1;   // strict 모드에서는 ReferenceError를 출력합니다.
+  var z = 2;
+}
+
+x();
+
+console.log(y); // 로그에 "1" 출력합니다.
+console.log(z); // ReferenceError: z is not defined outside x를 출력합니다.
+
+ +

2. 선언된 변수들은 어떠한 코드가 실행되기 전에 만들어집니다. 선언되지 않은 변수들은 변수들을 할당하는 코드가 실행되기 전까지는 존재하지 않습니다.

+ +
console.log(a);                // ReferenceError를 출력합니다.
+console.log('still going...'); // 결코 실행되지 않습니다.
+ +
var a;
+console.log(a);                // 브라우저에 따라 로그에 "undefined" 또는 "" 출력합니다.
+console.log('still going...'); // 로그에 "still going..." 출력합니다.
+ +

3. 선언된 변수들은 변수들의 실행 콘텍스트(execution context)의 프로퍼티를 변경되지 않습니다. 선언되지 않은 변수들은 변경 가능합니다. (e.g 삭제 될 수도 있습니다.)

+ +
var a = 1;
+b = 2;
+
+delete this.a; // strict 모드에서는 TypeError를 출력합니다. 그렇지 않으면 자동적으로 실패합니다.
+delete this.b;
+
+console.log(a, b); // ReferenceError를 출력합니다.
+// 'b' 프로퍼티는 삭제되었고, 어디에도 존재하지 않습니다.
+ +

이러한 세가지 다른점 때문에, 변수 선언 오류는 예기치않은 결과로 이어질 가능성이 높습니다.  그러므로 함수 또는 전역 범위인지 여부와 상관없이, 항상 변수를 선언 하는 것을 추천합니다. 그리고 ECMAScript 5 안에 strict mode, 선언되지 않은 변수에 할당하면 오류를 출력합니다.

+ +

var 호이스팅(hoisting)

+ +

변수 선언들 (그리고 일반적인 선언)은 어느 코드가 실행 되기 전에 처리하기 때문에, 코드 안에서 어디서든 변수 선언은  최상위에 선언한 것과 동등합니다. 이것은 변수가 선언되기 전에 사용 될 수 있다는 것을 의미합니다. 변수 선언이 함수 또는 전역 코드의 상단에 이동하는 것과 같은 행동을 "호이스팅(hoisting)"이라고 불립니다.

+ +
bla = 2
+var bla;
+// ...
+
+// 위 선언을 다음과 같이 암묵적으로 이해하면 됩니다:
+
+var bla;
+bla = 2;
+
+ +

이러한 이유로, 그들의 범위(전역 코드의 상단 그리고 함수 코드의 상단) 상단에 변수를 항상 선언하기를 권장합니다. 그러면 변수는 함수 범위 (지역)이 되며, 스코프 체인으로 해결될 것이 분명합니다.

+ +

예제

+ +

두 변수들의 선언 및 초기화

+ +
var a = 0, b = 0;
+
+ +

단일 문자열 값으로 두 변수들 할당

+ +
var a = "A";
+var b = a;
+
+// 다음과 같음:
+
+var a, b = a = "A";
+
+ +

순서에 유의:

+ +
var x = y, y = 'A';
+console.log(x + y); // undefinedA
+
+ +

여기, x와 y는 어떠한 코드 실행하기 전에 선언되었다, 할당은 후에 발생하였다. "x = y"가 실행될 때, y는 존재하여 ReferenceError를 출력하진 않고 값은 'undefined' 입니다. 그래서, x는 undefined 값이 할당 됩니다. 그리고나서, y는 'A' 값이 할당 됩니다. 결과적으로, 첫번째 줄 이후에, x === undefined && y === 'A', 이와 같은 결과가 됩니다.

+ +

다수의 변수들의 초기화

+ +
var x = 0;
+
+function f(){
+  var x = y = 1; // x는 지역변수로 선언됩니다. y는 아닙니다!
+}
+f();
+
+console.log(x, y); // 0, 1
+// x는 예상대로 전역이다
+// y leaked outside of the function, though! 
+ +

암묵적인 전역변수와 외부 함수 범위

+ +

암묵적인 전역변수가 될 것으로 보이는 변수는 함수 범위 밖에서 변수들을 참조할 수 있다.

+ +
var x = 0;  // x는 전역으로 선언되었고, 0으로 할당됩니다.
+
+console.log(typeof z); // undefined, z는 아직 존재하지 않습니다.
+
+function a() { // a 함수를 호출했을 때,
+  var y = 2;   // y는 함수 a에서 지역변수로 선언되었으며, 2로 할당됩니다.
+
+  console.log(x, y);   // 0 2
+
+  function b() {       // b 함수를 호출하였을때,
+    x = 3;  // 존재하는 전역 x값에 3을 할당, 새로운 전역 var 변수를 만들지 않습니다.
+    y = 4;  // 존재하는 외부 y값에 4를 할당, 새로운 전역 var 변수를 만들지 않습니다.
+    z = 5;  // 새로운 전역 z 변수를 생성하고 5를 할당 합니다.
+  }         // (strict mode에서는 ReferenceError를 출력합니다.)
+
+  b();     // 호출되는 b는 전역 변수로 z를 생성합니다.
+  console.log(x, y, z);  // 3 4 5
+}
+
+a();                   // 호출되는 a는 또한 b를 호출합니다.
+console.log(x, z);     // 3 5
+console.log(typeof y); // undefined y는 function a에서 지역 변수입니다.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-12.2', 'var statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-variable-statement', 'variable statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-variable-statement', 'variable statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.var")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/while/index.html b/files/ko/web/javascript/reference/statements/while/index.html new file mode 100644 index 0000000000..5509404ed6 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/while/index.html @@ -0,0 +1,142 @@ +--- +title: while +slug: Web/JavaScript/Reference/Statements/while +tags: + - 반복문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Statements/while +--- +
{{jsSidebar("Statements")}}
+ +

while문은 조건문이 참일 때 실행되는 반복문이다. 조건은 문장안이 실행되기 전에 참, 거짓을 판단한다.

+ +

문법

+ +
while (condition)
+  statement
+
+ +
+
조건
+
반복이 시작되기 전에 조건문은 참,거짓을 판단받게 된다. 만약 조건문이 참이라면, while문 안의 문장들이 실행된다. 거짓이라면, 문장은 그냥 while 반복문 후로 넘어간다.
+
문장
+
조건문이 참일 때만 while문 속의 문장들이 실행된다. 반복문 속에 여러개의 문장을 사용하고 싶다면 중괄호 { } 를 통해 문장들을 하나로 묶어야 한다.
+
+ +

예제

+ +

다음의 while문은 n이 3보다 작을 때까지 반복한다.

+ +
var n = 0;
+var x = 0;
+
+while (n < 3) {
+  n++;
+  x += n;
+}
+ +

반복을 살펴보면, n을 x에 계속 더하게 된다. 그러므로 x와 n 변수는 다음의 값을 갖는다.

+ + + +

세번째 반복후, n<3 이라는 초건은 더 이상 참이아니가 되므로 반복은 종료된다

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-while-statement', 'while statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.6.2', 'while statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.6.2', 'while statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.6.1', 'while statement')}}{{Spec2('ES1')}}Initial definition
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/with/index.html b/files/ko/web/javascript/reference/statements/with/index.html new file mode 100644 index 0000000000..30940cc297 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/with/index.html @@ -0,0 +1,127 @@ +--- +title: with +slug: Web/JavaScript/Reference/Statements/with +translation_of: Web/JavaScript/Reference/Statements/with +--- +
Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. See the "Ambiguity Contra" paragraph in the "Description" section below for details.
+ +
{{jsSidebar("Statements")}}
+ +

with statement 는 명령문의 범위 체인을 확장합니다.

+ +

Syntax

+ +
with (expression)
+  statement
+
+ +
+
expression
+
명령문을 평가할 때 사용되는 범위 체인에 지정된 표현식을 추가합니다. 표현식을 중괄호로 감싸는 것은 필수입니다.
+
statement
+
모든 구문을 말합니다. 여러개의 명령문을 실행하려면 블록명령문 ({...})을 사용하여 해당 명령문을 그룹화 하세요.
+
+ +

Description

+ +

JavaScript는 규정되지 않은 이름을 포함하는 스크립트 또는 함수의 실행 컨텍스트와 연관된 범위 체인을 검색하여 규정되지 않은 이름을 찾습니다. 'with'문은 해당 개체를 평가하는 동안 이 개체를 해당 범위 체인의 머리글에 추가합니다. 본문에 사용된 규정되지 않은 이름이 범위 체인의 속성과 일치하는 경우 이름은 속성과 속성이 포함 된 개체에 바인딩 됩니다. 그렇지 않으면, {{jsxref("ReferenceError")}} 가 발생됩니다.

+ +
with 를 사용하는 것은 권장하지 않으며, ECMAScript 5 strict mode에서는 금지되어 있습니다. 임시 변수에 액세스 하려는 속성이 있는 객체를 할당하는 것이 좋습니다.
+ +

Performance pro & contra

+ +

Pro: with 구문은 성능저하 없이 긴 객체 참조를 반복해야할 필요를 줄여서 파일 크기를 감소 시킬 수 있습니다. 'with'에 필요한 스코프 체인 변경은 연산 비용이 들지 않습니다. 'with'를 사용하면 반복되는 객체 참조를 파싱하는 인터프리터가 해소됩니다. 하지만 대게의 경우에 이 이점은 임시변수를 사용하여 원하는 객체에 대한 참조를 저장함으로써 얻을 수 있습니다.

+ +

Contra: The with statement forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. Where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object.

+ +

Ambiguity contra

+ +

Contra: The with statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:

+ +
function f(x, o) {
+  with (o) {
+    console.log(x);
+  }
+}
+ +

Only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results.

+ +

Contra: Code using with may not be forward compatible, especially when used with something other than a plain object. Consider this example:

+ +
+
function f(foo, values) {
+  with (foo) {
+    console.log(values);
+  }
+}
+
+ +

If you call f([1,2,3], obj) in an ECMAScript 5 environment, then the values reference inside the with statement will resolve to obj. However, ECMAScript 6 introduces a values property on {{jsxref("Array.prototype")}} (so that it will be available on every array). So, in a JavaScript environment that supports ECMAScript 6, the values reference inside the with statement could resolve to [1,2,3].values. However, in this particular example, {{jsxref("Array.prototype")}} has been defined with values in its {{jsxref("Symbol.unscopables")}} object. If it were not, one can see how this would be a difficult issue to debug.

+
+ +

Examples

+ +

Using with

+ +

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

+ +
var a, x, y;
+var r = 10;
+
+with (Math) {
+  a = PI * r * r;
+  x = r * cos(PI);
+  y = r * sin(PI / 2);
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-with-statement', 'with statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-with-statement', 'with statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.10', 'with statement')}}{{Spec2('ES5.1')}}Now forbidden in strict mode.
{{SpecName('ES3', '#sec-12.10', 'with statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.10', 'with statement')}}{{Spec2('ES1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.with")}}

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf