Skip to content

Commit 06cfae2

Browse files
[옵셔널 체이닝] 번역
1 parent 1ae5166 commit 06cfae2

File tree

1 file changed

+64
-64
lines changed
  • 1-js/04-object-basics/07-optional-chaining

1 file changed

+64
-64
lines changed
Lines changed: 64 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,57 @@
11

2-
# Optional chaining '?.'
2+
# 옵셔널 체이닝 '?.'
33

44
[recent browser="new"]
55

6-
The optional chaining `?.` is an error-proof way to access nested object properties, even if an intermediate property doesn't exist.
6+
옵셔널 체이닝(optional chaining) `?.`을 사용하면 중첩 객체에 프로퍼티가 없어도 에러 없이 안전하게 접근할 수 있습니다.
77

8-
## The problem
8+
## 옵셔널 체이닝이 필요한 이유
99

10-
If you've just started to read the tutorial and learn JavaScript, maybe the problem hasn't touched you yet, but it's quite common.
10+
이제 막 자바스크립트를 배우기 시작했다면 옵셔널 체이닝이 등장하게 된 배경 상황을 직접 겪어보지 않았을 겁니다. 몇 가지 사례를 재현하면서 왜 옵셔널 체이닝이 등장했는지 살펴봅시다.
1111

12-
For example, some of our users have addresses, but few did not provide them. Then we can't safely read `user.address.street`:
12+
사용자가 여러 명 있는데 그 중 몇 명은 주소 정보를 가지고 있지 않다고 가정해보겠습니다. 이럴 때 `user.address.street`를 사용해 주소 정보에 접근하면 에러가 발생할 수 있습니다.
1313

1414
```js run
15-
let user = {}; // the user happens to be without address
15+
let user = {}; // 주소정보가 없는 사용자
1616

17-
alert(user.address.street); // Error!
17+
alert(user.address.street); // TypeError: Cannot read property 'street' of undefined
1818
```
1919

20-
Or, in the web development, we'd like to get an information about an element on the page, but it may not exist:
20+
또 다른 사례는 브라우저에서 동작하는 코드를 개발하는 도중에 발생할 수 있는 문제입니다. 페이지에 있는 특정 요소에 담긴 정보에 접근하려 하는데 , 요소가 페이지에 없는 경우입니다.
2121

2222
```js run
23-
// Error if the result of querySelector(...) is null
24-
let html = document.querySelector('.my-element').innerHTML;
23+
// querySelector(...) 호출 결과가 null인 경우
24+
let html = document.querySelector('.my-element').innerHTML; //TypeError: Cannot read property 'innerHTML' of null
2525
```
2626

27-
Before `?.` appeared in the language, the `&&` operator was used to work around that.
27+
명세서에 `?.`이 추가되기 전엔 이런 문제들을 해결하기 위해 `&&` 연산자를 사용하곤 했습니다.
2828

29-
For example:
29+
예시:
3030

3131
```js run
32-
let user = {}; // user has no address
32+
let user = {}; // 주소정보가 없는 사용자
3333

34-
alert( user && user.address && user.address.street ); // undefined (no error)
34+
alert( user && user.address && user.address.street ); // undefined, 에러가 발생하지 않습니다.
3535
```
3636

37-
AND'ing the whole path to the property ensures that all components exist, but is cumbersome to write.
37+
중첩 객체의 특정 프로퍼티에 접근하기 위해 거쳐야 할 구성요소들을 AND로 연결해 실제 해당 객체나 프로퍼티가 있는지 확인하는 방법을 사용했었죠. 그런데 이렇게 AND를 연결해서 사용하면 코드가 아주 길어진다는 문제가 생깁니다.
3838

39-
## Optional chaining
39+
## 옵셔널 체이닝의 등장
4040

41-
The optional chaining `?.` stops the evaluation and returns `undefined` if the part before `?.` is `undefined` or `null`.
41+
`?.``?.`'앞'의 평가 대상이 `undefined``null`이면 평가를 멈추고 `undefined`를 반환합니다.
4242

43-
Further in this article, for brevity, we'll be saying that something "exists" if it's not `null` and not `undefined`.
43+
설명이 장황해지지 않도록 지금부턴 평가 대상의 평가 결과가 `null`이나 `undefined`가 아닌 경우엔 값이 '있다', '존재한다'라고 표현하겠습니다.
4444

4545

46-
Here's the safe way to access `user.address.street`:
46+
이제 옵셔널 체이닝을 사용해 `user.address.street`에 안전하게 접근해봅시다.
4747

4848
```js run
49-
let user = {}; // user has no address
49+
let user = {}; // 주소정보가 없는 사용자
5050

51-
alert( user?.address?.street ); // undefined (no error)
51+
alert( user?.address?.street ); // undefined, 에러가 발생하지 않습니다.
5252
```
5353
54-
Reading the address with `user?.address` works even if `user` object doesn't exist:
54+
`user?.address`로 주소를 읽으면 아래와 같이 `user` 객체가 존재하지 않더라도 에러가 발생하지 않습니다.
5555
5656
```js run
5757
let user = null;
@@ -62,115 +62,115 @@ alert( user?.address.street ); // undefined
6262
alert( user?.address.street.anything ); // undefined
6363
```
6464
65-
Please note: the `?.` syntax works exactly where it's placed, not any further.
65+
위 예시를 통해 우리는 `?.`은 문법이 위치해 있는 그 자리에서만 동작하지, 확장되어 동작하지는 않는다는 것을 알 수 있습니다.
6666
67-
In the last two lines the evaluation stops immediately after `user?.`, never accessing further properties. But if the `user` actually exists, then the further intermediate properties, such as `user.address` must exist.
67+
`user?.` 평가가 끝나고 `user`에 값이 없다는 것이 판별되면 그 즉시 평가를 멈추기 때문에 마지막 두 줄에서 에러가 발생하지 않았습니다. 평가가 끝나면 나머지 프로퍼티들엔 접근 자체를 하지 않기 때문입니다. 다만 `user`가 존재하는 경우엔 `user.address` 같은 중간 프로퍼티들이 평가대상이 되기 때문에 반드시 값이 있어야 에러가 발생하지 않습니다.
6868
69-
```warn header="Don't overuse the optional chaining"
70-
We should use `?.` only where it's ok that something doesn't exist.
69+
```warn header="옵셔널 체이닝을 남용하지 마세요."
70+
`?.`는 존재하지 않아도 괜찮은 대상에만 사용해야 합니다.
7171

72-
For example, if according to our coding logic `user` object must be there, but `address` is optional, then `user.address?.street` would be better.
72+
사용자 주소 관련 위 예시에서 논리상 `user`는 반드시 있어야 하는데 `address`는 필수값이 아닙니다. 그러니 `user.address?.street`를 사용하는 것이 바람직합니다.
7373

74-
So, if `user` happens to be undefined due to a mistake, we'll know about it and fix it. Otherwise, coding errors can be silenced where not appropriate, and become more difficult to debug.
74+
실수로 인해 `user`에 값을 할당하지 않았다면 바로 알아낼 수 있도록 해야 합니다. 그렇지 않으면 에러를 조기에 발견하지 못하고 디버깅이 어려워집니다.
7575
```
7676
77-
````warn header="The variable before `?.` must exist"
78-
If there's no variable `user`, then `user?.anything` triggers an error:
77+
````warn header="`?.`앞의 변수는 꼭 선언되어 있어야 합니다."
78+
변수 `user`가 선언되어있지 않으면 `user?.anything` 평가시 에러가 발생합니다.
7979
8080
```js run
8181
// ReferenceError: user is not defined
8282
user?.address;
8383
```
84-
The optional chaining only tests for `null/undefined`, doesn't interfere with any other language mechanics.
84+
옵셔널 체이닝은 다른 언어 메커니즘엔 전혀 영향을 끼치지 않고 오직 `null/undefined` 여부만 검사합니다.
8585
````
8686
87-
## Short-circuiting
87+
## 단락 평가
8888
89-
As it was said before, the `?.` immediately stops ("short-circuits") the evaluation if the left part doesn't exist.
89+
`?.`는 왼쪽 평가대상에 값이 없으면 즉시 평가를 멈춥니다(단락 평가, short-circuit).
9090
91-
So, if there are any further function calls or side effects, they don't occur:
91+
따라서 `?.` 오른쪽에 있는 함수 호출 등의 부가 동작들은 `?.`의 평가가 멈췄을 때 더는 일어나지 않습니다.
9292
9393
```js run
9494
let user = null;
9595
let x = 0;
9696

97-
user?.sayHi(x++); // nothing happens
97+
user?.sayHi(x++); // 아무 일도 일어나지 않습니다.
9898

99-
alert(x); // 0, value not incremented
99+
alert(x); // 0, x의 값은 증가하지 않습니다.
100100
```
101101
102-
## Other cases: ?.(), ?.[]
102+
## ?.() ?.[]
103103
104-
The optional chaining `?.` is not an operator, but a special syntax construct, that also works with functions and square brackets.
104+
`?.`은 연산자가 아니고 함수, 대괄호와 함께 동작하는 특별한 문법 구조체(syntax construct)입니다.
105105
106-
For example, `?.()` is used to call a function that may not exist.
106+
`?.()`는 존재 여부가 확실치 않은 함수를 호출할 때 쓸 수 있습니다.
107107
108-
In the code below, some of our users have `admin` method, and some don't:
108+
예시를 살펴봅시다. 한 객체엔 메서드 `admin`이 있지만 다른 객체엔 없는 상황입니다.
109109
110110
```js run
111111
let user1 = {
112112
admin() {
113-
alert("I am admin");
113+
alert("관리자 계정입니다.");
114114
}
115115
}
116116

117117
let user2 = {};
118118

119119
*!*
120-
user1.admin?.(); // I am admin
120+
user1.admin?.(); // 관리자 계정입니다.
121121
user2.admin?.();
122122
*/!*
123123
```
124124
125-
Here, in both lines we first use the dot `.` to get `admin` property, because the user object must exist, so it's safe read from it.
125+
user 객체는 반드시 존재하기 때문에 `admin` 프로퍼티엔 `.`만 사용해 접근했습니다.
126126
127-
Then `?.()` checks the left part: if the user exists, then it runs (for `user1`). Otherwise (for `user2`) the evaluation stops without errors.
127+
그리고 난 후 `?.()`를 사용해 `admin`의 존재 여부를 확인했습니다. `user1``admin`이 정의되어 있기 때문에 메서드가 제대로 호출되는 반면, `user2``admin`이 정의되어 있지 않기 때문에 에러 없이 그냥 평가가 멈추는 것을 확인할 수 있습니다.
128128
129-
The `?.[]` syntax also works, if we'd like to use brackets `[]` to access properties instead of dot `.`. Similar to previous cases, it allows to safely read a property from an object that may not exist.
129+
`.`대신 대괄호 `[]`를 사용해 객체 프로퍼티에 접근하는 경우엔 `?.[]`를 사용할 수도 있습니다. 위 예시와 마찬가지로 `?.[]`를 사용하면 프로퍼티 존재 여부가 확실치 않은 경우에도 안전하게 프로퍼티를 읽을 수 있습니다.
130130
131131
```js run
132132
let user1 = {
133-
firstName: "John"
133+
firstName: "Violet"
134134
};
135135

136-
let user2 = null; // Imagine, we couldn't authorize the user
136+
let user2 = null; // user2는 권한이 없는 사용자라고 가정해봅시다.
137137

138138
let key = "firstName";
139139

140-
alert( user1?.[key] ); // John
140+
alert( user1?.[key] ); // Violet
141141
alert( user2?.[key] ); // undefined
142142

143143
alert( user1?.[key]?.something?.not?.existing); // undefined
144144
```
145145
146-
Also we can use `?.` with `delete`:
146+
`?.``delete`와도 함께 사용할 수 있습니다.
147147
148148
```js run
149-
delete user?.name; // delete user.name if user exists
149+
delete user?.name; // user가 존재하면 user.name을 삭제합니다.
150150
```
151151
152-
```warn header="We can use `?.` for safe reading and deleting, but not writing"
153-
The optional chaining `?.` has no use at the left side of an assignment:
152+
```warn header="`?.`은 읽기나 삭제하기에는 사용할 수 있지만 쓰기에는 사용할 수 없습니다."
153+
`?.`은 할당 연산자 왼쪽에서 사용할 수 없습니다.
154154

155155
```js run
156-
// the idea of the code below is to write user.name, if user exists
156+
// user가 존재할 경우 user.name에 값을 쓰려는 의도로 아래와 같이 코드를 작성
157157
158-
user?.name = "John"; // Error, doesn't work
159-
// because it evaluates to undefined = "John"
158+
user?.name = "Violet"; // SyntaxError: Invalid left-hand side in assignment
159+
// 에러가 발생하는 이유는 undefined = "Violet"이 되기 때문입니다.
160160
```
161161

162-
## Summary
162+
## 요약
163163

164-
The `?.` syntax has three forms:
164+
옵셔널 체이닝 문법 `?.`은 세 가지 형태로 사용할 수 있습니다.
165165

166-
1. `obj?.prop` -- returns `obj.prop` if `obj` exists, otherwise `undefined`.
167-
2. `obj?.[prop]` -- returns `obj[prop]` if `obj` exists, otherwise `undefined`.
168-
3. `obj?.method()` -- calls `obj.method()` if `obj` exists, otherwise returns `undefined`.
166+
1. `obj?.prop` -- `obj`가 존재하면 `obj.prop`을 반환하고, 그렇지 않으면 `undefined`를 반환함
167+
2. `obj?.[prop]` -- `obj`가 존재하면 `obj.[prop]`을 반환하고, 그렇지 않으면 `undefined`를 반환함
168+
3. `obj?.method()` -- `obj`가 존재하면 `obj.method()`를 호출하고, 그렇지 않으면 `undefined`를 반환함
169169

170-
As we can see, all of them are straightforward and simple to use. The `?.` checks the left part for `null/undefined` and allows the evaluation to proceed if it's not so.
170+
여러 예시를 통해 살펴보았듯이 옵셔널 체이닝 문법은 꽤 직관적이고 사용하기도 쉽습니다. `?.` 왼쪽 평가 대상이 `null/undefined`인지 확인하고 `null/undefined`가 아니라면 평가를 계속 진행하죠.
171171

172-
A chain of `?.` allows to safely access nested properties.
172+
`?.`를 계속 연결해서 체인을 만들면 중첩 프로퍼티들에 안전하게 접근할 수 있습니다.
173173

174-
Still, we should apply `?.` carefully, only where it's ok that the left part doesn't to exist.
174+
다만 `?.``?.`왼쪽 평가대상이 없어도 괜찮은 경우에만 선택적으로 사용해야 합니다.
175175

176-
So that it won't hide programming errors from us, if they occur.
176+
꼭 있어야 하는 값인데 없는 경우에 `?.`를 사용해서 프로그래밍 에러를 쉽게 찾을 수 없게 하는 상황을 만들지 말도록 합시다.

0 commit comments

Comments
 (0)