본문 바로가기

카테고리 없음

[JavaScript] const 키워드

변경 불가능한 상수를 선언할때 사용합니다.

const의 선언은 블록범위 입니다.

const는 업데이트 하거나 다시 선언할 수 없습니다.

 

const_ex01.html 파일을 다음과 같이 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>const(상수 선언)</title>
    <script>
        const PI = 3.141592;
 
        // 원의 둘레를 구해주는 함수
        function circumference(radius){
            // 블록 단위 스코드
            const PI = 3.14;
            console.log(`원주율 : ${PI}`);
            console.log(`원의 둘레 =  2 * ${PI} * ${radius} = ${2*PI*radius}`);
            return 2 * PI * radius; 
        }
        console.log(`반지름 17인 원의 둘레 : ${circumference(17)}`)
        console.log(`원주율 : ${PI}`);
        // 변경불가
        PI = 3.1415// 에러발생 : TypeError: Assignment to constant variable.
    </script>
</head>
<body>
</body>
</html>
cs

 

실행 결과 입니다.

 

다음 예제를 한번 보겠습니다. 

const 변수에 객체를 대입하고 객체의 내용을 수정해 보았습니다.

당연히 에러가 발생할 것 같지만 아닙니다. 왜 그럴까요?

객체는 참조형 변수 입니다. 주소를 가리키고 있습니다.

변수가 다른 객체를 가리킬 수 없다는 것이지 지정 주소에 저장된 값을 변경할 수 없다는 것은 아닙니다.

 

const_ex02.html 파일을 다음과 같이 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>const(상수 선언)</title>
    <script>
        const user = {
            "name" : "한사람",
            "age"  : 18,
            "gender" : false,
            toString(){
                return `${name}(${age}세, ${gender?"남자":"여자"})`;
            }
        }
        console.log(user);
        // 에러가 아님
        user.age = 22;
        
        console.log(user);
        
        // 에러발생 : TypeError: Assignment to constant variable.
        user = {}
        
    </script>
</head>
<body>
</body>
</html>
cs

 

 

실행 결과 입니다.