[ECMAScript 6] const - 상수 선언하기
>const
는 >let
과 같이 ECMAScript 6에 도입된 block 단위 상수 선언문이다. 중복으로 선언할 수 없고, 선언 전에 사용할 수 없다는 것은 >let
과 같다. 거기에 >const
는 추가적인 제약이 더 붙는다.
우선 >const
로 선언된 이름에는 값을 재할당할 수 없다. 이는 문법적으로 에러로 처리한다. 따라서 >const
에 값을 할당하는 구문을 실행할 때 발생하는 것이 아니라 >const
에 값을 할당하는 구문이 있는 함수가 선언될 때 에러가 발생한다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PORT = 80; | |
function setPort(port) { | |
PORT = port; // const로 선언한 상수에 값을 재할당할 수 없다. | |
} // 이 함수를 선언할 때 에러가 발생한다. |
또한, >const
를 이용해서 상수를 선언할 때는 언제나 값을 초기화해주어야 한다. >const
로 선언된 상수에 값을 할당하지 못한다는 것을 생각하면, 당연한 일이다. 이 또한 문법 에러로, 초기화하지 않는 >const
를 선언할 때가 아니라, 선언하는 구문이 있는 함수를 선언할 때 에러가 발생한다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function draw(mode) { | |
const COLOR_CODE; // 로 선언하는 상수는 반드시 초기화해야 한다. | |
switch(mode) { | |
case RED: | |
COLOR_CODE = 0; | |
break; | |
case BLUE: | |
COLOR_CODE = 1; | |
break; | |
case GREEN: | |
COLOR_CODE = 2; | |
break; | |
} | |
fill(COLOR_CODE); | |
} // 이 함수를 선언할 때 에러가 발생한다. |
하지만 >const
도 상수 선언을 위한 완벽한 해결책은 아니다. >const
로 선언한 상수에는 값을 재할당할 수 없지만, 상수임에도 불구하고 값을 변경시킬 수 있기 때문이다. >const
로 선언한 상수는 어디까지나 값의 재할당을 막을 뿐, 그 값을 보호해주지 않는다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MEMBER = []; | |
MEMBER.push(someone); | |
MEMBER.push(another); | |
MEMBER.push(the_other); | |
// MEMBER = [ someone, another, the_other ] | |
const EVENT_HANDLER = { }; | |
EVENT_HANDLER["connection"] = doConnection; | |
EVENT_HANDLER["close"] = doClose; | |
EVENT_HANDLER["err"] = handleError; | |
// EVENT_HANDLER = { "connection": doConnection, "close": doClose, "err": handleError } |
>const가 완벽한 해결책인 것은 아니지만
, 한계를 알고 적절하게 사용하면 좀 더 안정적이고 가독성 있는 코드를 작성할 수 있다.
댓글
댓글 쓰기