JS : var, let, const?

?·2020년 8월 17일
0

What I've learned

목록 보기
3/21

javaScript의 변수 종류인 var let const에 대해서 알아보자.

var는 ES6 이전부터 사용된 javaScript의 변수이다. 여기서 잠깐 ES6에 대해서 짚고 넘어가자면 ES6ECMAscript 6의 약자로 자바스크립트 언어의 표준 중 하나이다.

ES6부터 let과 const가 추가 되었는데, var만 사용할 때의 문제점을 보완하기 위해 생긴 것이라고 보면 된다.

그러면 우선 var의 특징에 대해서 알아보자.

1. var

1) var는 function 단위의 scope를 가진다.

var hello='hello!'
function sayHello() {
  var hello='hello in function!';
  console.log(hello);
}

sayHello(); // hello in function!
console.log(hello); // hello!

위의 예시를 보면 hello라는 변수의 유효범위가 function내 라는 것을 알 수 있다.
따라서 이와 같은 경우도 가능하다. 하나의 예시를 더 살펴보자

var hello='hello';
if(true)  {
  var hello = 'hello in if';
}

console.log(hello); // hello in if

위의 예제를 보면,

if절 내부에 hello를 변수를 새로 선언했지만, var로 선언한 변수의 scope은 {}가 아닌 function이기 때문에 hello 변수가 {} 바깥에서도 변경된 것을 볼 수 있다.

2) var는 변수의 재선언이 가능하다.

    var name = 'bathingape'
    console.log(name) // bathingape

    var name = 'javascript'
    console.log(name) // javascript

위의 코드를 보면 변수를 한 번 더 선언했음에도 불구하고, 에러가 나오지 않고 각기 다른 값이 출력되는 것을 볼 수 있다.

이는 유연한 변수 선언으로 간단한 테스트에는 편리 할 수 있겠으나, 코드량이 많아 진다면 어디에서 어떻게 사용 될지도 파악하기 힘들뿐더러 값이 바뀔 수 있다는 문제가 있었다.

그래서 이러한 문제점을 보완하기 위해 추가 된 변수 선언 방식이 let 과 const 이다.

2. var VS let, const

let, const 와 var과의 가장 큰 차이점은 scope 가 {} 이라는 점이다.

const에 대한 예시를 하나 살펴보자

const hello='hello!';
{
  const hello='inner hello!'; 
  console.log(hello); // inner hello!
}
console.log(hello); // hello! 

위의 코드를 보면 괄호 안에 hello를 선언했지만, const의 scope은 괄호 블록 안이기 때문에 괄호 바깥에 hello 상수를 또 선언할 수 있다.

let도 이와 마찬가지이다.

let hello='first hello';  
{
  let hello = 'inner hello';  
  console.log(hello); // inner hello
}
console.log(hello); // first hello

3. let VS const

그렇다면 {} scope라는 공통점을 갖고 있는 let과 const의 차이점은 무엇일까?

let과 const의 차이는 immutable이다.

const는 constance의 약자이다. 한번 선언된 상수는 변수 재선언 및 재 할당이 불가능하다.

const name = 'bathingape'
   console.log(name) // bathingape

   const name = 'javascript'
   console.log(name) 
   // Uncaught SyntaxError: Identifier 'name' has already been declared

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

그러나 변수의 값을 let으로 선언하면 값의 재할당이 가능하다.

let name = 'bathingape'
    console.log(name) // bathingape

    let name = 'javascript'
    console.log(name) 
    // Uncaught SyntaxError: Identifier 'name' has already been declared

    name = 'react'
    console.log(name) //react

4. 정리

그렇다면, 어떤 변수 선언 방식을 써야할까?

변수 선언에는 기본적으로 const를 사용하고, 재할당이 필요한 경우에 한정해 let 을 사용하는 것이 좋다.

그리고 객체를 재할당하는 경우는 생각보다 흔하지 않다. const 를 사용하면 의도치 않은 재할당을 방지해 주기 때문에 보다 안전하다.

재할당이 필요한 경우에 한정해 let 을 사용한다. 이때, 변수의 스코프는 최대한 좁게 만든다.

재할당이 필요 없는 상수와 객체에는 const 를 사용한다.

profile
?

0개의 댓글