<JS> var, let, const

Sinjae Lee·2021년 5월 13일

_**5.1.1 Use const and let

Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used.**_

출처 Google Javascript Style Guide

해당 가이드에서 보면 js 에서 변수 할당에 const, let 을 쓰고 var는 쓰지 마라고 한다. 왜??? 뭐가 다른데?

1. Scope

// let - 
{
let myname = 'Jake';
console.log(myname); // >> Jake 출력
}
console.log(myname); // >> err 메세지 출력

// var -
{
var maname = 'Gray';
console.log(maname); // >> Gray 출력
}
console.log(maname); // >> Gray 출력

2. 중복선언

let -> {block} 안에서 선언된 변수는 block 안에서만 호출 가능 => 지역변수
var -> 블록 레벨 스코프를 따르지 않고 {block} 안에서 선언된 변수도 block 밖에서 호출 가능

let abc = 123;
let abc = 456; // err 메세지 출력 
var abc = 123;
var abc = 456; // 중복 할당 허용 

let -> 중복 선언 불가능
var -> 중복 선언 가능

=> 그래서 var를 썼을때의 문제는? var를 쓰면 project 가 커졌을때 의도하지 않은 변수의 값들이 튀어나온다

3. var VS let VS const

let은 mutable / const 는 immutable
favor immutable data type always for a few reasons

  • security
  • thread safety
  • reduce human mistake
    변수 선언에는 기본적으로 const!
    ES6 라면 기본적으로 var 는 지양하자!
    재할당이 필요한 변수에 한정해 let 을 사용하자! 이때 변수의 스코프는 최대한 좁게!
    (변수를 선언하는 시점에는 재할당이 필요 할지 안할지도 미지수 나중에 가서 생각해봐도 충분)
profile
Back-end developer

0개의 댓글