프론트 개발 블로그

void 0; 이 뭐지? 본문

Javascript

void 0; 이 뭐지?

maybe.b50 2021. 1. 18. 03:49

ES6 Class Properties 내에서 Arrow Function을 사용했을 때 Babel로 컴파일하면 아래와 같은 코드로 컴파일된다. 

(화살표 함수 사용 시 this 바인딩을 따로 해주지 않아도 되는 것을 테스트 하는 중이었다.)

// ES6 Class Properties 내에서 arrow function 사용
handleClick = () => {
    console.log(this);
    alert(this.state.message);
}
// 위의 코드를 Babel 로 컴파일 시 
"use strict";

var _this = void 0;

handleClick = function handleClick() {
  console.log(_this); // undefined
  alert(_this.state.message);
};

 

컴파일 후 나타나는 var _this = void 0; 에서 void 0; 은 무슨 의미일까?

void는 연산자로, 표현식을 해서 undefined를 반환한다.

오직 undefined 원시값을 얻기 위해 void 0 또는 void (0)처럼 사용하는 경우도 볼 수 있다.

이런 경우 전역 undefined 대신 사용해도 된다고 MDN 문서에 나와있다.

 

 

 

아래의 내용은 stackoverflow 에서 설명되어 있는 글이다.

왜? undefined 를 사용하지 않고, void 0; 을 사용하는 걸까?

void 0 보다 undefined 를 사용하는 것이 훨씬 간단하고 이해하기 쉽다.

그러나, undefined 를 사용할 때 문제점은 undefined 가 예약어가 아니라는 것이다. 

(실제로 전역 객체의 속성이다.)

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note. ES5 이상을 지원하는 환경에서는 더 이상 문제가 되지 않는다. 이는 전역 개체의 정의되지 않은 속성을 읽기 전용으로 정의하는 변수를 shadow 하는 것만 가능하다. 그러나 이 정보는 이전 버전과 호환성을 위해 여전히 유용하다.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

반면에 void 는 오버라이드가 되지 않는다.

void 0 은 항상 undefined를 리턴한다.

반면에 undefined 는 Javascript가 원하는 무엇이든 될 수 있다.

 

구체적으로, 왜 void 0 인가??

0 대신 1로 쓸 수도 있고, 42 또는 100000으로도 사용할 수 있다.

그러나 다른 인수 대신 0을 전달하는 유일한 이점은 0이 짧고 관용적이라는 것이다.

 

왜 이것이 여전히 관련되어 있습니까?

undefined는 일반적으로 최신 자바스크립트 환경에서 신뢰할 수 있지만, void 0의 장점은 다음과 같다. 

.... it's shorter....??? 더 짧다!!

대부분의 코드 축소기는 undefined 를 void 0으로 대체하여 브라우저로 전송되는 바이트 수를 줄인다.

 

정리

  • void 연산자는 값을 평가하고 undefined 를 반환한다.
  • void 0 은 원시값 undefined를 반환받기 위해 사용한다.
  • 코드 축소기에서 바이트 수를 줄이기 위해 undefined 를 void 0으로 대체하는 경우도 있다.

 

stackoverflow.com/questions/7452341/what-does-void-0-mean

 

What does `void 0` mean?

Reading through the Backbone.js source code, I saw this: validObj[attr] = void 0; What is void 0? What is the purpose of using it here?

stackoverflow.com

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/void

 

void - JavaScript | MDN

void 연산자는 주어진 표현식을 평가하고 undefined를 반환합니다. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/m

developer.mozilla.org

 

반응형