본문 바로가기
Tech/JS

undefined 초기화

by egas 2021. 7. 30.

코어 자바스크립트를 읽다가 다음과 같은 문장을 접할 수 있었다.

 

예제 1-19의 [1]의 '값을 대입하지 않은 변수. 즉 데이터 영역의 메모리 주소를 지정하지 않은 식별자에 접근할 때 undefined를 반환한다'는 내용은 다른 자바스크립트 입문서에서 소개하는 내용과는 거리가 있습니다. 즉 'var a'라는 구문에 의해 식별자 a에 자동으로 undefined가 '할당된다'고 소개하는 것이 일반적입니다. 그런데 자바스크립트가 실제로 그렇게 동작하는 것은 아닙니다. 정확히는 아무것도 할당되지 않고 끝나며, 이후 변수 a에 접근하고자 할 때 비로소 undefined를 반환하는 것이 맞습니다.

var a 로 선언하고 아무것도 할당하지 않았을 때, 아무것도 할당이 되지 않는다는게 사실일까? 궁금해졌다.

 

MDN

MDN에서는 다음과 같은 사실을 알 수 있었다.

 

undefined is a property of the global object. That is, it is a variable in global scope. The initial value of undefined is the primitive value undefined.

A variable that has not been assigned a value is of type undefined.
- https://developer.mozilla.org/
en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined -


전역 식별자로 undefined가 정의 되어있긴 하지만, var a; 경우에는 기본형 undefined로 결정됨을 알 수 있다. 하지만 type으로 undefined를 갖는다는 의미가 할당이 된다는 의미가 아니라고 생각하니 혼동이 많이 된다.

 

A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.

 

`변수에 값이 할당된 값이 없는경우 undefined를 반환한다`라고 명시되어있다. (명시적으로 undefined가 할당이 안된다고는 안적혀있어서, 조금 모호한 표현인것 같다.)

디버거

이 사실을 확인하기위해 우선 크롬 디버거로 확인해보았다. 하지만, 둘의 차이점은 찾아볼 수 없었다.

 

명세서

명세서에 'var는 선언될 때, undefined로 초기화된다.'고 명시 되어있다. 

https://tc39.es/ecma262/#sec-variable-statement

 

ECMAScript® 2022 Language Specification

The first and subsequent editions of ECMAScript have provided, for certain operators, implicit numeric conversions that could lose precision or truncate. These legacy implicit conversions are maintained for backward compatibility, but not provided for BigI

tc39.es

 

추가적으로 let에 대해서는 '초기화가 따로 없으면 undefined가 할당된다.'고 명시 되어있다. 

https://tc39.es/ecma262/#sec-let-and-const-declarations

 

ECMAScript® 2022 Language Specification

The first and subsequent editions of ECMAScript have provided, for certain operators, implicit numeric conversions that could lose precision or truncate. These legacy implicit conversions are maintained for backward compatibility, but not provided for BigI

tc39.es

 

결론

직접 코어 자바스크립트 책을 집필하신 정재남님께 메일로 여쭤보았다. 답변을 주셨는데, 잘못된 지식이라고 알려주셨다. 따라서, var a;로 선언시 undefined로 초기화된다.

728x90

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

.filter(Boolean)  (0) 2021.07.30
불변성 Immutability  (0) 2021.07.30
ES5 vs ES6  (0) 2021.07.30
자바스크립트 꼬리물기와 for에 관하여...  (0) 2021.05.28

댓글