-01- Var v Let v Const

mintgranita·2024년 3월 8일

JS101

목록 보기
1/9
post-thumbnail

자바스크립트에서의 변수

자바스크립트에서 변수 선언을 하는 방법은 3가지가 있습니다. 바로 var let const인데 이 세 가지의 변수 선언은 스코프를 기준으로 두 분류로 나눌 수 있습니다.

스코프?

변수의 스코프란 어떤 변수가 유효한 범위를 말합니다. 예를 들어 A라는 변수가 있다면 A의 스코프는 A라는 변수에 접근 가능한 범위를 말합니다. var와 let과 const의 차이는 스코프가 다릅니다.

함수 스코프

function calcAge(birthYear) {
    var now = 2022;
    var age = now - birthYear
    return age
}

console.log(age);  //Reference Error

함수 스코프는 함수의 바깥이 아닌 안쪽에서만 접근 가능한 범위를 뜻합니다. var로 선언한 변수의 스코프는 함수 스코프입니다.

블록스코프

if(year >= 1981 && year =< 1996) {
   const milleniel = true
   const food = "Avocado toast"
}

console.log(milleniel) //Reference Error

블록 스코프는 블록({ })의 바깥이 아닌 안쪽에서만 접근 가능한 범위를 뜻합니다. let과 const로 선언한 변수의 스코프는 블록 스코프입니다.

호이스팅(hoisting)

*hoisting:끌어올리다.

호이스팅이란 몇 가지 타입의 변수가 선언되기도 전에 접근 가능하거나/사용 가능해지는 현상을 말합니다. 호이스팅된 변수는 변수 스코프의 최상단으로 올라가게 됩니다.


function example1() {
  console.log(notDefined); // => throws a ReferenceError
}


// 변수를 선언하가 전에 변수를 참조하는것은   
// 호이스팅 때문에 동작한다 
// 하지만 할당된 값인 true는 호이스팅 되지 않는다. 

function example2() {
  console.log(declaredButNotAssigned); // => undefined
  var declaredButNotAssigned = true;
}


// 인터프리터는 변수선언을 스코프의 최상단으로 호이스팅한다
// 그렇다면 앞의 예제를 다음과 같이 고쳐 쓸수 있다:

function example3() {
  let declaredButNotAssigned;
  console.log(declaredButNotAssigned); // => undefined
  declaredButNotAssigned = true;
}

// using const and let
function example4() {
  console.log(declaredButNotAssigned); // => throws a ReferenceError
  console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
  const declaredButNotAssigned = true;
}

let이나 const를 쓰면 호이스팅이 일어나지 않기 때문에 코드가 조금 더 예측 가능해집니다.

let vs const

const는 말 그대로 상수입니다 그렇기 때문에 어떤 변수에 한 번 값을 할당하면 그 변수에 할당한 값을 바꿀 수 없습니다.

const name = 'Harry'
console.log(name)
// Harry
name = 'Sally'
// Uncaught TypeError: Assignment to constant variable.
console.log(name)

만약 어떤 값을 나중에 바꿔야 한다면 let을 이용하면 됩니다.

// bad
var count = 1;
if (true) {
  count += 1;
}

// good, use the let.
let count = 1;
if (true) {
  count += 1;
}

결론: var를 사용하면 코드가 어떻게 동작하는지 예측하기 더 어려워 진다. 그러므로 항상 let이나 const를 쓰자.

참고자료:
JavaScript Var vs Let vs Const -Web Dev Simplified Blog-
The complete javascript course -Jonas Schmedtmann-
airbnb javascript style guide

profile
UX광인이 되고싶어요

0개의 댓글