3줄 정리

  • 애매모호한 var는 잊어라.

  • const는 상수개념의 변경되지 않는 고정값을 변수로 사용하고자 할 때 쓴다.

  • let는 const를 제외한 나머지 경우에 사용한다.


추가설명

var
변수를 선언. 추가로 동시에 값을 초기화.

let
블록 범위(scope) 지역 변수를 선언. 추가로 동시에 값을 초기화.

const
블록 범위 읽기 전용 상수를 선언.

var a;
console.log("a 값은 " + a); // "a 값은 undefined"로 로그가 남음.

console.log('b 값은 ' + b); // b 값은 undefined
var b;

console.log("c 값은 " + c); // ReferenceError 예외 던짐

let x;
console.log('x 값은 ' + x); // x 값은 undefined

console.oog('y 값은 ' + y); // ReferenceError 예외 던짐
let y;

 

var은 꼭 변수선언을 먼저하지 않아도 사용가능하다.

/*
* 1. 변수 a를 생성하지 않고 a를 호출하면 에러발생.
*/
console.log(a); // ReferenceError: a is not defined

/*
* 2. 선언되지 않은 변수 b를 먼저 호출하고 나서 선언해도 에러는 나지 않는다.
*/
console.log(b); // undefined
var b;

/*
* 3. var로 생성된 변수는 소스전체에서 접근할 수 있다.
*/
var c = 'default';
console.log(c);	// 'default'

if(true){
	c = 'modifying'
    console.log(c);	// modifying
}

console.log(c);	// modifying

 

const, let의 블록범위에 대해 추가작성할 예정임....

출처: https://sometimes-n.tistory.com/17# [종종 올리는 블로그] 출처: https://sometimes-n.tistory.com/17# [종종 올리는 블로그]

+ Recent posts