TIL/JS

JS와 JSON의 undefined

yyeon111 2023. 4. 2. 23:56

옵셔널 체이닝을 공부하다가 예제를 보고 이해가 안되는 부분이 있어서 코드를 뜯어보았다.

 

분명 property를 반환하는 함수임에도 불구하고 계속 빈 객체를 반환하는 것이였다.

 

그래서 예제인 코드를 수정해서 검토해 본 결과, undefined를 인식하는 방법이 JS와 JSON에서 다르다는 것을 확인 할 수 있었다.

 

⚪ 예제

const rand = () => Math.random() < 0.75;

const notSure = () => rand() ? {
  prop1: rand() ? {
    prop2: rand() ? {
      prop3: rand() ? '성공!' : undefined
    } : undefined
  } : undefined
} : undefined;

const result = notSure();
console.log(JSON.stringify(result));

예제에서 random함수를 사용했기 때문에 작동 원리를 추측으로 해서 혼돈이 왔던 것 같다.

예제를 보다 직관적으로 수정 해 보았다.

 

⚫ 변경 예제

const notSure = () => 1 ? {
  prop1: 0 ? {
    prop2: 0 {
      prop3: 0 ? '성공!' : undefined
    } : undefined
  } : undefined
} : undefined;

const result = notSure();

console.log(result)
console.log(JSON.stringify(result));

확인 해 본 결과, result가 true가 나왔을 경우, JS식으로 생각 했을 때는 {prop1: undefined} 를 생각한다.

하지만 JSON의 특성상 property의 값이 undefined일 경우에는 해당 property가 없다고 인식하는 것이다.

그래서 생각했던 것과는 달리 {}가 결과로 나온다.

그렇다면 처음부터 false가 나온다면 아무것도 나오지 않을까?

그렇지 않다.

JS든 JSON이든 아무것도 없는 것 자체가 undefined를 가리키기 때문에 공백 자체를 결과로 보여주지 않는다.

따라서 JS도 JSON도 undefined가 결과로 나온다.

//JavaScript 결과

undefined
{prop1: undefined}
{prop1 {prop2: undefined}
{prop1 {prop2: {prop3: undefined}
{prop1 {prop2: {prop3: '성공!'}

//JSON 결과
undefined
{}
{prop1:{}}
{prop1: prop2: {}}
{prop1: prop2: prop3: '성공!'}

'TIL > JS' 카테고리의 다른 글

렉시컬, 스코프체인, 클로저  (0) 2023.04.03
옵셔널 체이닝  (0) 2023.04.02
var  (0) 2023.04.02
에러 핸들링(4)_에러타입  (0) 2023.04.01
에러 핸들링(3)_Error 속성 바꾸기  (0) 2023.04.01