var 변수 선언의 문제점

치로·2024년 8월 21일
  • 변수를 한 번 더 선언했음에도 불구하고, 에러가 나오지 않고 각기 다른 값이 출력되는 것을 볼 수 있음. 이는 유연한 변수 선언으로 간단한 테스트에는 편리할 수 있겠으나, 코드량이 많아진다면 어디에서 어떻게 사용될지도 파악하기 힘들 뿐더러 값이 바뀔 오류가 있음
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var name = 'html';
        console.log(name);

        var name = 'javascript';
        console.log(name);
    </script>
</body>
</html>

-ES6 이후, 이를 보완하기 위해 추가된 변수 선언 방식이 let과 const

1. let과 const의 차이점

  • let은 변수에 재할당이 가능
  • const는 변수 재선언, 변수 재할당이 모두 불가능
  • 변수 선언에는 기본적으로 const를 사용하고 재할당이 필요한 경우에 한정해 let을 사용하는 것이 좋음
  • const를 사용하면 의도치 않은 재할당을 방지해주기 때문
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // SyntaxError: Identifier 'name' has already been declared (at val2.html:13:13)
        // let name = 'html';
        // console.log(name);

        let name = 'javascript';
        console.log(name);

        name = 'react';
        console.log(name);
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const name = 'html';
        console.log(name);

        // SyntaxError: Identifier 'name' has already been declared (at val2.html:13:13)
        // const name = 'javascript';
        // console.log(name);

        name = 'react';
        console.log(name);
        // TypeError: Assignment to constant variable.
        // const는 재할당 안됨
    </script>
</body>
</html>

0개의 댓글