[JavaScript] 상수 사용하기

let currentResult = 0;

currentResult = (currentResult + 10) * 3 / 2 - 1;

let calculationDescription = '(' + currentResult + ' + 10) * 3 / 2 -1)'

outputResult(currentResult, calculationDescription)

이 구조를 가진 코드를 저장하고 index.html을 열어보면

(14 + 10)*3 / 2 - 1

이렇게 나온다 내가 의도하는건 14가 0이 되게 출력되어야 하는데 말이다. 

왜 이런일이 벌어지냐 하면 JS 코드는 위에서 아래로 실행이 되기 때문이다. 

HTML 파일은 브라우저에 의해 위에서부터 아래로 분석이 되고, JS를 그곳에 임포트 하면 파일내의 코드 역시 위에서부터 밑으로 실행이 되기 때문이다. 

따라서 구조를 이렇게 바꾸어서 currentResult를 계산하는 행 전에 넣으면

원하는 대로 출력이 된다. 

혹은 상수를 사용한다. 

const defaultResult = 0;

let currentResult = defaultResult;

currentResult = (currentResult + 10) * 3 / 2 - 1;

let calculationDescription =  '(' + currentResult + ' + 10) * 3 / 2 -1)'

outputResult(currentResult, calculationDescription)

다른 변수나 상수의 값으로 변수를 초기화 할 수 있다.

결과적으로 let으로 생성한 변수인 currentResults는 변경이 가능하지만 defaultResults는 변경 할 수 없다.

const defaultResult = 0;

let currentResult = defaultResult;

defaultResult = (currentResult + 10) * 3 / 2 - 1;

let calculationDescription =  '(' + currentResult + ' + 10) * 3 / 2 -1)'

outputResult(currentResult, calculationDescription)

이렇게 상수 defaultResult를 let으로 재할당 하듯이 재할당 하면

구글 크롬의 개발자 모드로 확인해보면 변수 할당 문제가 있기 때문에 0 으로 표시되는것을 알 수 있다. 

하지만 currentResult에 할당하는 것은 허용된다. 변수이기 때문이다. 단 변경은 되지 않는다.


상수에 저장되어 있는 값으로 currentResult를 초기화 했기 때문에 코드에서 은연중에 상수를 바꾸고 있는건 아닐까?

const defaultResult = 0;

let currentResult = defaultResult;

defaultResult = (currentResult + 10) * 3 / 2 - 1;

let calculationDescription =  '(' + currentResult + ' + 10) * 3 / 2 -1)'

outputResult(currentResult, calculationDescription)

let currentResult = defaultResult 부분에서 = 을 사용해서

하지만 '상수에 저장된 값'을 새로운 변수로 복사한 것이기 때문에 실제로 상수를 변경한 것이 아니다.

따라서 그 이후로 변수를 변경하면 복사본을 수정하는 것이고, 변수를 수정해도 상수 원본과 그 값은 변하지 않는다.

 

 

JUNE .

20'S LIFE IN SYDNEY and BUSAN

    이미지 맵

    Programming Study/JavaScript 다른 글

    이전 글

    다음 글